EditorUi.js 276 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193
  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 = /.*\.draw\.io$/.test(window.location.hostname);
  19. /**
  20. * Switch to enable PlantUML in the insert from text dialog.
  21. * NOTE: This must also be enabled on the server-side.
  22. */
  23. EditorUi.enablePlantUml = EditorUi.enableLogging;
  24. /**
  25. * https://github.com/electron/electron/issues/2288
  26. */
  27. EditorUi.isElectronApp = window != null && window.process != null &&
  28. window.process.versions != null && window.process.versions['electron'] != null;
  29. /**
  30. * Link for scratchpad help.
  31. */
  32. EditorUi.scratchpadHelpLink = 'https://desk.draw.io/support/solutions/articles/16000042367';
  33. /**
  34. * Contains the default XML for an empty diagram.
  35. */
  36. EditorUi.prototype.emptyDiagramXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
  37. /**
  38. *
  39. */
  40. EditorUi.prototype.emptyLibraryXml = '<mxlibrary>[]</mxlibrary>';
  41. /**
  42. * Sets the delay for autosave in milliseconds. Default is 2000.
  43. */
  44. EditorUi.prototype.mode = null;
  45. /**
  46. * Allows for two buttons in the sidebar footer.
  47. */
  48. EditorUi.prototype.sidebarFooterHeight = 36;
  49. /**
  50. * Specifies the default custom shape style.
  51. */
  52. 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;';
  53. /**
  54. * Broken image symbol for offline SVG.
  55. */
  56. 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"/>');
  57. /**
  58. * Specifies if img.crossOrigin is supported. This is true for all browsers except IE10 and earlier.
  59. */
  60. EditorUi.prototype.crossOriginImages = !mxClient.IS_IE;
  61. /**
  62. * Defines the maximum size for images.
  63. */
  64. EditorUi.prototype.maxBackgroundSize = 1600;
  65. /**
  66. * Defines the maximum size for images.
  67. */
  68. EditorUi.prototype.maxImageSize = 520;
  69. /**
  70. * Images above 100K should be resampled.
  71. */
  72. EditorUi.prototype.resampleThreshold = 100000;
  73. /**
  74. * Maximum allowed size for images is 1 MB.
  75. */
  76. EditorUi.prototype.maxImageBytes = 1000000;
  77. /**
  78. * Maximum size for background images is 2.5 MB.
  79. */
  80. EditorUi.prototype.maxBackgroundBytes = 2500000;
  81. /**
  82. * Holds the current file.
  83. */
  84. EditorUi.prototype.currentFile = null;
  85. /**
  86. * Specifies if PDF export should be done via print dialog. Default is
  87. * false which uses the PhantomJS backend to create the PDF.
  88. */
  89. EditorUi.prototype.printPdfExport = false;
  90. /**
  91. * Specifies if PDF export with pages is enabled.
  92. */
  93. EditorUi.prototype.pdfPageExport = true;
  94. /**
  95. * Restores app defaults for UI
  96. */
  97. EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
  98. /**
  99. * Restores app defaults for UI
  100. */
  101. EditorUi.prototype.closableScratchpad = true;
  102. /**
  103. * Specifies if PDF export with pages is enabled.
  104. */
  105. EditorUi.prototype.showCsvImport = true;
  106. /**
  107. * Capability check for canvas export
  108. */
  109. (function()
  110. {
  111. EditorUi.prototype.useCanvasForExport = false;
  112. EditorUi.prototype.jpgSupported = false;
  113. // Checks if canvas is supported
  114. try
  115. {
  116. var cnv = document.createElement('canvas');
  117. EditorUi.prototype.canvasSupported = !!(cnv.getContext && cnv.getContext('2d'));
  118. }
  119. catch (e)
  120. {
  121. // ignore
  122. }
  123. try
  124. {
  125. var canvas = document.createElement('canvas');
  126. var img = new Image();
  127. // LATER: Capability check should not be async
  128. img.onload = function()
  129. {
  130. try
  131. {
  132. var ctx = canvas.getContext('2d');
  133. ctx.drawImage(img, 0, 0);
  134. // Works in Chrome, Firefox, Edge and Opera
  135. // LATER: Fix security error caused by foreignObjects in Safari for toDataUri (tainted canvas)
  136. var result = canvas.toDataURL('image/png');
  137. EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
  138. }
  139. catch (e)
  140. {
  141. // ignore
  142. }
  143. };
  144. // Checks if SVG with foreignObject can be exported
  145. 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>';
  146. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  147. }
  148. catch (e)
  149. {
  150. // ignore
  151. }
  152. // Checks for client-side JPG support
  153. try
  154. {
  155. var canvas = document.createElement('canvas');
  156. canvas.width = canvas.height = 1;
  157. var uri = canvas.toDataURL('image/jpeg');
  158. EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
  159. }
  160. catch (e)
  161. {
  162. // ignore
  163. }
  164. })();
  165. /**
  166. * Hook for subclassers.
  167. */
  168. EditorUi.prototype.openLink = function(url, target)
  169. {
  170. // LATER: Replace this with direct calls to graph
  171. return this.editor.graph.openLink(url, target);
  172. };
  173. /**
  174. * Hook for subclassers.
  175. */
  176. EditorUi.prototype.showSplash = function(force) { };
  177. /**
  178. * Abstraction for local storage access.
  179. */
  180. EditorUi.prototype.getLocalData = function(key, fn)
  181. {
  182. fn(localStorage.getItem(key));
  183. };
  184. /**
  185. * Abstraction for local storage access.
  186. */
  187. EditorUi.prototype.setLocalData = function(key, data, fn)
  188. {
  189. localStorage.setItem(key, data);
  190. fn();
  191. };
  192. /**
  193. * Abstraction for local storage access.
  194. */
  195. EditorUi.prototype.removeLocalData = function(key, fn)
  196. {
  197. localStorage.removeItem(key)
  198. fn();
  199. };
  200. EditorUi.prototype.setMathEnabled = function(value)
  201. {
  202. this.editor.graph.mathEnabled = value;
  203. this.editor.updateGraphComponents();
  204. this.editor.graph.refresh();
  205. this.fireEvent(new mxEventObject('mathEnabledChanged'));
  206. };
  207. EditorUi.prototype.isMathEnabled = function(value)
  208. {
  209. return this.editor.graph.mathEnabled;
  210. };
  211. /**
  212. * Returns true if using application cache
  213. */
  214. EditorUi.prototype.isAppCache = function()
  215. {
  216. return (urlParams['appcache'] == '1' || this.isOfflineApp());
  217. };
  218. /**
  219. * Returns true if offline app, which isn't a defined thing
  220. */
  221. EditorUi.prototype.isOfflineApp = function()
  222. {
  223. return (urlParams['offline'] == '1');
  224. };
  225. /**
  226. * Returns true if no external comms allowed or possible
  227. */
  228. EditorUi.prototype.isOffline = function()
  229. {
  230. return this.isOfflineApp() || !navigator.onLine || urlParams['stealth'] == '1';
  231. };
  232. /**
  233. * Translates this point by the given vector.
  234. *
  235. * @param {number} dx X-coordinate of the translation.
  236. * @param {number} dy Y-coordinate of the translation.
  237. */
  238. EditorUi.prototype.createSpinner = function(x, y, size)
  239. {
  240. size = (size != null) ? size : 24;
  241. var spinner = new Spinner({
  242. lines: 12, // The number of lines to draw
  243. length: size, // The length of each line
  244. width: Math.round(size / 3), // The line thickness
  245. radius: Math.round(size / 2), // The radius of the inner circle
  246. rotate: 0, // The rotation offset
  247. color: (uiTheme == 'dark') ? '#c0c0c0' : '#000', // #rgb or #rrggbb
  248. speed: 1.5, // Rounds per second
  249. trail: 60, // Afterglow percentage
  250. shadow: false, // Whether to render a shadow
  251. hwaccel: false, // Whether to use hardware acceleration
  252. zIndex: 2e9 // The z-index (defaults to 2000000000)
  253. });
  254. // Extends spin method to include an optional label
  255. var oldSpin = spinner.spin;
  256. spinner.spin = function(container, label)
  257. {
  258. var result = false;
  259. if (!this.active)
  260. {
  261. oldSpin.call(this, container);
  262. this.active = true;
  263. if (label != null)
  264. {
  265. var status = document.createElement('div');
  266. status.style.position = 'absolute';
  267. status.style.whiteSpace = 'nowrap';
  268. status.style.background = '#4B4243';
  269. status.style.color = 'white';
  270. status.style.fontFamily = 'Helvetica, Arial';
  271. status.style.fontSize = '9pt';
  272. status.style.padding = '6px';
  273. status.style.paddingLeft = '10px';
  274. status.style.paddingRight = '10px';
  275. status.style.zIndex = 2e9;
  276. status.style.left = Math.max(0, x) + 'px';
  277. status.style.top = Math.max(0, y + 70) + 'px';
  278. mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
  279. mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
  280. if (uiTheme != 'dark')
  281. {
  282. mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
  283. }
  284. status.innerHTML = label + '...';
  285. container.appendChild(status);
  286. spinner.status = status;
  287. // Centers the label in older IE versions
  288. if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
  289. {
  290. status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
  291. status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
  292. }
  293. }
  294. // Pause returns a function to resume the spinner
  295. this.pause = mxUtils.bind(this, function()
  296. {
  297. var fn = function() { };
  298. if (this.active)
  299. {
  300. fn = mxUtils.bind(this, function()
  301. {
  302. this.spin(container, label);
  303. });
  304. }
  305. this.stop();
  306. return fn;
  307. });
  308. result = true;
  309. }
  310. return result;
  311. };
  312. // Extends stop method to remove the optional label
  313. var oldStop = spinner.stop;
  314. spinner.stop = function()
  315. {
  316. oldStop.call(this);
  317. this.active = false;
  318. if (spinner.status != null)
  319. {
  320. spinner.status.parentNode.removeChild(spinner.status);
  321. spinner.status = null;
  322. }
  323. };
  324. spinner.pause = function()
  325. {
  326. return function() {};
  327. };
  328. return spinner;
  329. };
  330. /**
  331. * Static method for pasing PNG files.
  332. */
  333. EditorUi.parsePng = function(f, fn, error)
  334. {
  335. var pos = 0;
  336. function fread(d, count)
  337. {
  338. var start = pos;
  339. pos += count;
  340. return d.substring(start, pos);
  341. };
  342. // Reads unsigned long 32 bit big endian
  343. function _freadint(d)
  344. {
  345. var bytes = fread(d, 4);
  346. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  347. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  348. };
  349. // Checks signature
  350. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  351. {
  352. if (error != null)
  353. {
  354. error();
  355. }
  356. return;
  357. }
  358. // Reads header chunk
  359. fread(f,4);
  360. if (fread(f,4) != 'IHDR')
  361. {
  362. if (error != null)
  363. {
  364. error();
  365. }
  366. return;
  367. }
  368. fread(f, 17);
  369. do
  370. {
  371. var n = _freadint(f);
  372. var type = fread(f,4);
  373. if (fn != null)
  374. {
  375. if (fn(pos - 8, type, n))
  376. {
  377. break;
  378. }
  379. }
  380. value = fread(f,n);
  381. fread(f,4);
  382. if (type == 'IEND')
  383. {
  384. break;
  385. }
  386. }
  387. while (n);
  388. };
  389. /**
  390. * Returns true if the given string contains a compatible graph model.
  391. */
  392. EditorUi.prototype.isCompatibleString = function(data)
  393. {
  394. try
  395. {
  396. var doc = mxUtils.parseXml(data);
  397. var node = this.editor.extractGraphModel(doc.documentElement, true);
  398. return node != null && node.getElementsByTagName('parsererror').length == 0;
  399. }
  400. catch (e)
  401. {
  402. // ignore
  403. }
  404. return false;
  405. };
  406. /**
  407. * Extracts the mxfile from the given HTML data from a data transfer event.
  408. */
  409. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  410. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  411. {
  412. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  413. if (result == null)
  414. {
  415. try
  416. {
  417. var idx = data.indexOf('&lt;mxfile ');
  418. if (idx >= 0)
  419. {
  420. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  421. if (idx2 > idx)
  422. {
  423. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  424. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  425. }
  426. }
  427. else
  428. {
  429. // Gets compressed data from mxgraph element in HTML document
  430. var doc = mxUtils.parseXml(data);
  431. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  432. result = (node != null) ? mxUtils.getXml(node) : '';
  433. }
  434. }
  435. catch (e)
  436. {
  437. // ignore
  438. }
  439. }
  440. return result;
  441. };
  442. /**
  443. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  444. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  445. */
  446. EditorUi.prototype.validateFileData = function(data)
  447. {
  448. if (data != null && data.length > 0)
  449. {
  450. var index = data.indexOf('<meta charset="utf-8">');
  451. if (index >= 0)
  452. {
  453. var replaceString = '<meta charset="utf-8"/>';
  454. var replaceStrLen = replaceString.length;
  455. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  456. }
  457. }
  458. return data;
  459. };
  460. /**
  461. *
  462. */
  463. EditorUi.prototype.replaceFileData = function(data)
  464. {
  465. data = this.validateFileData(data);
  466. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  467. // Some nodes must be extracted here to find the mxfile node
  468. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  469. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  470. if (tmp != null)
  471. {
  472. node = tmp;
  473. }
  474. if (node != null)
  475. {
  476. var graph = this.editor.graph;
  477. graph.model.beginUpdate();
  478. try
  479. {
  480. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  481. var nodes = node.getElementsByTagName('diagram');
  482. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  483. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  484. {
  485. this.fileNode = node;
  486. this.pages = (this.pages != null) ? this.pages : [];
  487. // Wraps page nodes
  488. for (var i = nodes.length - 1; i >= 0; i--)
  489. {
  490. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  491. // Checks for invalid page names
  492. if (page.getName() == null)
  493. {
  494. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  495. }
  496. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  497. }
  498. }
  499. else
  500. {
  501. // Creates tabbed file structure if enforced by URL
  502. if (urlParams['pages'] != '0' && this.fileNode == null)
  503. {
  504. this.fileNode = node.ownerDocument.createElement('mxfile');
  505. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  506. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  507. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  508. }
  509. // Avoids scroll offset when switching page
  510. this.editor.setGraphXml(node);
  511. // Avoids duplicate parsing of the XML stored in the node
  512. if (this.currentPage != null)
  513. {
  514. this.currentPage.root = this.editor.graph.model.root;
  515. }
  516. }
  517. if (oldPages != null)
  518. {
  519. for (var i = 0; i < oldPages.length; i++)
  520. {
  521. graph.model.execute(new ChangePage(this, oldPages[i], null));
  522. }
  523. }
  524. }
  525. finally
  526. {
  527. graph.model.endUpdate();
  528. }
  529. }
  530. };
  531. /**
  532. * Translates this point by the given vector.
  533. *
  534. * @param {number} dx X-coordinate of the translation.
  535. * @param {number} dy Y-coordinate of the translation.
  536. */
  537. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  538. {
  539. graph = (graph != null) ? graph : this.editor.graph;
  540. forceXml = (forceXml != null) ? forceXml : false;
  541. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  542. var editLink = null;
  543. var redirect = null;
  544. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  545. {
  546. editLink = '_blank';
  547. }
  548. else
  549. {
  550. editLink = url;
  551. redirect = editLink;
  552. }
  553. if (node == null)
  554. {
  555. return '';
  556. }
  557. else
  558. {
  559. var fileNode = node;
  560. // Ignores case for possible HTML or XML nodes
  561. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  562. {
  563. // Removes control chars in input for correct roundtrip check
  564. var text = graph.zapGremlins(mxUtils.getXml(node));
  565. var data = graph.compress(text);
  566. // Fallback to plain XML for invalid compression
  567. // TODO: Remove this fallback with active pages
  568. if (graph.decompress(data) != text)
  569. {
  570. return text;
  571. }
  572. else
  573. {
  574. var diagramNode = node.ownerDocument.createElement('diagram');
  575. mxUtils.setTextContent(diagramNode, data);
  576. fileNode = node.ownerDocument.createElement('mxfile');
  577. fileNode.appendChild(diagramNode);
  578. }
  579. }
  580. if (!compact)
  581. {
  582. fileNode.setAttribute('userAgent', navigator.userAgent);
  583. fileNode.setAttribute('version', EditorUi.VERSION);
  584. fileNode.setAttribute('editor', 'www.draw.io');
  585. var md = (file != null) ? file.getMode() : this.mode;
  586. if (md != null)
  587. {
  588. fileNode.setAttribute('type', md);
  589. }
  590. }
  591. else
  592. {
  593. fileNode = fileNode.cloneNode(true);
  594. fileNode.removeAttribute('userAgent');
  595. fileNode.removeAttribute('version');
  596. fileNode.removeAttribute('editor');
  597. fileNode.removeAttribute('type');
  598. }
  599. var xml = mxUtils.getXml(fileNode);
  600. // Writes the file as an embedded HTML file
  601. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  602. {
  603. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  604. }
  605. // Maps the XML data to the content attribute in the SVG node
  606. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  607. {
  608. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  609. {
  610. url = null;
  611. }
  612. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  613. }
  614. return xml;
  615. }
  616. };
  617. /**
  618. * Translates this point by the given vector.
  619. *
  620. * @param {number} dx X-coordinate of the translation.
  621. * @param {number} dy Y-coordinate of the translation.
  622. */
  623. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  624. {
  625. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  626. currentPage = (currentPage != null) ? currentPage : false;
  627. var node = this.editor.getGraphXml(ignoreSelection);
  628. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  629. {
  630. var data = this.editor.graph.compress(this.editor.graph.zapGremlins(mxUtils.getXml(node)));
  631. mxUtils.setTextContent(this.currentPage.node, data);
  632. node = this.fileNode.cloneNode(false);
  633. if (currentPage)
  634. {
  635. node.appendChild(this.currentPage.node);
  636. }
  637. else
  638. {
  639. // Restores order of pages
  640. for (var i = 0; i < this.pages.length; i++)
  641. {
  642. var mapping = this.pages[i].mapping;
  643. // Updates XML of all pages for realtime
  644. if (this.currentPage != this.pages[i] && mapping != null && mapping.needsUpdate)
  645. {
  646. var enc = new mxCodec(mxUtils.createXmlDocument());
  647. var temp = enc.encode(mapping.graphModel);
  648. // Uses the graph state from the realtime model
  649. mapping.writeRealtimeToNode(temp);
  650. var data = this.editor.graph.compress(this.editor.graph.zapGremlins(mxUtils.getXml(temp)));
  651. mxUtils.setTextContent(this.pages[i].node, data);
  652. // Marks the page as up-to-date
  653. mapping.needsUpdate = false;
  654. }
  655. node.appendChild(this.pages[i].node);
  656. }
  657. }
  658. }
  659. return node;
  660. };
  661. /**
  662. * Translates this point by the given vector.
  663. *
  664. * @param {number} dx X-coordinate of the translation.
  665. * @param {number} dy Y-coordinate of the translation.
  666. */
  667. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file)
  668. {
  669. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  670. currentPage = (currentPage != null) ? currentPage : false;
  671. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  672. file = (file != null) ? file : this.getCurrentFile();
  673. var graph = this.editor.graph;
  674. // Exports SVG for first page while other page is visible by creating a graph
  675. // LATER: Add caching for the graph or SVG while not on first page
  676. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  677. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  678. {
  679. graph = this.createTemporaryGraph(graph.getStylesheet());
  680. var graphGetGlobalVariable = graph.getGlobalVariable;
  681. var page = this.pages[0];
  682. graph.getGlobalVariable = function(name)
  683. {
  684. if (name == 'page')
  685. {
  686. return page.getName();
  687. }
  688. else if (name == 'pagenumber')
  689. {
  690. return 1;
  691. }
  692. return graphGetGlobalVariable.apply(this, arguments);
  693. };
  694. document.body.appendChild(graph.container);
  695. graph.model.setRoot(page.root);
  696. }
  697. var result = this.createFileData(node, graph, file, window.location.href,
  698. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  699. // Removes temporary graph from DOM
  700. if (graph != this.editor.graph)
  701. {
  702. graph.container.parentNode.removeChild(graph.container);
  703. }
  704. return result;
  705. };
  706. /**
  707. *
  708. */
  709. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  710. {
  711. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  712. var bg = null;
  713. var js = 'https://www.draw.io/js/embed-static.min.js';
  714. // LATER: Merge common code with EmbedDialog
  715. if (graph != null)
  716. {
  717. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  718. var scale = graph.view.scale;
  719. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  720. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  721. bg = graph.background;
  722. // Embed script only used if no redirect
  723. if (redirect == null)
  724. {
  725. var s = this.getBasenames().join(';');
  726. if (s.length > 0)
  727. {
  728. js = 'https://www.draw.io/embed.js?s=' + s;
  729. }
  730. }
  731. // Adds embed attributes
  732. node.setAttribute('x0', x0);
  733. node.setAttribute('y0', y0);
  734. }
  735. if (node != null)
  736. {
  737. node.setAttribute('pan', '1');
  738. node.setAttribute('zoom', '1');
  739. node.setAttribute('resize', '0');
  740. node.setAttribute('fit', '0');
  741. node.setAttribute('border', '20');
  742. // Hidden attributes
  743. node.setAttribute('links', '1');
  744. if (editLink != null)
  745. {
  746. node.setAttribute('edit', editLink);
  747. }
  748. }
  749. // Makes XHTML compatible
  750. if (redirect != null)
  751. {
  752. redirect = redirect.replace(/&/g, '&amp;');
  753. }
  754. // Removes control chars in input for correct roundtrip check
  755. var text = (node != null) ? this.editor.graph.zapGremlins(mxUtils.getXml(node)) : '';
  756. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  757. // embed clients that rely on this format. HTML files and export use getHtml2.
  758. var data = this.editor.graph.compress(text);
  759. // Fallback to URI encoded XML for invalid compression
  760. if (this.editor.graph.decompress(data) != text)
  761. {
  762. data = encodeURIComponent(text);
  763. }
  764. var style = 'position:relative;overflow:auto;width:100%;';
  765. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  766. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  767. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  768. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  769. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  770. '</head>\n<body' +
  771. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  772. '\n<div class="mxgraph" style="' + style + '">\n' +
  773. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  774. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  775. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  776. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  777. 'src="https://www.draw.io/images/drawlogo128.png"/></a>') +
  778. '\n</body>\n</html>\n';
  779. };
  780. /**
  781. * Same as above but using the new embed code.
  782. */
  783. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  784. {
  785. var bg = null;
  786. var js = 'https://www.draw.io/js/viewer.min.js';
  787. var s = '';
  788. // Makes XHTML compatible
  789. if (redirect != null)
  790. {
  791. redirect = redirect.replace(/&/g, '&amp;');
  792. }
  793. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  794. xml: this.editor.graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  795. if (this.pages != null && this.currentPage != null)
  796. {
  797. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  798. }
  799. var style = 'max-width:100%;border:1px solid transparent;';
  800. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  801. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  802. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  803. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  804. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  805. '<meta charset="utf-8"/>\n</head>\n<body>' +
  806. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  807. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  808. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  809. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  810. 'src="https://www.draw.io/images/drawlogo128.png"/></a>') +
  811. '\n</body>\n</html>\n';
  812. };
  813. /**
  814. *
  815. */
  816. EditorUi.prototype.setFileData = function(data)
  817. {
  818. data = this.validateFileData(data);
  819. this.currentPage = null;
  820. this.fileNode = null;
  821. this.pages = null;
  822. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  823. // Some nodes must be extracted here to find the mxfile node
  824. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  825. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  826. if (tmp != null)
  827. {
  828. node = tmp;
  829. }
  830. if (node != null && node.nodeName == 'mxfile')
  831. {
  832. var nodes = node.getElementsByTagName('diagram');
  833. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  834. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  835. {
  836. this.fileNode = node;
  837. this.pages = [];
  838. // Wraps page nodes
  839. for (var i = 0; i < nodes.length; i++)
  840. {
  841. var page = new DiagramPage(nodes[i]);
  842. // Checks for invalid page names
  843. if (page.getName() == null)
  844. {
  845. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  846. }
  847. this.pages.push(page);
  848. }
  849. this.currentPage = this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  850. node = this.currentPage.node;
  851. }
  852. }
  853. // Creates tabbed file structure if enforced by URL
  854. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  855. {
  856. this.fileNode = node.ownerDocument.createElement('mxfile');
  857. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  858. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  859. this.pages = [this.currentPage];
  860. }
  861. // Avoids scroll offset when switching page
  862. this.editor.setGraphXml(node);
  863. // Avoids duplicate parsing of the XML stored in the node
  864. if (this.currentPage != null)
  865. {
  866. this.currentPage.root = this.editor.graph.model.root;
  867. }
  868. };
  869. /**
  870. * Translates this point by the given vector.
  871. *
  872. * @param {number} dx X-coordinate of the translation.
  873. * @param {number} dy Y-coordinate of the translation.
  874. */
  875. EditorUi.prototype.getBaseFilename = function()
  876. {
  877. var file = this.getCurrentFile();
  878. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  879. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
  880. /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename))
  881. {
  882. basename = basename.substring(0, basename.lastIndexOf('.'));
  883. }
  884. return basename;
  885. };
  886. /**
  887. * Translates this point by the given vector.
  888. *
  889. * @param {number} dx X-coordinate of the translation.
  890. * @param {number} dy Y-coordinate of the translation.
  891. */
  892. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible)
  893. {
  894. try
  895. {
  896. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  897. var basename = this.getBaseFilename();
  898. var filename = basename + '.' + format;
  899. if (format == 'xml')
  900. {
  901. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  902. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  903. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  904. this.saveData(filename, format, data, 'text/xml');
  905. }
  906. else if (format == 'html')
  907. {
  908. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  909. this.saveData(filename, format, data, 'text/html');
  910. }
  911. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  912. {
  913. var svg = null;
  914. var saveSvg = mxUtils.bind(this, function(data)
  915. {
  916. if (data.length <= MAX_REQUEST_SIZE)
  917. {
  918. this.saveData(filename, 'svg', data, 'image/svg+xml');
  919. }
  920. else
  921. {
  922. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  923. {
  924. mxUtils.popup(svg);
  925. }));
  926. }
  927. });
  928. if (format == 'svg')
  929. {
  930. var bg = this.editor.graph.background;
  931. if (bg == mxConstants.NONE)
  932. {
  933. bg = null;
  934. }
  935. // Sets or disables alternate text for foreignObjects. Disabling is needed
  936. // because PhantomJS seems to ignore switch statements and paint all text.
  937. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  938. if (addShadow)
  939. {
  940. this.editor.graph.addSvgShadow(svgRoot);
  941. }
  942. // Embeds the images in the SVG output (async)
  943. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  944. {
  945. this.spinner.stop();
  946. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  947. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  948. mxUtils.getXml(svgRoot2));
  949. })));
  950. }
  951. else
  952. {
  953. filename = basename + '.svg';
  954. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  955. {
  956. this.spinner.stop();
  957. saveSvg(svg);
  958. }), ignoreSelection);
  959. }
  960. }
  961. else
  962. {
  963. if (format == 'xmlpng')
  964. {
  965. filename = basename + '.png';
  966. }
  967. else if (format == 'jpeg')
  968. {
  969. filename = basename + '.jpg';
  970. }
  971. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  972. {
  973. try
  974. {
  975. var prev = this.editor.graph.pageVisible;
  976. if (pageVisible != null)
  977. {
  978. this.editor.graph.pageVisible = pageVisible;
  979. }
  980. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64);
  981. this.editor.graph.pageVisible = prev;
  982. return req;
  983. }
  984. catch (e)
  985. {
  986. this.handleError(e);
  987. }
  988. }));
  989. }
  990. }
  991. catch (e)
  992. {
  993. this.handleError(e);
  994. }
  995. };
  996. /**
  997. * Translates this point by the given vector.
  998. *
  999. * @param {number} dx X-coordinate of the translation.
  1000. * @param {number} dy Y-coordinate of the translation.
  1001. */
  1002. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64)
  1003. {
  1004. var bounds = this.editor.graph.getGraphBounds();
  1005. // Exports only current page for PDF since it does not contain file data, but for
  1006. // the other formats with XML included we need to send the complete data and use
  1007. // the from/to URL parameters to specify the page to be exported.
  1008. var data = this.getFileData(true, null, null, null, ignoreSelection, format != 'xmlpng');
  1009. var range = '';
  1010. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  1011. {
  1012. throw {message: mxResources.get('drawingTooLarge')};
  1013. }
  1014. var embed = '0';
  1015. if (format == 'xmlpng')
  1016. {
  1017. embed = '1';
  1018. format = 'png';
  1019. // Finds the current page number
  1020. if (this.pages != null && this.currentPage != null)
  1021. {
  1022. for (var i = 0; i < this.pages.length; i++)
  1023. {
  1024. if (this.pages[i] == this.currentPage)
  1025. {
  1026. range = '&from=' + i;
  1027. break;
  1028. }
  1029. }
  1030. }
  1031. }
  1032. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range +
  1033. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1034. encodeURIComponent(data) + ((filename != null) ?
  1035. '&filename=' + encodeURIComponent(filename) : ''));
  1036. };
  1037. /**
  1038. * Translates this point by the given vector.
  1039. *
  1040. * @param {number} dx X-coordinate of the translation.
  1041. * @param {number} dy Y-coordinate of the translation.
  1042. */
  1043. EditorUi.prototype.setMode = function(mode, remember)
  1044. {
  1045. this.mode = mode;
  1046. };
  1047. /**
  1048. * Translates this point by the given vector.
  1049. *
  1050. * @param {number} dx X-coordinate of the translation.
  1051. * @param {number} dy Y-coordinate of the translation.
  1052. */
  1053. EditorUi.prototype.fileLoaded = function(file)
  1054. {
  1055. var result = false;
  1056. this.hideDialog();
  1057. var oldFile = this.getCurrentFile();
  1058. this.setCurrentFile(null);
  1059. if (oldFile != null)
  1060. {
  1061. oldFile.removeListener(this.descriptorChangedListener);
  1062. oldFile.close();
  1063. }
  1064. this.editor.graph.model.clear();
  1065. this.editor.undoManager.clear();
  1066. var noFile = mxUtils.bind(this, function()
  1067. {
  1068. this.setGraphEnabled(false);
  1069. this.setCurrentFile(null);
  1070. // Keeps initial title if no file existed before
  1071. if (oldFile != null)
  1072. {
  1073. this.updateDocumentTitle();
  1074. }
  1075. // File might have been loaded halfway
  1076. this.editor.graph.model.clear();
  1077. this.editor.undoManager.clear();
  1078. this.setBackgroundImage(null);
  1079. // Avoids empty hash with no value
  1080. if (window.location.hash != null && window.location.hash.length > 0)
  1081. {
  1082. window.location.hash = '';
  1083. }
  1084. if (this.fname != null)
  1085. {
  1086. this.fnameWrapper.style.display = 'none';
  1087. this.fname.innerHTML = '';
  1088. this.fname.setAttribute('title', mxResources.get('rename'));
  1089. }
  1090. this.updateUi();
  1091. this.showSplash();
  1092. });
  1093. if (file != null)
  1094. {
  1095. try
  1096. {
  1097. // Order is significant, current file needed for correct
  1098. // file format for initial save after starting realtime
  1099. this.setCurrentFile(file);
  1100. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1101. file.addListener('contentChanged', this.descriptorChangedListener);
  1102. file.open();
  1103. // DescriptorChanged updates the enabled state of the graph
  1104. this.setGraphEnabled(true);
  1105. this.setMode(file.getMode());
  1106. this.editor.undoManager.clear();
  1107. this.descriptorChanged();
  1108. this.updateUi();
  1109. // Realtime files have a valid status message
  1110. if (file.realtime == null)
  1111. {
  1112. if (!file.isEditable())
  1113. {
  1114. this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
  1115. mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
  1116. }
  1117. else
  1118. {
  1119. this.editor.setStatus('');
  1120. }
  1121. }
  1122. if (!this.editor.isChromelessView() || this.editor.editable)
  1123. {
  1124. this.editor.graph.selectUnlockedLayer();
  1125. this.showLayersDialog();
  1126. this.restoreLibraries();
  1127. // Workaround for no initial focus in FF
  1128. if (window.self !== window.top)
  1129. {
  1130. window.focus();
  1131. }
  1132. }
  1133. else if (this.editor.graph.isLightboxView())
  1134. {
  1135. this.lightboxFit();
  1136. }
  1137. if (this.chromelessResize)
  1138. {
  1139. this.chromelessResize();
  1140. }
  1141. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1142. result = true;
  1143. if (!this.isOffline() && file.getMode() != null)
  1144. {
  1145. this.logEvent({category: 'File', action: 'open', label: file.getMode()})
  1146. }
  1147. if (this.mode == file.getMode() && file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1148. {
  1149. try
  1150. {
  1151. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1152. }
  1153. catch (e)
  1154. {
  1155. // ignore
  1156. }
  1157. }
  1158. try
  1159. {
  1160. mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
  1161. mxSettings.save();
  1162. }
  1163. catch (e)
  1164. {
  1165. // ignore
  1166. }
  1167. }
  1168. catch (e)
  1169. {
  1170. // Makes sure the file does not save the invalid UI model and overwrites anything important
  1171. if (window.console != null)
  1172. {
  1173. console.log('error in fileLoaded:', file, e);
  1174. }
  1175. if (EditorUi.enableLogging && !this.isOffline())
  1176. {
  1177. try
  1178. {
  1179. var img = new Image();
  1180. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  1181. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  1182. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  1183. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  1184. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  1185. }
  1186. catch (e)
  1187. {
  1188. // ignore
  1189. }
  1190. }
  1191. // Asynchronous handling of errors
  1192. this.handleError(e, mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
  1193. {
  1194. // Removes URL parameter and reloads the page
  1195. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  1196. {
  1197. window.location.search = this.getSearch(['url']);
  1198. }
  1199. else if (oldFile != null)
  1200. {
  1201. // Workaround for close realtime model is to reload the file from scratch
  1202. if (oldFile.constructor == DriveFile)
  1203. {
  1204. this.loadFile(oldFile.getHash());
  1205. }
  1206. else
  1207. {
  1208. this.fileLoaded(oldFile);
  1209. }
  1210. }
  1211. else
  1212. {
  1213. noFile();
  1214. }
  1215. }));
  1216. }
  1217. }
  1218. else
  1219. {
  1220. noFile();
  1221. }
  1222. return result;
  1223. };
  1224. /**
  1225. * Adds empty implementation
  1226. */
  1227. EditorUi.prototype.descriptorChanged = function()
  1228. {
  1229. // empty
  1230. };
  1231. /**
  1232. * Updates action states depending on the selection.
  1233. */
  1234. EditorUi.prototype.logEvent = function(data)
  1235. {
  1236. if (EditorUi.enableLogging)
  1237. {
  1238. try
  1239. {
  1240. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  1241. var img = new Image();
  1242. img.src = logDomain + '/images/1x1.png?' +
  1243. 'v=' + encodeURIComponent(EditorUi.VERSION) +
  1244. ((data != null) ? '&data=' + encodeURIComponent(JSON.stringify(data)) : '');
  1245. }
  1246. catch (e)
  1247. {
  1248. // ignore
  1249. }
  1250. }
  1251. };
  1252. /**
  1253. * Updates action states depending on the selection.
  1254. */
  1255. EditorUi.prototype.restoreLibraries = function()
  1256. {
  1257. // hook for subclassers
  1258. };
  1259. /**
  1260. * Translates this point by the given vector.
  1261. *
  1262. * @param {number} dx X-coordinate of the translation.
  1263. * @param {number} dy Y-coordinate of the translation.
  1264. */
  1265. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn)
  1266. {
  1267. // hook for subclassers
  1268. };
  1269. /**
  1270. *
  1271. */
  1272. EditorUi.prototype.isScratchpadEnabled = function()
  1273. {
  1274. return isLocalStorage || mxClient.IS_CHROMEAPP;
  1275. };
  1276. /**
  1277. * Shows or hides the scratchpad library.
  1278. */
  1279. EditorUi.prototype.toggleScratchpad = function()
  1280. {
  1281. if (this.isScratchpadEnabled())
  1282. {
  1283. if (this.scratchpad == null)
  1284. {
  1285. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  1286. {
  1287. if (xml == null)
  1288. {
  1289. xml = this.emptyLibraryXml;
  1290. }
  1291. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  1292. }));
  1293. }
  1294. else
  1295. {
  1296. this.closeLibrary(this.scratchpad);
  1297. }
  1298. }
  1299. };
  1300. /**
  1301. * Translates this point by the given vector.
  1302. *
  1303. * @param {number} dx X-coordinate of the translation.
  1304. * @param {number} dy Y-coordinate of the translation.
  1305. */
  1306. EditorUi.prototype.createLibraryDataFromImages = function(images)
  1307. {
  1308. var doc = mxUtils.createXmlDocument();
  1309. var library = doc.createElement('mxlibrary');
  1310. mxUtils.setTextContent(library, JSON.stringify(images));
  1311. doc.appendChild(library);
  1312. return mxUtils.getXml(doc);
  1313. };
  1314. /**
  1315. * Translates this point by the given vector.
  1316. *
  1317. * @param {number} dx X-coordinate of the translation.
  1318. * @param {number} dy Y-coordinate of the translation.
  1319. */
  1320. EditorUi.prototype.closeLibrary = function(file)
  1321. {
  1322. if (file != null)
  1323. {
  1324. this.removeLibrarySidebar(file.getHash());
  1325. if (file.constructor != LocalLibrary)
  1326. {
  1327. mxSettings.removeCustomLibrary(file.getHash());
  1328. }
  1329. if (file.title == '.scratchpad')
  1330. {
  1331. this.scratchpad = null;
  1332. }
  1333. }
  1334. };
  1335. /**
  1336. * Translates this point by the given vector.
  1337. *
  1338. * @param {number} dx X-coordinate of the translation.
  1339. * @param {number} dy Y-coordinate of the translation.
  1340. */
  1341. EditorUi.prototype.removeLibrarySidebar = function(id)
  1342. {
  1343. var elts = this.sidebar.palettes[id];
  1344. if (elts != null)
  1345. {
  1346. for (var i = 0; i < elts.length; i++)
  1347. {
  1348. elts[i].parentNode.removeChild(elts[i]);
  1349. }
  1350. delete this.sidebar.palettes[id];
  1351. }
  1352. };
  1353. /**
  1354. * Changes the position of the library in the sidebar
  1355. */
  1356. EditorUi.prototype.repositionLibrary = function(nextChild)
  1357. {
  1358. var c = this.sidebar.container;
  1359. if (nextChild == null)
  1360. {
  1361. var elts = this.sidebar.palettes['L.scratchpad'];
  1362. if (elts == null)
  1363. {
  1364. elts = this.sidebar.palettes['search'];
  1365. }
  1366. if (elts != null)
  1367. {
  1368. nextChild = elts[elts.length - 1].nextSibling;
  1369. }
  1370. }
  1371. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  1372. var content = c.lastChild;
  1373. var title = content.previousSibling;
  1374. c.insertBefore(content, nextChild);
  1375. c.insertBefore(title, content);
  1376. }
  1377. /**
  1378. * Translates this point by the given vector.
  1379. *
  1380. * @param {number} dx X-coordinate of the translation.
  1381. * @param {number} dy Y-coordinate of the translation.
  1382. */
  1383. EditorUi.prototype.loadLibrary = function(file)
  1384. {
  1385. var doc = mxUtils.parseXml(file.getData());
  1386. if (doc.documentElement.nodeName == 'mxlibrary')
  1387. {
  1388. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  1389. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  1390. }
  1391. else
  1392. {
  1393. throw {message: mxResources.get('notALibraryFile')};
  1394. }
  1395. };
  1396. /**
  1397. * Translates this point by the given vector.
  1398. *
  1399. * @param {number} dx X-coordinate of the translation.
  1400. * @param {number} dy Y-coordinate of the translation.
  1401. */
  1402. EditorUi.prototype.getLibraryStorageHint = function(file)
  1403. {
  1404. return '';
  1405. };
  1406. /**
  1407. * Translates this point by the given vector.
  1408. *
  1409. * @param {number} dx X-coordinate of the translation.
  1410. * @param {number} dy Y-coordinate of the translation.
  1411. */
  1412. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  1413. {
  1414. if (this.sidebar == null)
  1415. {
  1416. return;
  1417. }
  1418. if (file.constructor != LocalLibrary)
  1419. {
  1420. mxSettings.addCustomLibrary(file.getHash());
  1421. }
  1422. if (file.title == '.scratchpad')
  1423. {
  1424. this.scratchpad = file;
  1425. }
  1426. var elts = this.sidebar.palettes[file.getHash()];
  1427. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  1428. // Removes existing sidebar entry for this library
  1429. this.removeLibrarySidebar(file.getHash());
  1430. var dropTarget = null;
  1431. var addImages = mxUtils.bind(this, function(imgs, content)
  1432. {
  1433. if (imgs.length == 0 && file.isEditable())
  1434. {
  1435. if (dropTarget == null)
  1436. {
  1437. dropTarget = document.createElement('div');
  1438. mxUtils.setPrefixedStyle(dropTarget.style, 'borderRadius', '6px');
  1439. dropTarget.style.border = '3px dotted lightGray';
  1440. dropTarget.style.textAlign = 'center';
  1441. dropTarget.style.padding = '8px';
  1442. dropTarget.style.color = '#B3B3B3';
  1443. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  1444. }
  1445. content.appendChild(dropTarget);
  1446. }
  1447. else
  1448. {
  1449. for (var i = 0; i < imgs.length; i++)
  1450. {
  1451. var img = imgs[i];
  1452. var data = img.data;
  1453. if (data != null)
  1454. {
  1455. data = this.convertDataUri(data);
  1456. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  1457. if (img.aspect == 'fixed')
  1458. {
  1459. s += 'aspect=fixed;'
  1460. }
  1461. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  1462. data, img.w, img.h, '', img.title || '', false, false, true));
  1463. }
  1464. else if (img.xml != null)
  1465. {
  1466. var cells = this.stringToCells(this.editor.graph.decompress(img.xml));
  1467. if (cells.length > 0)
  1468. {
  1469. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  1470. cells, img.w, img.h, img.title || '', true, false, true));
  1471. }
  1472. }
  1473. }
  1474. }
  1475. });
  1476. // Adds entries to search index
  1477. // KNOWN: Existing entries are not replaced after edit of custom library
  1478. if (this.sidebar != null && images != null)
  1479. {
  1480. for (var i = 0; i < images.length; i++)
  1481. {
  1482. (mxUtils.bind(this, function(img)
  1483. {
  1484. var data = img.data;
  1485. if (data != null && img.title != null)
  1486. {
  1487. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  1488. {
  1489. data = this.convertDataUri(data);
  1490. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  1491. if (img.aspect == 'fixed')
  1492. {
  1493. s += 'aspect=fixed;'
  1494. }
  1495. return this.sidebar.createVertexTemplate(s + 'image=' +
  1496. data, img.w, img.h, '', img.title || '', false, false, true)
  1497. }));
  1498. }
  1499. else if (img.xml != null && img.title != null)
  1500. {
  1501. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  1502. {
  1503. var cells = this.stringToCells(this.editor.graph.decompress(img.xml));
  1504. return this.sidebar.createVertexTemplateFromCells(
  1505. cells, img.w, img.h, img.title || '', true, false, true);
  1506. }));
  1507. }
  1508. }))(images[i]);
  1509. }
  1510. }
  1511. // Adds new sidebar entry for this library
  1512. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  1513. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  1514. {
  1515. addImages(images, content);
  1516. }));
  1517. this.repositionLibrary(nextSibling);
  1518. // Adds tooltip for backend
  1519. var title = contentDiv.parentNode.previousSibling;
  1520. var tip = title.getAttribute('title');
  1521. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  1522. {
  1523. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  1524. }
  1525. var buttons = document.createElement('div');
  1526. buttons.style.position = 'absolute';
  1527. buttons.style.right = '0px';
  1528. buttons.style.top = '0px';
  1529. buttons.style.padding = '8px'
  1530. // Workaround for CSS error in IE8 (standards and quirks)
  1531. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  1532. {
  1533. buttons.style.backgroundColor = 'inherit';
  1534. }
  1535. title.style.position = 'relative';
  1536. var btnWidth = 18;
  1537. var btn = document.createElement('img');
  1538. btn.setAttribute('src', Dialog.prototype.closeImage);
  1539. btn.setAttribute('title', mxResources.get('close'));
  1540. btn.setAttribute('valign', 'absmiddle');
  1541. btn.setAttribute('border', '0');
  1542. btn.style.margin = '0 3px';
  1543. var saveBtn = null;
  1544. if (file.title != '.scratchpad' || this.closableScratchpad)
  1545. {
  1546. buttons.appendChild(btn);
  1547. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  1548. {
  1549. // Workaround for close after any button click in IE8/quirks
  1550. if (!mxEvent.isConsumed(evt))
  1551. {
  1552. var fn = mxUtils.bind(this, function()
  1553. {
  1554. this.closeLibrary(file);
  1555. });
  1556. if (saveBtn != null)
  1557. {
  1558. this.confirm(mxResources.get('allChangesLost'), null, fn,
  1559. mxResources.get('cancel'), mxResources.get('discardChanges'));
  1560. }
  1561. else
  1562. {
  1563. fn();
  1564. }
  1565. mxEvent.consume(evt);
  1566. }
  1567. }));
  1568. }
  1569. if (file.isEditable())
  1570. {
  1571. var graph = this.editor.graph;
  1572. var spinBtn = null;
  1573. var editLibrary = mxUtils.bind(this, function(evt)
  1574. {
  1575. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  1576. mxEvent.consume(evt);
  1577. });
  1578. var saveLibrary = mxUtils.bind(this, function(evt)
  1579. {
  1580. file.setModified(true);
  1581. if (file.isAutosave())
  1582. {
  1583. if (spinBtn != null && spinBtn.parentNode != null)
  1584. {
  1585. spinBtn.parentNode.removeChild(spinBtn);
  1586. }
  1587. spinBtn = btn.cloneNode(false);
  1588. spinBtn.setAttribute('src', Editor.spinImage);
  1589. spinBtn.setAttribute('title', mxResources.get('saving'));
  1590. spinBtn.style.cursor = 'default';
  1591. spinBtn.style.marginRight = '2px';
  1592. spinBtn.style.marginTop = '-2px';
  1593. buttons.insertBefore(spinBtn, buttons.firstChild);
  1594. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1595. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  1596. {
  1597. if (spinBtn != null && spinBtn.parentNode != null)
  1598. {
  1599. spinBtn.parentNode.removeChild(spinBtn);
  1600. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1601. }
  1602. });
  1603. }
  1604. else if (saveBtn == null)
  1605. {
  1606. saveBtn = btn.cloneNode(false);
  1607. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  1608. saveBtn.setAttribute('title', mxResources.get('save'));
  1609. buttons.insertBefore(saveBtn, buttons.firstChild);
  1610. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  1611. {
  1612. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  1613. file.constructor == LocalLibrary, true, function()
  1614. {
  1615. if (saveBtn != null && !file.isModified())
  1616. {
  1617. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1618. saveBtn.parentNode.removeChild(saveBtn);
  1619. saveBtn = null;
  1620. }
  1621. });
  1622. mxEvent.consume(evt);
  1623. }));
  1624. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1625. }
  1626. });
  1627. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  1628. {
  1629. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  1630. // Translates cells to origin
  1631. for (var i = 0; i < cells.length; i++)
  1632. {
  1633. var geo = graph.getCellGeometry(cells[i]);
  1634. if (geo != null)
  1635. {
  1636. geo.translate(-bounds.x, -bounds.y);
  1637. }
  1638. }
  1639. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  1640. cells, bounds.width, bounds.height, title || '', true, false, false));
  1641. var xml = this.editor.graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  1642. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  1643. if (title != null)
  1644. {
  1645. entry.title = title;
  1646. }
  1647. images.push(entry);
  1648. saveLibrary(evt);
  1649. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1650. {
  1651. dropTarget.parentNode.removeChild(dropTarget);
  1652. dropTarget = null;
  1653. }
  1654. });
  1655. var addSelection = mxUtils.bind(this, function(evt)
  1656. {
  1657. if (!graph.isSelectionEmpty())
  1658. {
  1659. var cells = graph.getSelectionCells();
  1660. var bounds = graph.view.getBounds(cells);
  1661. var s = graph.view.scale;
  1662. bounds.x /= s;
  1663. bounds.y /= s;
  1664. bounds.width /= s;
  1665. bounds.height /= s;
  1666. bounds.x -= graph.view.translate.x;
  1667. bounds.y -= graph.view.translate.y;
  1668. addCells(cells, bounds);
  1669. }
  1670. else if (graph.getRubberband().isActive())
  1671. {
  1672. graph.getRubberband().execute(evt);
  1673. graph.getRubberband().reset();
  1674. }
  1675. else
  1676. {
  1677. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  1678. }
  1679. mxEvent.consume(evt);
  1680. });
  1681. // Defines inactive border state
  1682. contentDiv.style.border = '3px solid transparent';
  1683. // Adds drop handler from graph
  1684. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  1685. {
  1686. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  1687. {
  1688. graph.graphHandler.shape.node.style.visibility = 'hidden';
  1689. if (dropTarget != null)
  1690. {
  1691. dropTarget.style.border = '3px dotted rgb(254, 137, 12)';
  1692. }
  1693. else
  1694. {
  1695. contentDiv.style.border = '3px dotted rgb(254, 137, 12)';
  1696. }
  1697. contentDiv.style.cursor = 'copy';
  1698. graph.panningManager.stop();
  1699. graph.autoScroll = false;
  1700. if (graph.graphHandler.guide != null)
  1701. {
  1702. graph.graphHandler.guide.setVisible(false);
  1703. }
  1704. if (graph.graphHandler.hint != null)
  1705. {
  1706. graph.graphHandler.hint.style.visibility = 'hidden';
  1707. }
  1708. mxEvent.consume(evt);
  1709. }
  1710. }), mxUtils.bind(this, function(evt)
  1711. {
  1712. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  1713. {
  1714. contentDiv.style.border = '3px solid transparent';
  1715. if (dropTarget != null)
  1716. {
  1717. dropTarget.style.border = '3px dotted lightGray';
  1718. }
  1719. contentDiv.style.cursor = 'default';
  1720. this.sidebar.showTooltips = true;
  1721. graph.panningManager.stop();
  1722. graph.graphHandler.reset();
  1723. graph.isMouseDown = false;
  1724. graph.autoScroll = true;
  1725. addSelection(evt);
  1726. mxEvent.consume(evt);
  1727. }
  1728. }));
  1729. // Handles mouse leaving the library and restoring move
  1730. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  1731. {
  1732. if (graph.isMouseDown && graph.graphHandler.shape != null)
  1733. {
  1734. graph.graphHandler.shape.node.style.visibility = 'visible';
  1735. contentDiv.style.border = '3px solid transparent';
  1736. contentDiv.style.cursor = '';
  1737. graph.autoScroll = true;
  1738. if (graph.graphHandler.guide != null)
  1739. {
  1740. graph.graphHandler.guide.setVisible(true);
  1741. }
  1742. if (graph.graphHandler.hint != null)
  1743. {
  1744. graph.graphHandler.hint.style.visibility = 'visible';
  1745. }
  1746. if (dropTarget != null)
  1747. {
  1748. dropTarget.style.border = '3px dotted lightGray';
  1749. }
  1750. }
  1751. }));
  1752. // Adds drop handler from filesystem
  1753. if (Graph.fileSupport)
  1754. {
  1755. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  1756. {
  1757. if (dropTarget != null)
  1758. {
  1759. dropTarget.style.border = '3px dotted rgb(254, 137, 12)';
  1760. }
  1761. else
  1762. {
  1763. contentDiv.style.border = '3px dotted rgb(254, 137, 12)';
  1764. }
  1765. evt.dataTransfer.dropEffect = 'copy';
  1766. contentDiv.style.cursor = 'copy';
  1767. this.sidebar.hideTooltip();
  1768. evt.stopPropagation();
  1769. evt.preventDefault();
  1770. }));
  1771. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  1772. {
  1773. contentDiv.style.border = '3px solid transparent';
  1774. contentDiv.style.cursor = '';
  1775. if (dropTarget != null)
  1776. {
  1777. dropTarget.style.border = '3px dotted lightGray';
  1778. }
  1779. if (evt.dataTransfer.files.length > 0)
  1780. {
  1781. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  1782. {
  1783. if (data != null && mimeType.substring(0, 6) == 'image/')
  1784. {
  1785. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  1786. this.convertDataUri(data);
  1787. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  1788. cells[0].vertex = true;
  1789. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  1790. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1791. {
  1792. dropTarget.parentNode.removeChild(dropTarget);
  1793. dropTarget = null;
  1794. }
  1795. }
  1796. else
  1797. {
  1798. var done = false;
  1799. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  1800. {
  1801. if (theData != null && theMimeType == 'text/xml')
  1802. {
  1803. var doc = mxUtils.parseXml(theData);
  1804. if (doc.documentElement.nodeName == 'mxlibrary')
  1805. {
  1806. try
  1807. {
  1808. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  1809. addImages(temp, contentDiv);
  1810. images = images.concat(temp);
  1811. saveLibrary(evt);
  1812. this.spinner.stop();
  1813. done = true;
  1814. }
  1815. catch (e)
  1816. {
  1817. // ignore
  1818. }
  1819. }
  1820. else if (doc.documentElement.nodeName == 'mxfile')
  1821. {
  1822. try
  1823. {
  1824. var pages = doc.documentElement.getElementsByTagName('diagram');
  1825. for (var i = 0; i < pages.length; i++)
  1826. {
  1827. var temp = mxUtils.getTextContent(pages[i]);
  1828. var cells = this.stringToCells(this.editor.graph.decompress(temp));
  1829. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  1830. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  1831. }
  1832. done = true;
  1833. }
  1834. catch (e)
  1835. {
  1836. if (window.console != null)
  1837. {
  1838. console.log('error in drop handler:', e);
  1839. }
  1840. }
  1841. }
  1842. }
  1843. if (!done)
  1844. {
  1845. this.spinner.stop();
  1846. this.handleError({message: mxResources.get('errorLoadingFile')})
  1847. }
  1848. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1849. {
  1850. dropTarget.parentNode.removeChild(dropTarget);
  1851. dropTarget = null;
  1852. }
  1853. });
  1854. if (file != null && img != null && ((/(\.vsdx)($|\?)/i.test(img)) || /(\.vssx)($|\?)/i.test(img) || (/(\.vsd)($|\?)/i.test(img))))
  1855. {
  1856. this.importVisio(file, function(xml)
  1857. {
  1858. doImport(xml, 'text/xml');
  1859. }, null, img);
  1860. }
  1861. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  1862. {
  1863. this.parseFile(file, mxUtils.bind(this, function(xhr)
  1864. {
  1865. if (xhr.readyState == 4)
  1866. {
  1867. this.spinner.stop();
  1868. if (xhr.status >= 200 && xhr.status <= 299)
  1869. {
  1870. doImport(xhr.responseText, 'text/xml');
  1871. }
  1872. else
  1873. {
  1874. this.handleError({message: mxResources.get((xhr.status == 413) ?
  1875. 'drawingTooLarge' : 'invalidOrMissingFile')},
  1876. mxResources.get('errorLoadingFile'));
  1877. }
  1878. }
  1879. }));
  1880. }
  1881. else
  1882. {
  1883. doImport(data, mimeType);
  1884. }
  1885. }
  1886. }));
  1887. }
  1888. evt.stopPropagation();
  1889. evt.preventDefault();
  1890. }));
  1891. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  1892. {
  1893. if (dropTarget != null)
  1894. {
  1895. dropTarget.style.border = '3px dotted lightGray';
  1896. }
  1897. else
  1898. {
  1899. contentDiv.style.border = '3px solid transparent';
  1900. contentDiv.style.cursor = '';
  1901. }
  1902. evt.stopPropagation();
  1903. evt.preventDefault();
  1904. });
  1905. }
  1906. btn = btn.cloneNode(false);
  1907. btn.setAttribute('src', IMAGE_PATH + '/edit.gif');
  1908. btn.setAttribute('title', mxResources.get('edit'));
  1909. buttons.insertBefore(btn, buttons.firstChild);
  1910. mxEvent.addListener(btn, 'click', editLibrary);
  1911. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  1912. {
  1913. if (mxEvent.getSource(evt) == contentDiv)
  1914. {
  1915. editLibrary(evt);
  1916. }
  1917. });
  1918. var btn2 = btn.cloneNode(false);
  1919. btn2.setAttribute('src', Editor.plusImage);
  1920. btn2.setAttribute('title', mxResources.get('add'));
  1921. buttons.insertBefore(btn2, buttons.firstChild);
  1922. mxEvent.addListener(btn2, 'click', addSelection);
  1923. if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
  1924. {
  1925. var link = document.createElement('span');
  1926. link.setAttribute('title', mxResources.get('help'));
  1927. link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
  1928. mxUtils.write(link, '?');
  1929. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  1930. {
  1931. this.openLink(EditorUi.scratchpadHelpLink);
  1932. mxEvent.consume(evt);
  1933. }));
  1934. buttons.insertBefore(link, buttons.firstChild);
  1935. }
  1936. }
  1937. title.appendChild(buttons);
  1938. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1939. };
  1940. /**
  1941. * EditorUi Overrides
  1942. */
  1943. if (urlParams['offline'] == '1' || EditorUi.isElectronApp)
  1944. {
  1945. EditorUi.prototype.footerHeight = 4;
  1946. }
  1947. else
  1948. {
  1949. if (urlParams['savesidebar'] == '1')
  1950. {
  1951. Sidebar.prototype.thumbWidth = 64;
  1952. Sidebar.prototype.thumbHeight = 64;
  1953. }
  1954. EditorUi.prototype.footerHeight = (screen.width >= 760 && screen.height >= 240) ? 46 : 0;
  1955. // Fetches footer from page
  1956. EditorUi.prototype.createFooter = function()
  1957. {
  1958. var footer = document.getElementById('geFooter');
  1959. if (footer != null)
  1960. {
  1961. footer.style.visibility = 'visible';
  1962. // Adds button to hide the footer
  1963. var img = document.createElement('img');
  1964. img.setAttribute('border', '0');
  1965. img.setAttribute('src', Dialog.prototype.closeImage);
  1966. img.setAttribute('title', mxResources.get('hide'));
  1967. footer.appendChild(img)
  1968. if (mxClient.IS_QUIRKS)
  1969. {
  1970. img.style.position = 'relative';
  1971. img.style.styleFloat = 'right';
  1972. img.style.top = '-30px';
  1973. img.style.left = '164px';
  1974. img.style.cursor = 'pointer';
  1975. }
  1976. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  1977. {
  1978. this.hideFooter();
  1979. }));
  1980. }
  1981. return footer;
  1982. };
  1983. }
  1984. EditorUi.initTheme = function()
  1985. {
  1986. if (uiTheme == 'atlas')
  1987. {
  1988. mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
  1989. if (typeof Toolbar !== 'undefined')
  1990. {
  1991. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  1992. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  1993. }
  1994. Editor.prototype.initialTopSpacing = 3;
  1995. EditorUi.prototype.menubarHeight = 41;
  1996. EditorUi.prototype.toolbarHeight = 38;
  1997. EditorUi.prototype.hsplitPosition = 188;
  1998. Sidebar.prototype.thumbWidth = 46;
  1999. Sidebar.prototype.thumbHeight = 46;
  2000. Sidebar.prototype.thumbPadding = (document.documentMode >= 5) ? 0 : 1;
  2001. Sidebar.prototype.thumbBorder = 2;
  2002. }
  2003. else if (uiTheme == 'dark')
  2004. {
  2005. mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
  2006. Dialog.backdropColor = '#2a2a2a';
  2007. Graph.prototype.defaultThemeName = 'darkTheme';
  2008. Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
  2009. Graph.prototype.defaultGraphBackground = null;
  2010. Graph.prototype.defaultPageBorderColor = '#505759';
  2011. Graph.prototype.svgShadowColor = '#e0e0e0';
  2012. Graph.prototype.svgShadowOpacity = '0.6';
  2013. Graph.prototype.svgShadowSize = '0.8';
  2014. Graph.prototype.svgShadowBlur = '1.4';
  2015. Format.prototype.inactiveTabBackgroundColor = 'black';
  2016. BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
  2017. Sidebar.prototype.dragPreviewBorder = '1px dashed #cccccc';
  2018. mxGraphHandler.prototype.previewColor = '#cccccc';
  2019. StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
  2020. if (mxClient.IS_SVG)
  2021. {
  2022. Editor.helpImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAP1BMVEUAAAD///////////////////////////////////////////////////////////////////////////////9Du/pqAAAAFXRSTlMAT30qCJRBboyDZyCgRzUUdF46MJlgXETgAAAAeklEQVQY022O2w4DIQhEQUURda/9/28tUO2+7CQS5sgQ4F1RapX78YUwRqQjTU8ILqQfKerTKTvACJ4nLX3krt+8aS82oI8aQC4KavRgtvEW/mDvsICgA03PSGRr79MqX1YPNIxzjyqtw8ZnnRo4t5a5undtJYRywau+ds4Cyza3E6YAAAAASUVORK5CYII=';
  2023. Editor.checkmarkImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAARVBMVEUAAACZmZkICAgEBASNjY2Dg4MYGBiTk5N5eXl1dXVmZmZQUFBCQkI3NzceHh4MDAykpKSJiYl+fn5sbGxaWlo/Pz8SEhK96uPlAAAAAXRSTlMAQObYZgAAAE5JREFUGNPFzTcSgDAQQ1HJGUfy/Y9K7V1qeOUfzQifCQZai1XHaz11LFysbDbzgDSSWMZiETz3+b8yNUc/MMsktxuC8XQBSncdLwz+8gCCggGXzBcozAAAAABJRU5ErkJggg==';
  2024. }
  2025. }
  2026. };
  2027. EditorUi.initTheme();
  2028. /**
  2029. * Hides the footer.
  2030. */
  2031. EditorUi.prototype.hideFooter = function()
  2032. {
  2033. var footer = document.getElementById('geFooter');
  2034. if (footer != null)
  2035. {
  2036. this.footerHeight = 0;
  2037. footer.style.display = 'none';
  2038. this.refresh();
  2039. }
  2040. };
  2041. /**
  2042. * Shows the footer.
  2043. */
  2044. EditorUi.prototype.showFooter = function(height)
  2045. {
  2046. var footer = document.getElementById('geFooter');
  2047. if (footer != null)
  2048. {
  2049. this.footerHeight = height;
  2050. footer.style.display = 'inline';
  2051. this.refresh();
  2052. }
  2053. };
  2054. /**
  2055. * Overrides image dialog to add image search and Google+.
  2056. */
  2057. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  2058. {
  2059. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  2060. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  2061. this.showDialog(dlg.container, (Graph.fileSupport) ? 440 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
  2062. dlg.init();
  2063. };
  2064. /**
  2065. * Hides the current menu.
  2066. */
  2067. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  2068. {
  2069. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  2070. {
  2071. var change = new ChangePageSetup(this, null, image);
  2072. change.ignoreColor = true;
  2073. this.editor.graph.model.execute(change);
  2074. });
  2075. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  2076. {
  2077. apply(image);
  2078. }));
  2079. this.showDialog(dlg.container, 360, 200, true, true);
  2080. dlg.init();
  2081. };
  2082. /**
  2083. * Hides the current menu.
  2084. */
  2085. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  2086. {
  2087. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  2088. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  2089. {
  2090. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  2091. {
  2092. this.showSplash();
  2093. }
  2094. }));
  2095. dlg.init();
  2096. };
  2097. /**
  2098. * Hook for sidebar footer container.
  2099. */
  2100. EditorUi.prototype.createSidebarFooterContainer = function()
  2101. {
  2102. var div = this.createDiv('geSidebarContainer');
  2103. div.style.position = 'absolute';
  2104. div.style.overflow = 'hidden';
  2105. div.style.borderWidth = '3px';
  2106. var elt2 = document.createElement('a');
  2107. elt2.setAttribute('href', 'javascript:void(0);');
  2108. elt2.className = 'geTitle';
  2109. elt2.style.height = '100%';
  2110. elt2.style.paddingTop = '9px';
  2111. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  2112. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  2113. {
  2114. this.actions.get('shapes').funct();
  2115. mxEvent.consume(evt);
  2116. }));
  2117. div.appendChild(elt2);
  2118. return div;
  2119. };
  2120. /**
  2121. * Translates this point by the given vector.
  2122. *
  2123. * @param {number} dx X-coordinate of the translation.
  2124. * @param {number} dy Y-coordinate of the translation.
  2125. */
  2126. EditorUi.prototype.handleError = function(resp, title, fn)
  2127. {
  2128. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  2129. var e = (resp != null && resp.error != null) ? resp.error : resp;
  2130. if (e != null || title != null)
  2131. {
  2132. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  2133. var btn = mxResources.get('ok');
  2134. var retry = null;
  2135. title = (title != null) ? title : mxResources.get('error');
  2136. if (e != null)
  2137. {
  2138. if (e.retry != null)
  2139. {
  2140. btn = mxResources.get('cancel');
  2141. retry = function()
  2142. {
  2143. resume();
  2144. e.retry();
  2145. };
  2146. }
  2147. if (typeof(gapi) != 'undefined' && typeof(gapi.drive) != 'undefined' && typeof(gapi.drive.realtime) != 'undefined' &&
  2148. e.type == gapi.drive.realtime.ErrorType.FORBIDDEN)
  2149. {
  2150. msg = mxUtils.htmlEntities(mxResources.get('forbidden'));
  2151. }
  2152. else if (e.code == 404 || e.status == 404 || (typeof(gapi) != 'undefined' && typeof(gapi.drive) != 'undefined' &&
  2153. typeof(gapi.drive.realtime) != 'undefined' && e.type == gapi.drive.realtime.ErrorType.NOT_FOUND))
  2154. {
  2155. msg = mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied'));
  2156. var id = window.location.hash;
  2157. if (id != null && id.substring(0, 2) == '#G')
  2158. {
  2159. id = id.substring(2);
  2160. msg += ' <a href="https://drive.google.com/open?id=' + id + '" target="_blank">' +
  2161. mxUtils.htmlEntities(mxResources.get('tryOpeningViaThisPage')) + '</a>';
  2162. }
  2163. }
  2164. else if (e.code == App.ERROR_TIMEOUT)
  2165. {
  2166. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  2167. }
  2168. else if (e.code == App.ERROR_BUSY)
  2169. {
  2170. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  2171. }
  2172. else if (e.message != null)
  2173. {
  2174. msg = mxUtils.htmlEntities(e.message);
  2175. }
  2176. else if (e.response != null && e.response.error != null)
  2177. {
  2178. msg = mxUtils.htmlEntities(e.response.error);
  2179. }
  2180. }
  2181. this.showError(title, msg, btn, fn, retry);
  2182. }
  2183. else if (fn != null)
  2184. {
  2185. fn();
  2186. }
  2187. };
  2188. /**
  2189. * Translates this point by the given vector.
  2190. *
  2191. * @param {number} dx X-coordinate of the translation.
  2192. * @param {number} dy Y-coordinate of the translation.
  2193. */
  2194. EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h)
  2195. {
  2196. var dlg = new ErrorDialog(this, title, msg, btn, fn, retry, btn2, fn2, null, btn3, fn3);
  2197. this.showDialog(dlg.container, w || 340, h || 150, true, false);
  2198. dlg.init();
  2199. };
  2200. /**
  2201. * Translates this point by the given vector.
  2202. *
  2203. * @param {number} dx X-coordinate of the translation.
  2204. * @param {number} dy Y-coordinate of the translation.
  2205. */
  2206. EditorUi.prototype.alert = function(msg, fn)
  2207. {
  2208. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  2209. this.showDialog(dlg.container, 340, 100, true, false);
  2210. dlg.init();
  2211. };
  2212. /**
  2213. * Translates this point by the given vector.
  2214. *
  2215. * @param {number} dx X-coordinate of the translation.
  2216. * @param {number} dy Y-coordinate of the translation.
  2217. */
  2218. EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel)
  2219. {
  2220. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  2221. this.showDialog(new ConfirmDialog(this, msg, function()
  2222. {
  2223. resume();
  2224. if (okFn != null)
  2225. {
  2226. okFn();
  2227. }
  2228. }, function()
  2229. {
  2230. resume();
  2231. if (cancelFn != null)
  2232. {
  2233. cancelFn();
  2234. }
  2235. }, okLabel, cancelLabel).container, 340, 90, true, false);
  2236. };
  2237. /**
  2238. * Translates this point by the given vector.
  2239. *
  2240. * @param {number} dx X-coordinate of the translation.
  2241. * @param {number} dy Y-coordinate of the translation.
  2242. */
  2243. EditorUi.prototype.setCurrentFile = function(file)
  2244. {
  2245. this.currentFile = file;
  2246. };
  2247. /**
  2248. * Translates this point by the given vector.
  2249. *
  2250. * @param {number} dx X-coordinate of the translation.
  2251. * @param {number} dy Y-coordinate of the translation.
  2252. */
  2253. EditorUi.prototype.getCurrentFile = function()
  2254. {
  2255. return this.currentFile;
  2256. };
  2257. /**
  2258. * Handling for canvas export.
  2259. */
  2260. /**
  2261. *
  2262. */
  2263. EditorUi.prototype.isExportToCanvas = function()
  2264. {
  2265. // LATER: Fix security error caused by foreignObjects in Safari for toDataUri (tainted canvas)
  2266. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  2267. };
  2268. /**
  2269. * Translates this point by the given vector.
  2270. *
  2271. * @param {number} dx X-coordinate of the translation.
  2272. * @param {number} dy Y-coordinate of the translation.
  2273. */
  2274. EditorUi.prototype.createSvgDataUri = function(svg)
  2275. {
  2276. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  2277. };
  2278. /**
  2279. *
  2280. */
  2281. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  2282. {
  2283. var data = canvas.toDataURL('image/' + format);
  2284. // Checks if output is invalid or empty
  2285. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  2286. {
  2287. throw {message: 'Invalid image'};
  2288. }
  2289. if (xml != null)
  2290. {
  2291. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(this.editor.graph.compress(xml)));
  2292. }
  2293. return data;
  2294. };
  2295. /**
  2296. *
  2297. */
  2298. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  2299. {
  2300. var ext = ((format == 'jpeg') ? 'jpg' : format);
  2301. var filename = this.getBaseFilename() + '.' + ext;
  2302. var data = this.createImageDataUri(canvas, xml, format);
  2303. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  2304. };
  2305. /**
  2306. * Returns true if files should be saved using <saveLocalFile>.
  2307. */
  2308. EditorUi.prototype.isLocalFileSave = function()
  2309. {
  2310. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  2311. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  2312. document.documentMode != 9 && document.documentMode != 8 &&
  2313. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  2314. this.isOfflineApp() || mxClient.IS_IOS);
  2315. };
  2316. /**
  2317. * Translates this point by the given vector.
  2318. *
  2319. * @param {number} dx X-coordinate of the translation.
  2320. * @param {number} dy Y-coordinate of the translation.
  2321. */
  2322. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  2323. {
  2324. // Newer versions of IE
  2325. if (window.Blob && navigator.msSaveOrOpenBlob)
  2326. {
  2327. var blob = (base64Encoded) ?
  2328. this.base64ToBlob(data, mimeType) :
  2329. new Blob([data], {type: mimeType})
  2330. navigator.msSaveOrOpenBlob(blob, filename);
  2331. }
  2332. // Older versions of IE (binary not supported)
  2333. else if (mxClient.IS_IE)
  2334. {
  2335. var win = window.open('about:blank', '_blank');
  2336. if (win == null)
  2337. {
  2338. mxUtils.popup(data, true);
  2339. }
  2340. else
  2341. {
  2342. win.document.write(data);
  2343. win.document.close();
  2344. win.document.execCommand('SaveAs', true, filename);
  2345. win.close();
  2346. }
  2347. }
  2348. else if (mxClient.IS_IOS)
  2349. {
  2350. // Poor man's saveAs in iOS via context menu of selected output
  2351. var dlg = new TextareaDialog(this, filename + ':', data, null, null, mxResources.get('close'));
  2352. dlg.textarea.style.width = '600px';
  2353. dlg.textarea.style.height = '380px';
  2354. this.showDialog(dlg.container, 620, 460, true, true);
  2355. dlg.init();
  2356. document.execCommand('selectall', false, null);
  2357. }
  2358. else
  2359. {
  2360. var a = document.createElement('a');
  2361. // Workaround for mxXmlRequest.simulate no longer working in Safari
  2362. // if this is used (ie PNG export broken after XML export in Safari).
  2363. var useDownload = !mxClient.IS_SF && typeof a.download !== 'undefined';
  2364. // Workaround for Chromium 65 cross-domain anchor download issue
  2365. if (mxClient.IS_GC)
  2366. {
  2367. var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
  2368. var vers = raw ? parseInt(raw[2], 10) : false;
  2369. useDownload = vers == 65 ? false : useDownload;
  2370. }
  2371. if (useDownload || this.isOffline())
  2372. {
  2373. a.href = URL.createObjectURL((base64Encoded) ?
  2374. this.base64ToBlob(data, mimeType) :
  2375. new Blob([data], {type: mimeType}));
  2376. if (useDownload)
  2377. {
  2378. a.download = filename;
  2379. }
  2380. else
  2381. {
  2382. // Workaround for same window in Safari
  2383. a.setAttribute('target', '_blank');
  2384. }
  2385. document.body.appendChild(a);
  2386. try
  2387. {
  2388. window.setTimeout(function()
  2389. {
  2390. URL.revokeObjectURL(a.href);
  2391. }, 0);
  2392. a.click();
  2393. a.parentNode.removeChild(a);
  2394. }
  2395. catch (e)
  2396. {
  2397. // ignore
  2398. }
  2399. }
  2400. else
  2401. {
  2402. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  2403. req.simulate(document, '_blank');
  2404. }
  2405. }
  2406. };
  2407. /**
  2408. * Translates this point by the given vector.
  2409. *
  2410. * @param {number} dx X-coordinate of the translation.
  2411. * @param {number} dy Y-coordinate of the translation.
  2412. */
  2413. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  2414. {
  2415. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  2416. 'data=' + encodeURIComponent(this.editor.graph.compress(data));
  2417. return new mxXmlRequest(SAVE_URL, param +
  2418. ((mimeType != null) ? '&mime=' + mimeType : '') +
  2419. ((format != null) ? '&format=' + format : '') +
  2420. ((base64Response != null) ? '&base64=' + base64Response : '') +
  2421. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  2422. ((base64Encoded) ? '&binary=1' : ''));
  2423. };
  2424. /**
  2425. * Translates this point by the given vector.
  2426. *
  2427. * @param {number} dx X-coordinate of the translation.
  2428. * @param {number} dy Y-coordinate of the translation.
  2429. */
  2430. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  2431. {
  2432. contentType = contentType || '';
  2433. var sliceSize = 1024;
  2434. var byteCharacters = atob(base64Data);
  2435. var bytesLength = byteCharacters.length;
  2436. var slicesCount = Math.ceil(bytesLength / sliceSize);
  2437. var byteArrays = new Array(slicesCount);
  2438. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  2439. {
  2440. var begin = sliceIndex * sliceSize;
  2441. var end = Math.min(begin + sliceSize, bytesLength);
  2442. var bytes = new Array(end - begin);
  2443. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  2444. {
  2445. bytes[i] = byteCharacters[offset].charCodeAt(0);
  2446. }
  2447. byteArrays[sliceIndex] = new Uint8Array(bytes);
  2448. }
  2449. return new Blob(byteArrays, {type: contentType});
  2450. };
  2451. /**
  2452. * Translates this point by the given vector.
  2453. *
  2454. * @param {number} dx X-coordinate of the translation.
  2455. * @param {number} dy Y-coordinate of the translation.
  2456. */
  2457. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab)
  2458. {
  2459. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  2460. allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  2461. var count = this.getServiceCount(allowBrowser);
  2462. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2463. {
  2464. try
  2465. {
  2466. // Opens a new window
  2467. if (mode == '_blank')
  2468. {
  2469. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  2470. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  2471. {
  2472. this.openInNewWindow(data, mimeType, base64Encoded);
  2473. }
  2474. else
  2475. {
  2476. var win = window.open('about:blank');
  2477. if (win == null)
  2478. {
  2479. mxUtils.popup(data, true);
  2480. }
  2481. else
  2482. {
  2483. win.document.write(mxUtils.htmlEntities(data, false));
  2484. win.document.close();
  2485. }
  2486. }
  2487. }
  2488. else if (mode == App.MODE_DEVICE || mode == 'download')
  2489. {
  2490. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  2491. }
  2492. else if (newTitle != null && newTitle.length > 0)
  2493. {
  2494. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2495. {
  2496. try
  2497. {
  2498. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  2499. }
  2500. catch (e)
  2501. {
  2502. this.handleError(e);
  2503. }
  2504. }));
  2505. }
  2506. }
  2507. catch (e)
  2508. {
  2509. this.handleError(e);
  2510. }
  2511. }), mxUtils.bind(this, function()
  2512. {
  2513. this.hideDialog();
  2514. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
  2515. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  2516. var noServices = (mxClient.IS_IOS) ? 0 : 1;
  2517. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  2518. this.showDialog(dlg.container, 420, height, true, true);
  2519. dlg.init();
  2520. };
  2521. /**
  2522. *
  2523. */
  2524. EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
  2525. {
  2526. // In Google Chrome 60 the code from below produces a blank window
  2527. if (mxClient.IS_GC || mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  2528. {
  2529. var win = window.open('about:blank');
  2530. if (win == null)
  2531. {
  2532. mxUtils.popup(data, true);
  2533. }
  2534. else
  2535. {
  2536. // Workaround for broken images in SVG output in Chrome
  2537. if (mimeType == 'image/svg+xml')
  2538. {
  2539. win.document.write('<html>' + data + '</html>');
  2540. }
  2541. else
  2542. {
  2543. win.document.write('<html><img src="data:' +
  2544. mimeType + ((base64Encoded) ? ';base64,' +
  2545. data : ';charset=utf8,' + encodeURIComponent(data)) +
  2546. '"/></html>');
  2547. }
  2548. win.document.close();
  2549. }
  2550. }
  2551. else
  2552. {
  2553. // win.open is workaround for cleared contents in Chrome after delay
  2554. // when using location.replace
  2555. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  2556. data : ';charset=utf8,' + encodeURIComponent(data)));
  2557. if (win == null)
  2558. {
  2559. mxUtils.popup(data, true);
  2560. }
  2561. }
  2562. };
  2563. var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
  2564. /**
  2565. * Creates a temporary graph instance for rendering off-screen content.
  2566. */
  2567. EditorUi.prototype.addChromelessToolbarItems = function(addButton)
  2568. {
  2569. if (this.isExportToCanvas())
  2570. {
  2571. this.exportDialog = null;
  2572. var exportButton = addButton(mxUtils.bind(this, function(evt)
  2573. {
  2574. var clickHandler = mxUtils.bind(this, function()
  2575. {
  2576. mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
  2577. if (this.exportDialog != null)
  2578. {
  2579. this.exportDialog.parentNode.removeChild(this.exportDialog);
  2580. this.exportDialog = null;
  2581. }
  2582. });
  2583. if (this.exportDialog != null)
  2584. {
  2585. clickHandler.apply(this);
  2586. }
  2587. else
  2588. {
  2589. this.exportDialog = document.createElement('div');
  2590. var r = exportButton.getBoundingClientRect();
  2591. mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
  2592. this.exportDialog.style.position = 'fixed';
  2593. this.exportDialog.style.textAlign = 'center';
  2594. this.exportDialog.style.fontFamily = 'Helvetica,Arial';
  2595. this.exportDialog.style.backgroundColor = '#000000';
  2596. this.exportDialog.style.width = '50px';
  2597. this.exportDialog.style.height = '50px';
  2598. this.exportDialog.style.padding = '4px 2px 4px 2px';
  2599. this.exportDialog.style.color = '#ffffff';
  2600. mxUtils.setOpacity(this.exportDialog, 70);
  2601. this.exportDialog.style.left = r.left + 'px';
  2602. this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  2603. this.chromelessToolbar.offsetHeight + 4 + 'px';
  2604. // Puts the dialog on top of the container z-index
  2605. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  2606. this.exportDialog.style.zIndex = style.zIndex;
  2607. var spinner = new Spinner({
  2608. lines: 8, // The number of lines to draw
  2609. length: 6, // The length of each line
  2610. width: 5, // The line thickness
  2611. radius: 6, // The radius of the inner circle
  2612. rotate: 0, // The rotation offset
  2613. color: '#fff', // #rgb or #rrggbb
  2614. speed: 1.5, // Rounds per second
  2615. trail: 60, // Afterglow percentage
  2616. shadow: false, // Whether to render a shadow
  2617. hwaccel: false, // Whether to use hardware acceleration
  2618. top: '28px',
  2619. zIndex: 2e9 // The z-index (defaults to 2000000000)
  2620. });
  2621. spinner.spin(this.exportDialog);
  2622. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  2623. {
  2624. spinner.stop();
  2625. this.exportDialog.style.width = 'auto';
  2626. this.exportDialog.style.height = 'auto';
  2627. this.exportDialog.style.padding = '10px';
  2628. var data = this.createImageDataUri(canvas, null, 'png');
  2629. var img = document.createElement('img');
  2630. img.style.maxWidth = '140px';
  2631. img.style.maxHeight = '140px';
  2632. img.style.cursor = 'pointer';
  2633. img.setAttribute('title', mxResources.get('openInNewWindow'));
  2634. img.setAttribute('border', '0');
  2635. img.setAttribute('src', data);
  2636. this.exportDialog.appendChild(img);
  2637. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  2638. {
  2639. this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
  2640. clickHandler.apply(this, arguments);
  2641. }));
  2642. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  2643. {
  2644. this.spinner.stop();
  2645. this.handleError(e);
  2646. }));
  2647. mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
  2648. document.body.appendChild(this.exportDialog);
  2649. }
  2650. mxEvent.consume(evt);
  2651. }), Editor.cameraLargeImage, mxResources.get('export'));
  2652. }
  2653. editoUiAddChromelessToolbarItems.apply(this, arguments);
  2654. };
  2655. /**
  2656. * Translates this point by the given vector.
  2657. *
  2658. * @param {number} dx X-coordinate of the translation.
  2659. * @param {number} dy Y-coordinate of the translation.
  2660. */
  2661. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  2662. {
  2663. if (this.isLocalFileSave())
  2664. {
  2665. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  2666. }
  2667. else
  2668. {
  2669. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  2670. {
  2671. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  2672. }), data, base64Encoded, mime);
  2673. }
  2674. };
  2675. /**
  2676. * Translates this point by the given vector.
  2677. *
  2678. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  2679. * side without requiring a server roundtrip.
  2680. *
  2681. * @param {number} dx X-coordinate of the translation.
  2682. * @param {number} dy Y-coordinate of the translation.
  2683. */
  2684. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
  2685. {
  2686. allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
  2687. var count = this.getServiceCount(false);
  2688. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2689. {
  2690. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  2691. {
  2692. var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
  2693. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  2694. if (xhr != null)
  2695. {
  2696. if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
  2697. {
  2698. xhr.simulate(document, '_blank');
  2699. }
  2700. else
  2701. {
  2702. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2703. {
  2704. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  2705. 'application/pdf' : 'image/' + format);
  2706. // Workaround for no roundtrip required if data is available on client-side
  2707. // TODO: Refactor the saveData/saveRequest call chain for local data
  2708. if (data != null)
  2709. {
  2710. try
  2711. {
  2712. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  2713. }
  2714. catch (e)
  2715. {
  2716. this.handleError(e);
  2717. }
  2718. }
  2719. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  2720. {
  2721. // LATER: Catch possible mixed content error
  2722. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  2723. xhr.send(mxUtils.bind(this, function()
  2724. {
  2725. this.spinner.stop();
  2726. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  2727. {
  2728. try
  2729. {
  2730. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  2731. }
  2732. catch (e)
  2733. {
  2734. this.handleError(e);
  2735. }
  2736. }
  2737. else
  2738. {
  2739. this.handleError({message: mxResources.get('errorSavingFile')});
  2740. }
  2741. }), function(resp)
  2742. {
  2743. this.spinner.stop();
  2744. this.handleError(resp);
  2745. });
  2746. }
  2747. }));
  2748. }
  2749. }
  2750. }
  2751. }), mxUtils.bind(this, function()
  2752. {
  2753. this.hideDialog();
  2754. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
  2755. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  2756. var noServices = (mxClient.IS_IOS) ? 0 : 1;
  2757. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  2758. this.showDialog(dlg.container, 380, height, true, true);
  2759. dlg.init();
  2760. };
  2761. /**
  2762. *
  2763. */
  2764. EditorUi.prototype.getEditBlankXml = function()
  2765. {
  2766. return this.getFileData(true);
  2767. };
  2768. /**
  2769. * Hook for subclassers.
  2770. */
  2771. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  2772. {
  2773. // do nothing
  2774. };
  2775. /**
  2776. * Hook for subclassers.
  2777. */
  2778. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  2779. {
  2780. fn(null);
  2781. };
  2782. /**
  2783. *
  2784. */
  2785. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow, editable, embedImages, border, noCrop, currentPage)
  2786. {
  2787. if (this.spinner.spin(document.body, mxResources.get('export')))
  2788. {
  2789. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  2790. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  2791. var bg = (transparentBackground) ? null : this.editor.graph.background;
  2792. if (bg == mxConstants.NONE)
  2793. {
  2794. bg = null;
  2795. }
  2796. // Handles special case where background is null but transparent is false
  2797. if (bg == null && transparentBackground == false)
  2798. {
  2799. bg = '#ffffff';
  2800. }
  2801. // Sets or disables alternate text for foreignObjects. Disabling is needed
  2802. // because PhantomJS seems to ignore switch statements and paint all text.
  2803. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null, ignoreSelection);
  2804. if (addShadow)
  2805. {
  2806. this.editor.graph.addSvgShadow(svgRoot);
  2807. }
  2808. var filename = this.getBaseFilename() + '.svg';
  2809. var doSave = mxUtils.bind(this, function(svgRoot)
  2810. {
  2811. this.spinner.stop();
  2812. if (editable)
  2813. {
  2814. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  2815. }
  2816. if (this.editor.fontCss != null)
  2817. {
  2818. var svgDoc = svgRoot.ownerDocument;
  2819. var style = (svgDoc.createElementNS != null) ?
  2820. svgDoc.createElementNS(mxConstants.NS_SVG, 'style') : svgDoc.createElement('style');
  2821. style.setAttribute('type', 'text/css');
  2822. mxUtils.setTextContent(style, this.editor.fontCss);
  2823. svgRoot.getElementsByTagName('defs')[0].appendChild(style);
  2824. }
  2825. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  2826. mxUtils.getXml(svgRoot);
  2827. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  2828. {
  2829. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  2830. }
  2831. else
  2832. {
  2833. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  2834. {
  2835. mxUtils.popup(svg);
  2836. }));
  2837. }
  2838. });
  2839. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  2840. {
  2841. if (embedImages)
  2842. {
  2843. // Caches images
  2844. if (this.thumbImageCache == null)
  2845. {
  2846. this.thumbImageCache = new Object();
  2847. }
  2848. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  2849. }
  2850. else
  2851. {
  2852. doSave(svgRoot);
  2853. }
  2854. }));
  2855. }
  2856. };
  2857. /**
  2858. *
  2859. */
  2860. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible)
  2861. {
  2862. visible = (visible != null) ? visible : true;
  2863. var cb = document.createElement('input');
  2864. cb.style.marginRight = '8px';
  2865. cb.style.marginTop = '16px';
  2866. cb.setAttribute('type', 'checkbox');
  2867. if (checked)
  2868. {
  2869. cb.setAttribute('checked', 'checked');
  2870. cb.defaultChecked = true;
  2871. }
  2872. if (disabled)
  2873. {
  2874. cb.setAttribute('disabled', 'disabled');
  2875. }
  2876. if (visible)
  2877. {
  2878. div.appendChild(cb);
  2879. var span = document.createElement('span');
  2880. mxUtils.write(span, label);
  2881. div.appendChild(span);
  2882. if (!disableNewline)
  2883. {
  2884. mxUtils.br(div);
  2885. }
  2886. mxEvent.addListener(span, 'click', mxUtils.bind(this, function(evt)
  2887. {
  2888. if (cb.getAttribute('disabled') != 'disabled')
  2889. {
  2890. cb.checked = !cb.checked;
  2891. mxEvent.consume(evt);
  2892. }
  2893. }));
  2894. }
  2895. return cb;
  2896. };
  2897. /**
  2898. *
  2899. */
  2900. EditorUi.prototype.addEditButton = function(div, lightbox)
  2901. {
  2902. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  2903. edit.style.marginLeft = '24px';
  2904. var file = this.getCurrentFile();
  2905. var editUrl = '';
  2906. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  2907. {
  2908. editUrl = window.location.href;
  2909. }
  2910. var editSelect = document.createElement('select');
  2911. editSelect.style.width = '120px';
  2912. editSelect.style.marginLeft = '8px';
  2913. editSelect.style.marginRight = '10px';
  2914. editSelect.className = 'geBtn';
  2915. var blankOption = document.createElement('option');
  2916. blankOption.setAttribute('value', 'blank');
  2917. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  2918. editSelect.appendChild(blankOption);
  2919. var customOption = document.createElement('option');
  2920. customOption.setAttribute('value', 'custom');
  2921. mxUtils.write(customOption, mxResources.get('custom') + '...');
  2922. editSelect.appendChild(customOption);
  2923. div.appendChild(editSelect);
  2924. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  2925. {
  2926. if (editSelect.value == 'custom')
  2927. {
  2928. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  2929. {
  2930. if (value != null)
  2931. {
  2932. editUrl = value;
  2933. }
  2934. else
  2935. {
  2936. editSelect.value = 'blank';
  2937. }
  2938. }, mxResources.get('url'), null, null, null, null, function()
  2939. {
  2940. editSelect.value = 'blank';
  2941. });
  2942. this.showDialog(dlg2.container, 300, 80, true, false);
  2943. dlg2.init();
  2944. }
  2945. }));
  2946. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  2947. {
  2948. if (edit.checked && (lightbox == null || lightbox.checked))
  2949. {
  2950. editSelect.removeAttribute('disabled');
  2951. }
  2952. else
  2953. {
  2954. editSelect.setAttribute('disabled', 'disabled');
  2955. }
  2956. }));
  2957. mxUtils.br(div);
  2958. return {
  2959. getLink: function()
  2960. {
  2961. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  2962. },
  2963. getEditInput: function()
  2964. {
  2965. return edit;
  2966. },
  2967. getEditSelect: function()
  2968. {
  2969. return editSelect;
  2970. }
  2971. };
  2972. }
  2973. /**
  2974. *
  2975. */
  2976. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  2977. {
  2978. mxUtils.write(div, mxResources.get('links') + ':');
  2979. var linkSelect = document.createElement('select');
  2980. linkSelect.style.width = '100px';
  2981. linkSelect.style.marginLeft = '8px';
  2982. linkSelect.style.marginRight = '10px';
  2983. linkSelect.className = 'geBtn';
  2984. var autoOption = document.createElement('option');
  2985. autoOption.setAttribute('value', 'auto');
  2986. mxUtils.write(autoOption, mxResources.get('automatic'));
  2987. linkSelect.appendChild(autoOption);
  2988. var blankOption = document.createElement('option');
  2989. blankOption.setAttribute('value', 'blank');
  2990. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  2991. linkSelect.appendChild(blankOption);
  2992. var selfOption = document.createElement('option');
  2993. selfOption.setAttribute('value', 'self');
  2994. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  2995. linkSelect.appendChild(selfOption);
  2996. if (showFrameOption)
  2997. {
  2998. var frameOption = document.createElement('option');
  2999. frameOption.setAttribute('value', 'frame');
  3000. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  3001. ' (' + mxResources.get('iframe') + ')');
  3002. linkSelect.appendChild(frameOption);
  3003. }
  3004. div.appendChild(linkSelect);
  3005. mxUtils.write(div, mxResources.get('borderColor') + ':');
  3006. var linkColor = '#0000ff';
  3007. var linkButton = null;
  3008. function updateLinkColor()
  3009. {
  3010. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  3011. ((linkColor != null && linkColor != mxConstants.NONE) ?
  3012. 'border:1px solid black;background-color:' + linkColor :
  3013. 'background-position:center center;background-repeat:no-repeat;' +
  3014. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  3015. };
  3016. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  3017. {
  3018. this.pickColor(linkColor || 'none', function(color)
  3019. {
  3020. linkColor = color;
  3021. updateLinkColor();
  3022. });
  3023. mxEvent.consume(evt);
  3024. }));
  3025. updateLinkColor();
  3026. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  3027. linkButton.style.marginLeft = '4px';
  3028. linkButton.style.height = '22px';
  3029. linkButton.style.width = '22px';
  3030. linkButton.style.position = 'relative';
  3031. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  3032. linkButton.className = 'geColorBtn';
  3033. div.appendChild(linkButton);
  3034. mxUtils.br(div);
  3035. return {
  3036. getColor: function()
  3037. {
  3038. return linkColor;
  3039. },
  3040. getTarget: function()
  3041. {
  3042. return linkSelect.value;
  3043. },
  3044. focus: function()
  3045. {
  3046. linkSelect.focus();
  3047. }
  3048. };
  3049. }
  3050. /**
  3051. *
  3052. */
  3053. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  3054. {
  3055. var file = this.getCurrentFile();
  3056. var params = [];
  3057. if (lightbox)
  3058. {
  3059. params.push('lightbox=1');
  3060. if (linkTarget != 'auto')
  3061. {
  3062. params.push('target=' + linkTarget);
  3063. }
  3064. if (linkColor != null && linkColor != mxConstants.NONE)
  3065. {
  3066. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  3067. }
  3068. if (editLink != null && editLink.length > 0)
  3069. {
  3070. params.push('edit=' + encodeURIComponent(editLink));
  3071. }
  3072. if (layers)
  3073. {
  3074. params.push('layers=1');
  3075. }
  3076. if (this.editor.graph.foldingEnabled)
  3077. {
  3078. params.push('nav=1');
  3079. }
  3080. }
  3081. if (allPages && this.pages != null && this.currentPage != null)
  3082. {
  3083. for (var i = 0; i < this.pages.length; i++)
  3084. {
  3085. if (this.pages[i] == this.currentPage)
  3086. {
  3087. if (i > 0)
  3088. {
  3089. params.push('page=' + i);
  3090. }
  3091. break;
  3092. }
  3093. }
  3094. }
  3095. var data = '';
  3096. var addTitle = true;
  3097. if (url != null)
  3098. {
  3099. data = '#U' + encodeURIComponent(url);
  3100. }
  3101. else
  3102. {
  3103. var file = this.getCurrentFile();
  3104. // Fallback to non-public URL for Drive files
  3105. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  3106. {
  3107. data = '#' + file.getHash();
  3108. addTitle = false;
  3109. }
  3110. else
  3111. {
  3112. data = '#R' + encodeURIComponent((allPages) ?
  3113. this.getFileData(true, null, null, null, null, null, null, true) :
  3114. this.editor.graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  3115. }
  3116. }
  3117. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  3118. {
  3119. params.push('title=' + encodeURIComponent(file.getTitle()));
  3120. }
  3121. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || !(/.*\.draw\.io$/.test(window.location.hostname))) ?
  3122. 'https://www.draw.io/' : 'https://' + window.location.host + '/') +
  3123. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  3124. };
  3125. /**
  3126. *
  3127. */
  3128. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  3129. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  3130. {
  3131. var s = this.getBasenames();
  3132. var data = {};
  3133. if (linkColor != '' && linkColor != mxConstants.NONE)
  3134. {
  3135. data.highlight = linkColor;
  3136. }
  3137. if (linkTarget !== 'auto')
  3138. {
  3139. data.target = linkTarget;
  3140. }
  3141. if (!lightbox)
  3142. {
  3143. data.lightbox = false;
  3144. }
  3145. data.nav = this.editor.graph.foldingEnabled;
  3146. var zoom = parseInt(initialZoom);
  3147. if (!isNaN(zoom) && zoom != 100)
  3148. {
  3149. data.zoom = zoom / 100;
  3150. }
  3151. var tb = [];
  3152. if (allPages)
  3153. {
  3154. tb.push('pages');
  3155. data.resize = true;
  3156. if (this.pages != null && this.currentPage != null)
  3157. {
  3158. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  3159. }
  3160. }
  3161. if (zoomEnabled)
  3162. {
  3163. tb.push('zoom');
  3164. data.resize = true;
  3165. }
  3166. if (layers)
  3167. {
  3168. tb.push('layers');
  3169. }
  3170. if (tb.length > 0)
  3171. {
  3172. if (lightbox)
  3173. {
  3174. tb.push('lightbox');
  3175. }
  3176. data.toolbar = tb.join(' ');
  3177. }
  3178. if (editLink != null && editLink.length > 0)
  3179. {
  3180. data.edit = editLink;
  3181. }
  3182. if (publicUrl != null)
  3183. {
  3184. data.url = publicUrl;
  3185. }
  3186. else
  3187. {
  3188. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  3189. }
  3190. var value = '<div class="mxgraph" style="' +
  3191. ((fit) ? 'max-width:100%;' : '') +
  3192. ((tb != '') ? 'border:1px solid transparent;' : '') +
  3193. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  3194. var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
  3195. var s2 = (fetchParam.length > 0) ?
  3196. (((urlParams['dev'] == '1') ?
  3197. 'https://test.draw.io/embed2.js?dev=1' :
  3198. 'https://www.draw.io/embed2.js?')) + fetchParam :
  3199. (((urlParams['dev'] == '1') ?
  3200. 'https://test.draw.io/js/viewer.min.js' :
  3201. 'https://www.draw.io/js/viewer.min.js'));
  3202. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  3203. fn(value, scr);
  3204. };
  3205. /**
  3206. *
  3207. */
  3208. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  3209. {
  3210. var div = document.createElement('div');
  3211. div.style.whiteSpace = 'nowrap';
  3212. var graph = this.editor.graph;
  3213. var hd = document.createElement('h3');
  3214. mxUtils.write(hd, mxResources.get('html'));
  3215. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  3216. div.appendChild(hd);
  3217. var radioSection = document.createElement('div');
  3218. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  3219. var publicUrlRadio = document.createElement('input');
  3220. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  3221. publicUrlRadio.setAttribute('value', 'url');
  3222. publicUrlRadio.setAttribute('type', 'radio');
  3223. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  3224. var copyRadio = publicUrlRadio.cloneNode(true);
  3225. copyRadio.setAttribute('value', 'copy');
  3226. radioSection.appendChild(copyRadio);
  3227. var span = document.createElement('span');
  3228. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  3229. radioSection.appendChild(span);
  3230. mxUtils.br(radioSection);
  3231. radioSection.appendChild(publicUrlRadio);
  3232. var span = document.createElement('span');
  3233. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  3234. radioSection.appendChild(span);
  3235. var file = this.getCurrentFile();
  3236. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  3237. {
  3238. var testLink = document.createElement('a');
  3239. testLink.style.paddingLeft = '12px';
  3240. testLink.style.color = 'gray';
  3241. testLink.setAttribute('href', 'javascript:void(0);');
  3242. mxUtils.write(testLink, mxResources.get('share'));
  3243. radioSection.appendChild(testLink);
  3244. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  3245. {
  3246. this.hideDialog();
  3247. this.drive.showPermissions(file.getId());
  3248. }));
  3249. }
  3250. copyRadio.setAttribute('checked', 'checked');
  3251. if (publicUrl == null)
  3252. {
  3253. publicUrlRadio.setAttribute('disabled', 'disabled');
  3254. }
  3255. div.appendChild(radioSection);
  3256. var linkSection = this.addLinkSection(div);
  3257. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  3258. mxUtils.write(div, ':');
  3259. var zoomInput = document.createElement('input');
  3260. zoomInput.setAttribute('type', 'text');
  3261. zoomInput.style.marginRight = '16px';
  3262. zoomInput.style.width = '60px';
  3263. zoomInput.style.marginLeft = '4px';
  3264. zoomInput.style.marginRight = '12px';
  3265. zoomInput.value = '100%';
  3266. div.appendChild(zoomInput);
  3267. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  3268. var hasPages = this.pages != null && this.pages.length > 1;
  3269. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  3270. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  3271. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3272. var editSection = this.addEditButton(div, lightbox);
  3273. var edit = editSection.getEditInput();
  3274. edit.style.marginBottom = '16px';
  3275. mxEvent.addListener(lightbox, 'change', function()
  3276. {
  3277. if (lightbox.checked)
  3278. {
  3279. edit.removeAttribute('disabled');
  3280. }
  3281. else
  3282. {
  3283. edit.setAttribute('disabled', 'disabled');
  3284. }
  3285. if (edit.checked && lightbox.checked)
  3286. {
  3287. editSection.getEditSelect().removeAttribute('disabled');
  3288. }
  3289. else
  3290. {
  3291. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3292. }
  3293. });
  3294. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3295. {
  3296. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  3297. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  3298. editSection.getLink());
  3299. }), null, btnLabel, helpLink);
  3300. this.showDialog(dlg.container, 340, 384, true, true);
  3301. copyRadio.focus();
  3302. };
  3303. /**
  3304. *
  3305. */
  3306. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  3307. {
  3308. var div = document.createElement('div');
  3309. div.style.whiteSpace = 'nowrap';
  3310. var graph = this.editor.graph;
  3311. var hd = document.createElement('h3');
  3312. mxUtils.write(hd, title || mxResources.get('link'));
  3313. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  3314. div.appendChild(hd);
  3315. var file = this.getCurrentFile();
  3316. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  3317. var dy = 0;
  3318. if (file != null && file.constructor == window.DriveFile && !hideShare)
  3319. {
  3320. dy = 80;
  3321. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  3322. var hintSection = document.createElement('div');
  3323. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  3324. var text = document.createElement('div');
  3325. text.style.whiteSpace = 'normal';
  3326. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  3327. hintSection.appendChild(text);
  3328. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  3329. {
  3330. this.drive.showPermissions(file.getId());
  3331. }));
  3332. shareBtn.style.marginTop = '12px';
  3333. shareBtn.className = 'geBtn';
  3334. hintSection.appendChild(shareBtn);
  3335. div.appendChild(hintSection);
  3336. var testLink = document.createElement('a');
  3337. testLink.style.paddingLeft = '12px';
  3338. testLink.style.color = 'gray';
  3339. testLink.style.fontSize = '11px';
  3340. testLink.setAttribute('href', 'javascript:void(0);');
  3341. mxUtils.write(testLink, mxResources.get('check'));
  3342. hintSection.appendChild(testLink);
  3343. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  3344. {
  3345. if (this.spinner.spin(document.body, mxResources.get('loading')))
  3346. {
  3347. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  3348. {
  3349. this.spinner.stop();
  3350. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  3351. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  3352. this.showDialog(dlg.container, 300, 80, true, false);
  3353. dlg.init();
  3354. }));
  3355. }
  3356. }));
  3357. }
  3358. var widthInput = null;
  3359. var heightInput = null;
  3360. if (width != null || height != null)
  3361. {
  3362. dy += 30;
  3363. mxUtils.write(div, mxResources.get('width') + ':');
  3364. widthInput = document.createElement('input');
  3365. widthInput.setAttribute('type', 'text');
  3366. widthInput.style.marginRight = '16px';
  3367. widthInput.style.width = '50px';
  3368. widthInput.style.marginLeft = '6px';
  3369. widthInput.style.marginRight = '16px';
  3370. widthInput.style.marginBottom = '10px';
  3371. widthInput.value = '100%';
  3372. div.appendChild(widthInput);
  3373. mxUtils.write(div, mxResources.get('height') + ':');
  3374. heightInput = document.createElement('input');
  3375. heightInput.setAttribute('type', 'text');
  3376. heightInput.style.width = '50px';
  3377. heightInput.style.marginLeft = '6px';
  3378. heightInput.style.marginBottom = '10px';
  3379. heightInput.value = height + 'px';
  3380. div.appendChild(heightInput);
  3381. mxUtils.br(div);
  3382. }
  3383. var linkSection = this.addLinkSection(div, showFrameOption);
  3384. var hasPages = this.pages != null && this.pages.length > 1;
  3385. var allPages = null;
  3386. if (file == null || file.constructor != window.DriveFile || hideShare)
  3387. {
  3388. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  3389. }
  3390. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3391. var editSection = this.addEditButton(div, lightbox);
  3392. var edit = editSection.getEditInput();
  3393. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  3394. layers.style.marginLeft = edit.style.marginLeft;
  3395. layers.style.marginBottom = '16px';
  3396. layers.style.marginTop = '8px';
  3397. mxEvent.addListener(lightbox, 'change', function()
  3398. {
  3399. if (lightbox.checked)
  3400. {
  3401. layers.removeAttribute('disabled');
  3402. edit.removeAttribute('disabled');
  3403. }
  3404. else
  3405. {
  3406. layers.setAttribute('disabled', 'disabled');
  3407. edit.setAttribute('disabled', 'disabled');
  3408. }
  3409. if (edit.checked && lightbox.checked)
  3410. {
  3411. editSection.getEditSelect().removeAttribute('disabled');
  3412. }
  3413. else
  3414. {
  3415. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3416. }
  3417. });
  3418. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3419. {
  3420. fn(linkSection.getTarget(), linkSection.getColor(),
  3421. (allPages == null) ? true : allPages.checked,
  3422. lightbox.checked, editSection.getLink(),
  3423. layers.checked, (widthInput != null) ? widthInput.value : null,
  3424. (heightInput != null) ? heightInput.value : null);
  3425. }), null, mxResources.get('create'), helpLink);
  3426. this.showDialog(dlg.container, 340, 254 + dy, true, true);
  3427. if (widthInput != null)
  3428. {
  3429. widthInput.focus();
  3430. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3431. {
  3432. widthInput.select();
  3433. }
  3434. else
  3435. {
  3436. document.execCommand('selectAll', false, null);
  3437. }
  3438. }
  3439. else
  3440. {
  3441. linkSection.focus();
  3442. }
  3443. };
  3444. /**
  3445. *
  3446. */
  3447. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  3448. {
  3449. var div = document.createElement('div');
  3450. div.style.whiteSpace = 'nowrap';
  3451. var hd = document.createElement('h3');
  3452. mxUtils.write(hd, mxResources.get('image'));
  3453. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3454. div.appendChild(hd);
  3455. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  3456. this.editor.graph.isSelectionEmpty());
  3457. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  3458. if (include != null)
  3459. {
  3460. include.style.marginBottom = '16px';
  3461. }
  3462. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3463. {
  3464. callback(!selection.checked, (include != null) ? include.checked : false);
  3465. }), null, btnLabel, helpLink);
  3466. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 146, true, true);
  3467. };
  3468. /**
  3469. *
  3470. */
  3471. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  3472. cropOption, defaultInclude, format)
  3473. {
  3474. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  3475. var div = document.createElement('div');
  3476. div.style.whiteSpace = 'nowrap';
  3477. var graph = this.editor.graph;
  3478. var height = (format == 'jpeg') ? 196 : 300;
  3479. var hd = document.createElement('h3');
  3480. mxUtils.write(hd, title);
  3481. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  3482. div.appendChild(hd);
  3483. mxUtils.write(div, mxResources.get('zoom') + ':');
  3484. var zoomInput = document.createElement('input');
  3485. zoomInput.setAttribute('type', 'text');
  3486. zoomInput.style.marginRight = '16px';
  3487. zoomInput.style.width = '60px';
  3488. zoomInput.style.marginLeft = '4px';
  3489. zoomInput.style.marginRight = '12px';
  3490. zoomInput.value = this.lastExportZoom || '100%';
  3491. div.appendChild(zoomInput);
  3492. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  3493. var borderInput = document.createElement('input');
  3494. borderInput.setAttribute('type', 'text');
  3495. borderInput.style.marginRight = '16px';
  3496. borderInput.style.width = '60px';
  3497. borderInput.style.marginLeft = '4px';
  3498. borderInput.value = this.lastExportBorder || '0';
  3499. div.appendChild(borderInput);
  3500. mxUtils.br(div);
  3501. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  3502. graph.background == mxConstants.NONE || graph.background == null, null, null, format != 'jpeg');
  3503. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  3504. false, graph.isSelectionEmpty());
  3505. var cb6 = document.createElement('input');
  3506. cb6.style.marginTop = '16px';
  3507. cb6.style.marginRight = '8px';
  3508. cb6.style.marginLeft = '24px';
  3509. cb6.setAttribute('disabled', 'disabled');
  3510. cb6.setAttribute('type', 'checkbox');
  3511. if (cropOption)
  3512. {
  3513. div.appendChild(cb6);
  3514. mxUtils.write(div, mxResources.get('crop'));
  3515. mxUtils.br(div);
  3516. height += 26;
  3517. mxEvent.addListener(selection, 'change', function()
  3518. {
  3519. if (selection.checked)
  3520. {
  3521. cb6.removeAttribute('disabled');
  3522. }
  3523. else
  3524. {
  3525. cb6.setAttribute('disabled', 'disabled');
  3526. }
  3527. });
  3528. }
  3529. if (!graph.isSelectionEmpty())
  3530. {
  3531. cb6.setAttribute('checked', 'checked');
  3532. cb6.defaultChecked = true;
  3533. }
  3534. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  3535. var cb5 = document.createElement('input');
  3536. cb5.style.marginTop = '16px';
  3537. cb5.style.marginRight = '8px';
  3538. cb5.setAttribute('type', 'checkbox');
  3539. if (this.isOffline() || !this.canvasSupported)
  3540. {
  3541. cb5.setAttribute('disabled', 'disabled');
  3542. }
  3543. if (embedOption)
  3544. {
  3545. div.appendChild(cb5);
  3546. mxUtils.write(div, mxResources.get('embedImages'));
  3547. mxUtils.br(div);
  3548. height += 26;
  3549. }
  3550. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  3551. var hasPages = this.pages != null && this.pages.length > 1;
  3552. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  3553. allPages.style.marginLeft = '24px';
  3554. allPages.style.marginBottom = '16px';
  3555. if (!hasPages)
  3556. {
  3557. allPages.style.visibility = 'hidden';
  3558. }
  3559. mxEvent.addListener(include, 'change', function()
  3560. {
  3561. if (include.checked && hasPages)
  3562. {
  3563. allPages.removeAttribute('disabled');
  3564. }
  3565. else
  3566. {
  3567. allPages.setAttribute('disabled', 'disabled');
  3568. }
  3569. });
  3570. if (!defaultInclude || !hasPages)
  3571. {
  3572. allPages.setAttribute('disabled', 'disabled');
  3573. }
  3574. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3575. {
  3576. this.lastExportBorder = borderInput.value;
  3577. this.lastExportZoom = zoomInput.value;
  3578. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  3579. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked);
  3580. }), null, btnLabel, helpLink);
  3581. this.showDialog(dlg.container, 340, height, true, true);
  3582. zoomInput.focus();
  3583. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3584. {
  3585. zoomInput.select();
  3586. }
  3587. else
  3588. {
  3589. document.execCommand('selectAll', false, null);
  3590. }
  3591. };
  3592. /**
  3593. *
  3594. */
  3595. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  3596. {
  3597. var div = document.createElement('div');
  3598. div.style.whiteSpace = 'nowrap';
  3599. var graph = this.editor.graph;
  3600. if (title != null)
  3601. {
  3602. var hd = document.createElement('h3');
  3603. mxUtils.write(hd, title);
  3604. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3605. div.appendChild(hd);
  3606. }
  3607. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  3608. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  3609. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  3610. var image = this.addCheckbox(div, imageLabel);
  3611. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3612. var editSection = this.addEditButton(div, lightbox);
  3613. var edit = editSection.getEditInput();
  3614. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  3615. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  3616. layers.style.marginLeft = edit.style.marginLeft;
  3617. layers.style.marginBottom = '12px';
  3618. layers.style.marginTop = '8px';
  3619. mxEvent.addListener(lightbox, 'change', function()
  3620. {
  3621. if (lightbox.checked)
  3622. {
  3623. if (hasLayers)
  3624. {
  3625. layers.removeAttribute('disabled');
  3626. }
  3627. edit.removeAttribute('disabled');
  3628. }
  3629. else
  3630. {
  3631. layers.setAttribute('disabled', 'disabled');
  3632. edit.setAttribute('disabled', 'disabled');
  3633. }
  3634. if (edit.checked && lightbox.checked)
  3635. {
  3636. editSection.getEditSelect().removeAttribute('disabled');
  3637. }
  3638. else
  3639. {
  3640. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3641. }
  3642. });
  3643. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3644. {
  3645. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  3646. editSection.getLink(), layers.checked);
  3647. }), null, mxResources.get('embed'), helpLink);
  3648. this.showDialog(dlg.container, 280, 280, true, true);
  3649. };
  3650. /**
  3651. *
  3652. */
  3653. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  3654. {
  3655. var bounds = this.editor.graph.getGraphBounds();
  3656. function doUpdate(dataUri)
  3657. {
  3658. var onclick = ' ';
  3659. var css = '';
  3660. // Adds double click handling
  3661. if (lightbox)
  3662. {
  3663. // KNOWN: Message passing does not seem to work in IE11
  3664. 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(" +
  3665. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3666. ((edit) ? "&edit=_blank" : "") +
  3667. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3668. css += 'cursor:pointer;';
  3669. }
  3670. if (fit)
  3671. {
  3672. css += 'max-width:100%;';
  3673. }
  3674. var atts = '';
  3675. if (retina)
  3676. {
  3677. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  3678. }
  3679. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3680. };
  3681. if (this.isExportToCanvas())
  3682. {
  3683. var scale = 1;
  3684. var ignoreSelection = true;
  3685. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3686. {
  3687. var xml = (lightbox) ? this.getFileData(true) : null;
  3688. var data = this.createImageDataUri(canvas, xml, 'png');
  3689. doUpdate(data);
  3690. }), null, null, null, mxUtils.bind(this, function(e)
  3691. {
  3692. err({message: mxResources.get('unknownError')});
  3693. }), null, true, (retina) ? 2 : 1, null, shadow);
  3694. }
  3695. else
  3696. {
  3697. var data = this.getFileData(true);
  3698. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  3699. {
  3700. var size = '';
  3701. if (retina)
  3702. {
  3703. size = '&w=' + Math.round(2 * bounds.width) +
  3704. '&h=' + Math.round(2 * bounds.height);
  3705. }
  3706. var embed = (lightbox) ? '1' : '0';
  3707. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  3708. '&base64=1&embedXml=' + embed + size + '&xml=' +
  3709. encodeURIComponent(data));
  3710. // LATER: Updates on each change, add a delay
  3711. req.send(mxUtils.bind(this, function()
  3712. {
  3713. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  3714. {
  3715. // Fixes possible "incorrect function" for select() on
  3716. // DOM node which is no longer in document with IE11
  3717. doUpdate('data:image/png;base64,' + req.getText());
  3718. }
  3719. else
  3720. {
  3721. err({message: mxResources.get('unknownError')});
  3722. }
  3723. }));
  3724. }
  3725. else
  3726. {
  3727. err({message: mxResources.get('drawingTooLarge')});
  3728. }
  3729. }
  3730. };
  3731. /**
  3732. *
  3733. */
  3734. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  3735. {
  3736. var svgRoot = this.editor.graph.getSvg();
  3737. // Keeps hashtag links on same page
  3738. var links = svgRoot.getElementsByTagName('a');
  3739. if (links != null)
  3740. {
  3741. for (var i = 0; i < links.length; i++)
  3742. {
  3743. var href = links[i].getAttribute('href');
  3744. if (href != null && href.charAt(0) == '#' &&
  3745. links[i].getAttribute('target') == '_blank')
  3746. {
  3747. links[i].removeAttribute('target');
  3748. }
  3749. }
  3750. }
  3751. if (lightbox)
  3752. {
  3753. svgRoot.setAttribute('content', this.getFileData(true));
  3754. }
  3755. // Adds shadow filter
  3756. if (shadow)
  3757. {
  3758. this.editor.graph.addSvgShadow(svgRoot);
  3759. }
  3760. // SVG inside image tag
  3761. if (image)
  3762. {
  3763. var onclick = ' ';
  3764. var css = '';
  3765. // Adds double click handling
  3766. if (lightbox)
  3767. {
  3768. // KNOWN: Message passing does not seem to work in IE11
  3769. 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(" +
  3770. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3771. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3772. css += 'cursor:pointer;';
  3773. }
  3774. if (fit)
  3775. {
  3776. css += 'max-width:100%;';
  3777. }
  3778. // Images inside IMG don't seem to work so embed them all
  3779. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  3780. {
  3781. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  3782. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3783. }));
  3784. }
  3785. else
  3786. {
  3787. var css = '';
  3788. // Adds double click handling
  3789. if (lightbox)
  3790. {
  3791. // KNOWN: Message passing does not seem to work in IE11
  3792. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  3793. // Ignores link events
  3794. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  3795. // Focus existing lightbox
  3796. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  3797. // Message handling
  3798. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  3799. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  3800. "window.addEventListener('message',r);" +
  3801. // Opens lightbox window
  3802. "svg.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3803. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  3804. svgRoot.setAttribute('onclick', js);
  3805. css += 'cursor:pointer;';
  3806. }
  3807. // Adds responsive size
  3808. if (fit)
  3809. {
  3810. var w = parseInt(svgRoot.getAttribute('width'));
  3811. var h = parseInt(svgRoot.getAttribute('height'));
  3812. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  3813. css += 'max-width:100%;max-height:' + h + 'px;';
  3814. svgRoot.removeAttribute('height');
  3815. }
  3816. if (css != '')
  3817. {
  3818. svgRoot.setAttribute('style', css);
  3819. }
  3820. fn(mxUtils.getXml(svgRoot));
  3821. }
  3822. };
  3823. /**
  3824. * Translates this point by the given vector.
  3825. *
  3826. * @param {number} dx X-coordinate of the translation.
  3827. * @param {number} dy Y-coordinate of the translation.
  3828. */
  3829. EditorUi.prototype.timeSince = function(date)
  3830. {
  3831. var seconds = Math.floor((new Date() - date) / 1000);
  3832. var interval = Math.floor(seconds / 31536000);
  3833. if (interval > 1)
  3834. {
  3835. return interval + ' ' + mxResources.get('years');
  3836. }
  3837. interval = Math.floor(seconds / 2592000);
  3838. if (interval > 1)
  3839. {
  3840. return interval + ' ' + mxResources.get('months');
  3841. }
  3842. interval = Math.floor(seconds / 86400);
  3843. if (interval > 1)
  3844. {
  3845. return interval + ' ' + mxResources.get('days');
  3846. }
  3847. interval = Math.floor(seconds / 3600);
  3848. if (interval > 1)
  3849. {
  3850. return interval + ' ' + mxResources.get('hours');
  3851. }
  3852. interval = Math.floor(seconds / 60);
  3853. if (interval > 1)
  3854. {
  3855. return interval + ' ' + mxResources.get('minutes');
  3856. }
  3857. if (interval == 1)
  3858. {
  3859. return interval + ' ' + mxResources.get('minute');
  3860. }
  3861. return null;
  3862. };
  3863. /**
  3864. * Converts math in the given SVG
  3865. */
  3866. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  3867. {
  3868. // FIXME: Only horizontal dash in output so better no conversion at all
  3869. /*if (false && graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  3870. {
  3871. // Workaround for lost gradients in Chrome after remove from DOM
  3872. var elts = svgRoot.getElementsByTagName('*');
  3873. for (var i = 0; i < elts.length; i++)
  3874. {
  3875. if (elts[i].getAttribute('id') != null)
  3876. {
  3877. elts[i].setAttribute('id', 'mxTemporaryPrefix-' + elts[i].getAttribute('id'));
  3878. }
  3879. }
  3880. // Temporarily attaches to DOM for rendering
  3881. svgRoot.style.visibility = 'hidden';
  3882. document.body.appendChild(svgRoot);
  3883. Editor.MathJaxRender(svgRoot);
  3884. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  3885. {
  3886. // Removes from DOM
  3887. svgRoot.parentNode.removeChild(svgRoot);
  3888. svgRoot.style.visibility = '';
  3889. // Restores original IDs
  3890. for (var i = 0; i < elts.length; i++)
  3891. {
  3892. if (elts[i].getAttribute('id') != null)
  3893. {
  3894. elts[i].setAttribute('id', elts[i].getAttribute('id').substring('mxTemporaryPrefix-'.length));
  3895. }
  3896. }
  3897. // Keeping scale but moving translate only works for image export which
  3898. // is fine since we do not want the SVG export to contain a workaround.
  3899. // See https://github.com/mathjax/MathJax/issues/279
  3900. if (fixPosition && navigator.userAgent.indexOf('AppleWebKit/') >= 0)
  3901. {
  3902. var fo = svgRoot.getElementsByTagName('foreignObject');
  3903. for (var i = 0; i < fo.length; i++)
  3904. {
  3905. var tr = fo[i].parentNode.parentNode.getAttribute('transform');
  3906. var translate = /translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/.exec(tr);
  3907. fo[i].setAttribute('x', Math.round(translate[1]));
  3908. fo[i].setAttribute('y', Math.round(translate[2]));
  3909. // Must use translate for crisp rendering
  3910. fo[i].parentNode.parentNode.setAttribute('transform', 'translate(0.5,0.5)' + tr.substring(tr.indexOf(')') + 1));
  3911. }
  3912. }
  3913. callback();
  3914. }));
  3915. }
  3916. else*/
  3917. {
  3918. callback();
  3919. }
  3920. };
  3921. /**
  3922. *
  3923. */
  3924. EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
  3925. {
  3926. if (node != null)
  3927. {
  3928. var diagramNode = null;
  3929. if (node.nodeName == 'diagram')
  3930. {
  3931. diagramNode = node;
  3932. }
  3933. else if (node.nodeName == 'mxfile')
  3934. {
  3935. var diagrams = node.getElementsByTagName('diagram');
  3936. if (diagrams.length > 0)
  3937. {
  3938. diagramNode = diagrams[0];
  3939. var graphGetGlobalVariable = graph.getGlobalVariable;
  3940. graph.getGlobalVariable = function(name)
  3941. {
  3942. if (name == 'page')
  3943. {
  3944. return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
  3945. }
  3946. else if (name == 'pagenumber')
  3947. {
  3948. return 1;
  3949. }
  3950. return graphGetGlobalVariable.apply(this, arguments);
  3951. };
  3952. }
  3953. }
  3954. if (diagramNode != null)
  3955. {
  3956. var tmp = graph.decompress(mxUtils.getTextContent(diagramNode));
  3957. if (tmp != null && tmp.length > 0)
  3958. {
  3959. node = mxUtils.parseXml(tmp).documentElement;
  3960. }
  3961. }
  3962. }
  3963. // Hack to decode XML into temp graph via editor
  3964. var prev = this.editor.graph;
  3965. try
  3966. {
  3967. this.editor.graph = graph;
  3968. this.editor.setGraphXml(node);
  3969. }
  3970. catch (e)
  3971. {
  3972. // ignore
  3973. }
  3974. finally
  3975. {
  3976. this.editor.graph = prev;
  3977. }
  3978. return node;
  3979. };
  3980. /**
  3981. *
  3982. */
  3983. EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData)
  3984. {
  3985. var graph = this.editor.graph;
  3986. var diagramData = null;
  3987. // Exports PNG for given optional data
  3988. if (optionalData != null && optionalData.length > 0)
  3989. {
  3990. graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
  3991. document.body.appendChild(graph.container);
  3992. this.decodeNodeIntoGraph(this.editor.extractGraphModel(
  3993. mxUtils.parseXml(optionalData).documentElement, true), graph);
  3994. diagramData = optionalData;
  3995. }
  3996. // Exports PNG for first page while other page is showing
  3997. else if (this.pages != null && this.currentPage != this.pages[0])
  3998. {
  3999. graph = this.createTemporaryGraph(graph.getStylesheet());
  4000. var graphGetGlobalVariable = graph.getGlobalVariable;
  4001. var page = this.pages[0];
  4002. graph.getGlobalVariable = function(name)
  4003. {
  4004. if (name == 'page')
  4005. {
  4006. return page.getName();
  4007. }
  4008. else if (name == 'pagenumber')
  4009. {
  4010. return 1;
  4011. }
  4012. return graphGetGlobalVariable.apply(this, arguments);
  4013. };
  4014. document.body.appendChild(graph.container);
  4015. graph.model.setRoot(page.root);
  4016. }
  4017. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4018. {
  4019. try
  4020. {
  4021. if (diagramData == null)
  4022. {
  4023. diagramData = this.getFileData(true);
  4024. }
  4025. var data = canvas.toDataURL('image/png');
  4026. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel',
  4027. atob(this.editor.graph.compress(diagramData)));
  4028. success(data.substring(data.lastIndexOf(',') + 1));
  4029. // Removes temporary graph from DOM
  4030. if (graph != this.editor.graph)
  4031. {
  4032. graph.container.parentNode.removeChild(graph.container);
  4033. }
  4034. }
  4035. catch (e)
  4036. {
  4037. if (error != null)
  4038. {
  4039. error(e);
  4040. }
  4041. }
  4042. }), null, null, null, mxUtils.bind(this, function(e)
  4043. {
  4044. if (error != null)
  4045. {
  4046. error(e);
  4047. }
  4048. }), null, null, null, null, graph.shadowVisible, null, graph);
  4049. }
  4050. /**
  4051. * Returns the SVG of the diagram with embedded XML. If a callback function is
  4052. * used, the images are converted to data URIs.
  4053. */
  4054. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  4055. {
  4056. var bg = graph.background;
  4057. if (bg == mxConstants.NONE)
  4058. {
  4059. bg = null;
  4060. }
  4061. // Sets or disables alternate text for foreignObjects. Disabling is needed
  4062. // because PhantomJS seems to ignore switch statements and paint all text.
  4063. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  4064. if (xml != null)
  4065. {
  4066. svgRoot.setAttribute('content', xml);
  4067. }
  4068. if (url != null)
  4069. {
  4070. svgRoot.setAttribute('resource', url);
  4071. }
  4072. // LATER: Click on SVG content to start editing
  4073. // if (redirect != null)
  4074. // {
  4075. // // TODO: Ignore anchor tag source for click event
  4076. // svgRoot.setAttribute('style', 'cursor:pointer;');
  4077. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  4078. // }
  4079. if (callback != null)
  4080. {
  4081. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  4082. {
  4083. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  4084. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  4085. mxUtils.getXml(svgRoot));
  4086. }));
  4087. }
  4088. else
  4089. {
  4090. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  4091. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  4092. mxUtils.getXml(svgRoot);
  4093. }
  4094. };
  4095. /**
  4096. *
  4097. */
  4098. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  4099. {
  4100. format = (format != null) ? format : 'png';
  4101. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  4102. {
  4103. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  4104. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  4105. // Caches images
  4106. if (this.thumbImageCache == null)
  4107. {
  4108. this.thumbImageCache = new Object();
  4109. }
  4110. try
  4111. {
  4112. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4113. {
  4114. this.spinner.stop();
  4115. try
  4116. {
  4117. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  4118. null, null, ignoreSelection, currentPage) : null, format);
  4119. }
  4120. catch (e)
  4121. {
  4122. // Fallback to server-side image export
  4123. if (e.message == 'Invalid image')
  4124. {
  4125. this.downloadFile(format);
  4126. }
  4127. else
  4128. {
  4129. this.handleError(e);
  4130. }
  4131. }
  4132. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  4133. {
  4134. this.spinner.stop();
  4135. this.handleError(e);
  4136. }), null, ignoreSelection, scale || 1, transparentBackground,
  4137. addShadow, null, null, border, noCrop);
  4138. }
  4139. catch (e)
  4140. {
  4141. this.spinner.stop();
  4142. this.handleError(e);
  4143. }
  4144. }
  4145. };
  4146. /**
  4147. * For the fontCSS to be applied when rendering images on canvas, the actual
  4148. * font data must be made available via a data URI encoding of the file.
  4149. */
  4150. EditorUi.prototype.loadFonts = function(then)
  4151. {
  4152. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  4153. {
  4154. var parts = this.editor.fontCss.split('url(');
  4155. var waiting = 0;
  4156. var fonts = {};
  4157. // Strips leading and trailing quotes and spaces
  4158. function trimString(str)
  4159. {
  4160. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  4161. };
  4162. var finish = mxUtils.bind(this, function()
  4163. {
  4164. if (waiting == 0)
  4165. {
  4166. // Constructs string
  4167. var result = [parts[0]];
  4168. for (var j = 1; j < parts.length; j++)
  4169. {
  4170. var idx = parts[j].indexOf(')');
  4171. result.push('url("');
  4172. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  4173. result.push('"' + parts[j].substring(idx));
  4174. }
  4175. this.editor.resolvedFontCss = result.join('');
  4176. then();
  4177. }
  4178. });
  4179. if (parts.length > 0)
  4180. {
  4181. for (var i = 1; i < parts.length; i++)
  4182. {
  4183. var idx = parts[i].indexOf(')');
  4184. var format = null;
  4185. // Checks if there is a format directive
  4186. var fmtIdx = parts[i].indexOf('format(', idx);
  4187. if (fmtIdx > 0)
  4188. {
  4189. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  4190. }
  4191. (mxUtils.bind(this, function(url)
  4192. {
  4193. if (fonts[url] == null)
  4194. {
  4195. // Mark font es being fetched and fetch it
  4196. fonts[url] = url;
  4197. waiting++;
  4198. var mime = 'application/x-font-ttf';
  4199. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  4200. if (format == 'svg' || /(\.svg)($|\?)/i.test(url))
  4201. {
  4202. mime = 'image/svg+xml';
  4203. }
  4204. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url))
  4205. {
  4206. mime = 'application/x-font-opentype';
  4207. }
  4208. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url))
  4209. {
  4210. mime = 'application/font-woff';
  4211. }
  4212. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url))
  4213. {
  4214. mime = 'application/font-woff2';
  4215. }
  4216. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url))
  4217. {
  4218. mime = 'application/vnd.ms-fontobject';
  4219. }
  4220. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url))
  4221. {
  4222. mime = 'application/font-sfnt';
  4223. }
  4224. var realUrl = url;
  4225. if ((/^https?:\/\//.test(realUrl)) && !this.isCorsEnabledForUrl(realUrl))
  4226. {
  4227. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  4228. }
  4229. // LATER: Remove cache-control header
  4230. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  4231. {
  4232. fonts[url] = uri;
  4233. waiting--;
  4234. finish();
  4235. }), mxUtils.bind(this, function(err)
  4236. {
  4237. // LATER: handle error
  4238. waiting--;
  4239. finish();
  4240. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  4241. }
  4242. }))(trimString(parts[i].substring(0, idx)), format);
  4243. }
  4244. }
  4245. }
  4246. else
  4247. {
  4248. then();
  4249. }
  4250. };
  4251. /**
  4252. *
  4253. */
  4254. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  4255. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  4256. {
  4257. limitHeight = (limitHeight != null) ? limitHeight : true;
  4258. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  4259. graph = (graph != null) ? graph : this.editor.graph;
  4260. border = (border != null) ? border : 0;
  4261. var bg = (transparentBackground) ? null : graph.background;
  4262. if (bg == mxConstants.NONE)
  4263. {
  4264. bg = null;
  4265. }
  4266. if (bg == null)
  4267. {
  4268. bg = background;
  4269. }
  4270. // Handles special case where background is null but transparent is false
  4271. if (bg == null && transparentBackground == false)
  4272. {
  4273. bg = this.editor.graph.defaultPageBackgroundColor;
  4274. }
  4275. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection), mxUtils.bind(this, function(svgRoot)
  4276. {
  4277. var img = new Image();
  4278. img.onload = mxUtils.bind(this, function()
  4279. {
  4280. try
  4281. {
  4282. var canvas = document.createElement('canvas');
  4283. var w = parseInt(svgRoot.getAttribute('width'));
  4284. var h = parseInt(svgRoot.getAttribute('height'));
  4285. scale = (scale != null) ? scale : 1;
  4286. if (width != null)
  4287. {
  4288. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  4289. }
  4290. w = Math.ceil(scale * w) + 2 * border;
  4291. h = Math.ceil(scale * h) + 2 * border;
  4292. canvas.setAttribute('width', w);
  4293. canvas.setAttribute('height', h);
  4294. var ctx = canvas.getContext('2d');
  4295. if (bg != null)
  4296. {
  4297. ctx.beginPath();
  4298. ctx.rect(0, 0, w, h);
  4299. ctx.fillStyle = bg;
  4300. ctx.fill();
  4301. }
  4302. ctx.scale(scale, scale);
  4303. ctx.drawImage(img, border / scale, border / scale);
  4304. callback(canvas);
  4305. }
  4306. catch (e)
  4307. {
  4308. if (error != null)
  4309. {
  4310. error(e);
  4311. }
  4312. }
  4313. });
  4314. img.onerror = function(e)
  4315. {
  4316. //console.log('img', e, img.src);
  4317. if (error != null)
  4318. {
  4319. error(e);
  4320. }
  4321. };
  4322. try
  4323. {
  4324. if (addShadow)
  4325. {
  4326. this.editor.graph.addSvgShadow(svgRoot);
  4327. }
  4328. var done = mxUtils.bind(this, function()
  4329. {
  4330. if (this.editor.resolvedFontCss != null)
  4331. {
  4332. var st = document.createElement('style');
  4333. st.setAttribute('type', 'text/css');
  4334. st.innerHTML = this.editor.resolvedFontCss;
  4335. // Must be in defs section for FF to work
  4336. var defs = svgRoot.getElementsByTagName('defs');
  4337. defs[0].appendChild(st);
  4338. }
  4339. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  4340. {
  4341. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  4342. }));
  4343. });
  4344. this.loadFonts(done);
  4345. }
  4346. catch (e)
  4347. {
  4348. //console.log('src', e, img.src);
  4349. if (error != null)
  4350. {
  4351. error(e);
  4352. }
  4353. }
  4354. }), imageCache, converter);
  4355. };
  4356. /**
  4357. * Converts all images in the SVG output to data URIs for immediate rendering
  4358. */
  4359. EditorUi.prototype.createImageUrlConverter = function()
  4360. {
  4361. var converter = new mxUrlConverter();
  4362. converter.updateBaseUrl();
  4363. // Extends convert to avoid CORS using an image proxy server where needed
  4364. var convert = converter.convert;
  4365. var self = this;
  4366. converter.convert = function(src)
  4367. {
  4368. if (src != null)
  4369. {
  4370. var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  4371. if (remote && !navigator.onLine)
  4372. {
  4373. src = self.svgBrokenImage.src;
  4374. }
  4375. else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  4376. (!self.crossOriginImages || !self.isCorsEnabledForUrl(src)))
  4377. {
  4378. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  4379. }
  4380. else if (src.substring(0, 19) != 'chrome-extension://')
  4381. {
  4382. src = convert.apply(this, arguments);
  4383. }
  4384. }
  4385. return src;
  4386. };
  4387. return converter;
  4388. };
  4389. /**
  4390. * Converts all images in the SVG output to data URIs for immediate rendering
  4391. */
  4392. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  4393. {
  4394. // Converts images to data URLs for immediate painting
  4395. if (converter == null)
  4396. {
  4397. converter = this.createImageUrlConverter();
  4398. }
  4399. // Barrier for asynchronous image loading
  4400. var counter = 0;
  4401. function inc()
  4402. {
  4403. counter++;
  4404. };
  4405. function dec()
  4406. {
  4407. counter--;
  4408. if (counter == 0)
  4409. {
  4410. callback(svgRoot);
  4411. }
  4412. };
  4413. var cache = imageCache || new Object();
  4414. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  4415. {
  4416. var images = svgRoot.getElementsByTagName(tagName);
  4417. for (var i = 0; i < images.length; i++)
  4418. {
  4419. (mxUtils.bind(this, function(img)
  4420. {
  4421. var src = converter.convert(img.getAttribute(srcAttr));
  4422. // Data URIs are pass-through
  4423. if (src != null && src.substring(0, 5) != 'data:')
  4424. {
  4425. var tmp = cache[src];
  4426. if (tmp == null)
  4427. {
  4428. inc();
  4429. this.convertImageToDataUri(src, function(uri)
  4430. {
  4431. if (uri != null)
  4432. {
  4433. cache[src] = uri;
  4434. img.setAttribute(srcAttr, uri);
  4435. }
  4436. dec();
  4437. });
  4438. }
  4439. else
  4440. {
  4441. img.setAttribute(srcAttr, tmp);
  4442. }
  4443. }
  4444. else if (src != null)
  4445. {
  4446. img.setAttribute(srcAttr, src);
  4447. }
  4448. }))(images[i]);
  4449. }
  4450. });
  4451. // Converts all known image tags in output
  4452. // LATER: Add support for images in CSS
  4453. convertImages('image', 'xlink:href');
  4454. convertImages('img', 'src');
  4455. // All from cache or no images
  4456. if (counter == 0)
  4457. {
  4458. callback(svgRoot);
  4459. }
  4460. };
  4461. /**
  4462. * Checks if the client is authorized and calls the next step.
  4463. */
  4464. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix)
  4465. {
  4466. try
  4467. {
  4468. var binary = forceBinary || /(\.png)($|\?)/i.test(url) ||
  4469. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url);
  4470. retry = (retry != null) ? retry : true;
  4471. var fn = mxUtils.bind(this, function()
  4472. {
  4473. mxUtils.get(url, mxUtils.bind(this, function(req)
  4474. {
  4475. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4476. {
  4477. if (success != null)
  4478. {
  4479. var data = req.getText();
  4480. // Returns PNG as base64 encoded data URI
  4481. if (binary)
  4482. {
  4483. // NOTE: This requires BinaryToArray VB script in the page
  4484. if ((document.documentMode == 9 || document.documentMode == 10) &&
  4485. typeof window.mxUtilsBinaryToArray !== 'undefined')
  4486. {
  4487. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  4488. var tmp = new Array(bin.length);
  4489. for (var i = 0; i < bin.length; i++)
  4490. {
  4491. tmp[i] = String.fromCharCode(bin[i]);
  4492. }
  4493. data = tmp.join('');
  4494. }
  4495. // LATER: Could be JPG but modern browsers
  4496. // ignore the mime type in the data URI
  4497. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  4498. data = dataUriPrefix + this.base64Encode(data);
  4499. }
  4500. success(data);
  4501. }
  4502. }
  4503. else if (error != null)
  4504. {
  4505. error({code: App.ERROR_UNKNOWN}, req);
  4506. }
  4507. }), function()
  4508. {
  4509. if (error != null)
  4510. {
  4511. error({code: App.ERROR_UNKNOWN});
  4512. }
  4513. }, binary, this.timeout, function()
  4514. {
  4515. if (retry && error != null)
  4516. {
  4517. error({code: App.ERROR_TIMEOUT, retry: fn});
  4518. }
  4519. });
  4520. });
  4521. fn();
  4522. }
  4523. catch (e)
  4524. {
  4525. if (error != null)
  4526. {
  4527. error(e);
  4528. }
  4529. }
  4530. };
  4531. /**
  4532. * Returns true if the given URL is known to have CORS headers.
  4533. */
  4534. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  4535. {
  4536. if (urlParams['cors'] != null && this.corsRegExp == null)
  4537. {
  4538. this.corsRegExp = new RegExp(decodeURIComponent(urlParams['cors']));
  4539. }
  4540. return (this.corsRegExp != null && this.corsRegExp.test(url)) ||
  4541. url.substring(0, 34) === 'https://raw.githubusercontent.com/' ||
  4542. url.substring(0, 23) === 'https://cdn.rawgit.com/' ||
  4543. url.substring(0, 19) === 'https://rawgit.com/' ||
  4544. /^https?:\/\/[^\/]*\.iconfinder.com\//.test(url) ||
  4545. /^https?:\/\/[^\/]*\.draw\.io\/proxy/.test(url) ||
  4546. /^https?:\/\/[^\/]*\.github\.io\//.test(url);
  4547. };
  4548. /**
  4549. * Translates this point by the given vector.
  4550. *
  4551. * @param {number} dx X-coordinate of the translation.
  4552. * @param {number} dy Y-coordinate of the translation.
  4553. */
  4554. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  4555. {
  4556. if (/(\.svg)$/i.test(url))
  4557. {
  4558. mxUtils.get(url, mxUtils.bind(this, function(req)
  4559. {
  4560. callback(this.createSvgDataUri(req.getText()));
  4561. }),
  4562. function()
  4563. {
  4564. callback(this.svgBrokenImage.src);
  4565. });
  4566. }
  4567. else
  4568. {
  4569. var img = new Image();
  4570. var self = this;
  4571. if (this.crossOriginImages)
  4572. {
  4573. img.crossOrigin = 'anonymous';
  4574. }
  4575. img.onload = function()
  4576. {
  4577. var canvas = document.createElement('canvas');
  4578. var ctx = canvas.getContext('2d');
  4579. canvas.height = img.height;
  4580. canvas.width = img.width;
  4581. ctx.drawImage(img, 0, 0);
  4582. try
  4583. {
  4584. callback(canvas.toDataURL());
  4585. }
  4586. catch (e)
  4587. {
  4588. callback(self.svgBrokenImage.src);
  4589. }
  4590. };
  4591. img.onerror = function()
  4592. {
  4593. callback(self.svgBrokenImage.src);
  4594. };
  4595. img.src = url;
  4596. }
  4597. };
  4598. /**
  4599. * Handling drag and drop and import.
  4600. */
  4601. /**
  4602. * Imports the given XML into the existing diagram.
  4603. */
  4604. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  4605. {
  4606. dx = (dx != null) ? dx : 0;
  4607. dy = (dy != null) ? dy : 0;
  4608. var cells = []
  4609. try
  4610. {
  4611. var graph = this.editor.graph;
  4612. if (xml != null && xml.length > 0)
  4613. {
  4614. var doc = mxUtils.parseXml(xml);
  4615. // Checks for mxfile with multiple pages
  4616. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  4617. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  4618. {
  4619. var diagrams = node.getElementsByTagName('diagram');
  4620. if (diagrams.length == 1)
  4621. {
  4622. node = mxUtils.parseXml(graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  4623. }
  4624. else if (diagrams.length > 1)
  4625. {
  4626. // Adds pages
  4627. graph.model.beginUpdate();
  4628. try
  4629. {
  4630. for (var i = 0; i < diagrams.length; i++)
  4631. {
  4632. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  4633. var index = this.pages.length;
  4634. // Checks for invalid page names
  4635. if (page.getName() == null)
  4636. {
  4637. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  4638. }
  4639. graph.model.execute(new ChangePage(this, page, page, index));
  4640. }
  4641. }
  4642. finally
  4643. {
  4644. graph.model.endUpdate();
  4645. }
  4646. }
  4647. }
  4648. if (node != null && node.nodeName === 'mxGraphModel')
  4649. {
  4650. cells = graph.importGraphModel(node, dx, dy, crop);
  4651. }
  4652. }
  4653. }
  4654. catch (e)
  4655. {
  4656. if (!noErrorHandling)
  4657. {
  4658. this.handleError(e, mxResources.get('invalidOrMissingFile'));
  4659. }
  4660. throw e;
  4661. }
  4662. return cells;
  4663. };
  4664. /**
  4665. * Imports the given Visio file
  4666. */
  4667. EditorUi.prototype.importVisio = function(file, done, onerror, filename)
  4668. {
  4669. filename = (filename != null) ? filename : file.name;
  4670. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  4671. {
  4672. this.handleError(e);
  4673. });
  4674. var delayed = mxUtils.bind(this, function()
  4675. {
  4676. this.loadingExtensions = false;
  4677. if (this.doImportVisio)
  4678. {
  4679. if (/(\.vsd)($|\?)/i.test(filename) && VSD_CONVERT_URL != null)
  4680. {
  4681. var formData = new FormData();
  4682. formData.append("file1", file);
  4683. var xhr = new XMLHttpRequest();
  4684. xhr.open('POST', VSD_CONVERT_URL);
  4685. xhr.responseType = "blob";
  4686. xhr.onreadystatechange = mxUtils.bind(this, function()
  4687. {
  4688. if (xhr.readyState == 4)
  4689. {
  4690. if (xhr.status >= 200 && xhr.status <= 299)
  4691. {
  4692. try
  4693. {
  4694. this.doImportVisio(xhr.response, done, onerror);
  4695. }
  4696. catch (e)
  4697. {
  4698. onerror(e);
  4699. }
  4700. }
  4701. else
  4702. {
  4703. onerror({});
  4704. }
  4705. }
  4706. });
  4707. xhr.send(formData);
  4708. } else {
  4709. try
  4710. {
  4711. this.doImportVisio(file, done, onerror);
  4712. }
  4713. catch (e)
  4714. {
  4715. onerror(e);
  4716. }
  4717. }
  4718. }
  4719. });
  4720. if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline())
  4721. {
  4722. this.loadingExtensions = true;
  4723. mxscript('js/extensions.min.js', delayed);
  4724. }
  4725. else
  4726. {
  4727. delayed();
  4728. }
  4729. };
  4730. /**
  4731. * Export the diagram to VSDX
  4732. */
  4733. EditorUi.prototype.exportVisio = function()
  4734. {
  4735. var delayed = mxUtils.bind(this, function()
  4736. {
  4737. this.loadingExtensions = false;
  4738. if (typeof VsdxExport !== 'undefined')
  4739. {
  4740. try
  4741. {
  4742. new VsdxExport(this).exportCurrentDiagrams();
  4743. }
  4744. catch (e)
  4745. {
  4746. this.handleError(e);
  4747. }
  4748. }
  4749. });
  4750. if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline())
  4751. {
  4752. this.loadingExtensions = true;
  4753. mxscript('js/extensions.min.js', delayed);
  4754. }
  4755. else
  4756. {
  4757. delayed();
  4758. }
  4759. };
  4760. /**
  4761. * Imports the given Lucidchart data.
  4762. */
  4763. EditorUi.prototype.importLucidChart = function(data, dx, dy, crop, done)
  4764. {
  4765. var delayed = mxUtils.bind(this, function()
  4766. {
  4767. this.loadingExtensions = false;
  4768. // Checks for signature method
  4769. if (this.pasteLucidChart)
  4770. {
  4771. try
  4772. {
  4773. this.insertLucidChart(data, dx, dy, crop, done);
  4774. }
  4775. catch (e)
  4776. {
  4777. this.handleError(e);
  4778. }
  4779. finally
  4780. {
  4781. if (done != null)
  4782. {
  4783. done();
  4784. }
  4785. }
  4786. }
  4787. });
  4788. if (!this.pasteLucidChart && !this.loadingExtensions && !this.isOffline())
  4789. {
  4790. this.loadingExtensions = true;
  4791. if (urlParams['dev'] == '1')
  4792. {
  4793. mxscript('js/diagramly/Extensions.js', delayed);
  4794. }
  4795. else
  4796. {
  4797. mxscript('js/extensions.min.js', delayed);
  4798. }
  4799. }
  4800. else
  4801. {
  4802. // Must be async for cell selection
  4803. window.setTimeout(delayed, 0);
  4804. }
  4805. };
  4806. /**
  4807. * Automatic loading for lucidchart import.
  4808. */
  4809. EditorUi.prototype.insertLucidChart = function(data, dx, dy, crop, done)
  4810. {
  4811. var state = JSON.parse(data);
  4812. // Extracts and sorts all pages
  4813. var pages = [];
  4814. if (state.state != null)
  4815. {
  4816. state = JSON.parse(state.state);
  4817. for (var id in state.Pages)
  4818. {
  4819. pages.push(state.Pages[id]);
  4820. }
  4821. pages.sort(function(a, b)
  4822. {
  4823. if (a.Properties.Order < b.Properties.Order)
  4824. {
  4825. return -1;
  4826. }
  4827. else if (a.Properties.Order > b.Properties.Order)
  4828. {
  4829. return 1;
  4830. }
  4831. else
  4832. {
  4833. return 0;
  4834. }
  4835. });
  4836. }
  4837. else
  4838. {
  4839. pages.push(state);
  4840. }
  4841. if (pages.length > 0)
  4842. {
  4843. this.editor.graph.getModel().beginUpdate();
  4844. try
  4845. {
  4846. this.pasteLucidChart(pages[0], dx, dy, crop);
  4847. // If pages are enabled add more pages
  4848. if (this.pages != null)
  4849. {
  4850. var current = this.currentPage;
  4851. for (var i = 1; i < pages.length; i++)
  4852. {
  4853. this.insertPage();
  4854. this.pasteLucidChart(pages[i]);
  4855. }
  4856. this.selectPage(current);
  4857. }
  4858. }
  4859. finally
  4860. {
  4861. this.editor.graph.getModel().endUpdate();
  4862. }
  4863. }
  4864. };
  4865. /**
  4866. * Imports the given XML into the existing diagram.
  4867. * TODO: Make this function asynchronous
  4868. */
  4869. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages)
  4870. {
  4871. crop = (crop != null) ? crop : true;
  4872. resizeImages = (resizeImages != null) ? resizeImages : true;
  4873. // Handles special case for Gliffy data which requires async server-side for parsing
  4874. if (text != null)
  4875. {
  4876. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  4877. {
  4878. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  4879. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  4880. {
  4881. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  4882. {
  4883. this.editor.graph.setSelectionCells(this.insertTextAt(xhr.responseText, dx, dy, true));
  4884. }
  4885. }));
  4886. // Returns empty cells array as it is aysynchronous
  4887. return [];
  4888. }
  4889. // Handles special case of data URI which requires async loading for finding size
  4890. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() && (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  4891. {
  4892. var graph = this.editor.graph;
  4893. // Checks for embedded XML in PNG
  4894. if (text.substring(0, 22) == 'data:image/png;base64,')
  4895. {
  4896. var xml = this.extractGraphModelFromPng(text);
  4897. var result = this.importXml(xml, dx, dy, crop, true);
  4898. if (result.length > 0)
  4899. {
  4900. return result;
  4901. }
  4902. }
  4903. // Tries to extract embedded XML from SVG data URI
  4904. if (text.substring(0, 19) == 'data:image/svg+xml;')
  4905. {
  4906. try
  4907. {
  4908. var xml = null;
  4909. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  4910. {
  4911. xml = text.substring(text.indexOf(',') + 1);
  4912. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  4913. }
  4914. else
  4915. {
  4916. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  4917. }
  4918. var result = this.importXml(xml, dx, dy, crop, true);
  4919. if (result.length > 0)
  4920. {
  4921. return result;
  4922. }
  4923. }
  4924. catch (e)
  4925. {
  4926. // Ignore
  4927. }
  4928. }
  4929. this.loadImage(text, mxUtils.bind(this, function(img)
  4930. {
  4931. if (text.substring(0, 5) == 'data:')
  4932. {
  4933. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  4934. {
  4935. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4936. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4937. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  4938. }), resizeImages, this.maxImageSize);
  4939. }
  4940. else
  4941. {
  4942. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  4943. var w = Math.round(img.width * s);
  4944. var h = Math.round(img.height * s);
  4945. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4946. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4947. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  4948. }
  4949. }), mxUtils.bind(this, function()
  4950. {
  4951. var cell = null;
  4952. // Inserts invalid data URIs as text
  4953. graph.getModel().beginUpdate();
  4954. try
  4955. {
  4956. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  4957. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4958. graph.updateCellSize(cell);
  4959. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4960. }
  4961. finally
  4962. {
  4963. graph.getModel().endUpdate();
  4964. }
  4965. graph.setSelectionCell(cell);
  4966. }));
  4967. return [];
  4968. }
  4969. else
  4970. {
  4971. text = this.editor.graph.zapGremlins(mxUtils.trim(text));
  4972. if (this.isCompatibleString(text))
  4973. {
  4974. return this.importXml(text, dx, dy, crop);
  4975. }
  4976. else if (text.length > 0)
  4977. {
  4978. if (text.substring(0, 26) == '{"state":"{\\"Properties\\":')
  4979. {
  4980. this.importLucidChart(text, dx, dy, crop);
  4981. }
  4982. else
  4983. {
  4984. var graph = this.editor.graph;
  4985. var cell = null;
  4986. graph.getModel().beginUpdate();
  4987. try
  4988. {
  4989. // Fires cellsInserted to apply the current style to the inserted text.
  4990. // This requires the value to be empty when the event is fired.
  4991. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  4992. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4993. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4994. // Apply value and updates the cell size to fit the text block
  4995. cell.value = text;
  4996. graph.updateCellSize(cell);
  4997. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  4998. 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;
  4999. if (regexp.test(cell.value))
  5000. {
  5001. graph.setLinkForCell(cell, cell.value);
  5002. }
  5003. // Adds spacing
  5004. cell.geometry.width += graph.gridSize;
  5005. cell.geometry.height += graph.gridSize;
  5006. }
  5007. finally
  5008. {
  5009. graph.getModel().endUpdate();
  5010. }
  5011. return [cell];
  5012. }
  5013. }
  5014. }
  5015. }
  5016. return [];
  5017. };
  5018. /**
  5019. * Formats the given file size.
  5020. */
  5021. EditorUi.prototype.formatFileSize = function(size)
  5022. {
  5023. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  5024. var i = -1;
  5025. do
  5026. {
  5027. size = size / 1024;
  5028. i++;
  5029. } while (size > 1024);
  5030. return Math.max(size, 0.1).toFixed(1) + units[i];
  5031. };
  5032. /**
  5033. * Imports the given XML into the existing diagram.
  5034. */
  5035. EditorUi.prototype.convertDataUri = function(uri)
  5036. {
  5037. // Handles special case of data URI which needs to be rewritten
  5038. // to be used in a cell style to remove the semicolon
  5039. if (uri.substring(0, 5) == 'data:')
  5040. {
  5041. var semi = uri.indexOf(';');
  5042. if (semi > 0)
  5043. {
  5044. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  5045. }
  5046. }
  5047. return uri;
  5048. };
  5049. /**
  5050. * Returns true for Gliffy or GraphML data or .vsdx filenames.
  5051. */
  5052. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  5053. {
  5054. return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
  5055. };
  5056. /**
  5057. * Imports the given XML into the existing diagram.
  5058. */
  5059. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  5060. {
  5061. crop = (crop != null) ? crop : true;
  5062. var async = false;
  5063. var cells = null;
  5064. var handleResult = mxUtils.bind(this, function(xml)
  5065. {
  5066. var importedCells = null;
  5067. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  5068. {
  5069. this.loadLibrary(new LocalLibrary(this, xml, filename));
  5070. }
  5071. else
  5072. {
  5073. importedCells = this.importXml(xml, dx, dy, crop);
  5074. }
  5075. if (done != null)
  5076. {
  5077. done(importedCells);
  5078. }
  5079. });
  5080. if (mimeType.substring(0, 5) == 'image')
  5081. {
  5082. var containsModel = false;
  5083. if (mimeType.substring(0, 9) == 'image/png')
  5084. {
  5085. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  5086. if (xml != null && xml.length > 0)
  5087. {
  5088. cells = this.importXml(xml, dx, dy, crop);
  5089. containsModel = true;
  5090. }
  5091. }
  5092. if (!containsModel)
  5093. {
  5094. var graph = this.editor.graph;
  5095. // Strips encoding bit (eg. ;base64,) for cell style
  5096. var semi = data.indexOf(';');
  5097. if (semi > 0)
  5098. {
  5099. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  5100. }
  5101. if (crop && graph.isGridEnabled())
  5102. {
  5103. dx = graph.snap(dx);
  5104. dy = graph.snap(dy);
  5105. }
  5106. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  5107. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5108. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  5109. }
  5110. }
  5111. else if (/(\.*<graphml )/.test(data) && typeof window.mxGraphMlCodec !== 'undefined')
  5112. {
  5113. new mxGraphMlCodec().decode(data, mxUtils.bind(this, function(xml)
  5114. {
  5115. var importedCells = this.importXml(xml, dx, dy, crop);
  5116. if (done != null)
  5117. {
  5118. done(importedCells);
  5119. }
  5120. }));
  5121. }
  5122. // else if (file != null && filename != null && ((/(\.vsdx)($|\?)/i.test(filename)) || /(\.vssx)($|\?)/i.test(filename) || /(\.vsd)($|\?)/i.test(filename)))
  5123. // {
  5124. //
  5125. // }
  5126. else if (file != null && filename != null && ((/(\.vsdx)($|\?)/i.test(filename)) || /(\.vssx)($|\?)/i.test(filename) || /(\.vsd)($|\?)/i.test(filename)))
  5127. {
  5128. // LATER: done and async are a hack before making this asynchronous
  5129. async = true;
  5130. this.importVisio(file, handleResult);
  5131. }
  5132. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  5133. {
  5134. // LATER: done and async are a hack before making this asynchronous
  5135. async = true;
  5136. // Returns empty cells array as it is aysynchronous
  5137. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  5138. {
  5139. if (xhr.readyState == 4)
  5140. {
  5141. if (xhr.status >= 200 && xhr.status <= 299)
  5142. {
  5143. handleResult(xhr.responseText);
  5144. }
  5145. else if (done != null)
  5146. {
  5147. done(null);
  5148. }
  5149. }
  5150. }), filename);
  5151. }
  5152. else if (!/(\.vsd)($|\?)/i.test(filename))
  5153. {
  5154. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  5155. }
  5156. if (!async && done != null)
  5157. {
  5158. done(cells);
  5159. }
  5160. return cells;
  5161. };
  5162. /**
  5163. * Base64 encodes the given string. This method seems to be more
  5164. * robust for encoding PNG from binary AJAX responses.
  5165. */
  5166. EditorUi.prototype.base64Encode = function(str)
  5167. {
  5168. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5169. var out = "", i = 0, len = str.length, c1, c2, c3;
  5170. while (i < len)
  5171. {
  5172. c1 = str.charCodeAt(i++) & 0xff;
  5173. if (i == len)
  5174. {
  5175. out += CHARS.charAt(c1 >> 2);
  5176. out += CHARS.charAt((c1 & 0x3) << 4);
  5177. out += "==";
  5178. break;
  5179. }
  5180. c2 = str.charCodeAt(i++);
  5181. if (i == len)
  5182. {
  5183. out += CHARS.charAt(c1 >> 2);
  5184. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  5185. out += CHARS.charAt((c2 & 0xF) << 2);
  5186. out += "=";
  5187. break;
  5188. }
  5189. c3 = str.charCodeAt(i++);
  5190. out += CHARS.charAt(c1 >> 2);
  5191. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  5192. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  5193. out += CHARS.charAt(c3 & 0x3F);
  5194. }
  5195. return out;
  5196. };
  5197. /**
  5198. *
  5199. */
  5200. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  5201. {
  5202. x = (x != null) ? x : 0;
  5203. y = (y != null) ? y : 0;
  5204. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  5205. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  5206. var crop = x != null && y != null;
  5207. var resizeImages = true;
  5208. // Checks if large images are imported
  5209. var largeImages = false;
  5210. if (!mxClient.IS_CHROMEAPP && files != null)
  5211. {
  5212. var thresh = resampleThreshold || this.resampleThreshold;
  5213. for (var i = 0; i < files.length; i++)
  5214. {
  5215. if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
  5216. {
  5217. largeImages = true;
  5218. break;
  5219. }
  5220. }
  5221. }
  5222. var doImportFiles = mxUtils.bind(this, function()
  5223. {
  5224. var graph = this.editor.graph;
  5225. var gs = graph.gridSize;
  5226. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  5227. {
  5228. if (data != null && data.substring(0, 10) == '<mxlibrary')
  5229. {
  5230. this.spinner.stop();
  5231. this.loadLibrary(new LocalLibrary(this, data, filename));
  5232. return null;
  5233. }
  5234. else
  5235. {
  5236. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  5237. }
  5238. });
  5239. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  5240. {
  5241. graph.setSelectionCells(cells);
  5242. });
  5243. if (this.spinner.spin(document.body, mxResources.get('loading')))
  5244. {
  5245. var count = files.length;
  5246. var remain = count;
  5247. var queue = [];
  5248. // Barrier waits for all files to be loaded asynchronously
  5249. var barrier = mxUtils.bind(this, function(index, fnc)
  5250. {
  5251. queue[index] = fnc;
  5252. if (--remain == 0)
  5253. {
  5254. this.spinner.stop();
  5255. if (barrierFn != null)
  5256. {
  5257. barrierFn(queue);
  5258. }
  5259. else
  5260. {
  5261. var cells = [];
  5262. graph.getModel().beginUpdate();
  5263. try
  5264. {
  5265. for (var j = 0; j < queue.length; j++)
  5266. {
  5267. var tmp = queue[j]();
  5268. if (tmp != null)
  5269. {
  5270. cells = cells.concat(tmp);
  5271. }
  5272. }
  5273. }
  5274. finally
  5275. {
  5276. graph.getModel().endUpdate();
  5277. }
  5278. }
  5279. resultFn(cells);
  5280. }
  5281. });
  5282. for (var i = 0; i < count; i++)
  5283. {
  5284. (mxUtils.bind(this, function(index)
  5285. {
  5286. var file = files[index];
  5287. var reader = new FileReader();
  5288. reader.onload = mxUtils.bind(this, function(e)
  5289. {
  5290. if (filterFn == null || filterFn(file))
  5291. {
  5292. if (file.type.substring(0, 6) == 'image/')
  5293. {
  5294. if (file.type.substring(0, 9) == 'image/svg')
  5295. {
  5296. // Checks if SVG contains content attribute
  5297. var data = e.target.result;
  5298. var comma = data.indexOf(',');
  5299. var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
  5300. var root = mxUtils.parseXml(svgText);
  5301. var svgs = root.getElementsByTagName('svg');
  5302. if (svgs.length > 0)
  5303. {
  5304. var svgRoot = svgs[0];
  5305. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  5306. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  5307. {
  5308. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  5309. }
  5310. if (cont != null && cont.charAt(0) == '%')
  5311. {
  5312. cont = decodeURIComponent(cont);
  5313. }
  5314. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  5315. cont.substring(0, 14) === '<mxGraphModel '))
  5316. {
  5317. barrier(index, mxUtils.bind(this, function()
  5318. {
  5319. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  5320. }));
  5321. }
  5322. else
  5323. {
  5324. // SVG needs special handling to add viewbox if missing and
  5325. // find initial size from SVG attributes (only for IE11)
  5326. barrier(index, mxUtils.bind(this, function()
  5327. {
  5328. try
  5329. {
  5330. var prefix = data.substring(0, comma + 1);
  5331. // Parses SVG and find width and height
  5332. if (root != null)
  5333. {
  5334. var svgs = root.getElementsByTagName('svg');
  5335. if (svgs.length > 0)
  5336. {
  5337. var svgRoot = svgs[0];
  5338. var w = parseFloat(svgRoot.getAttribute('width'));
  5339. var h = parseFloat(svgRoot.getAttribute('height'));
  5340. // Check if viewBox attribute already exists
  5341. var vb = svgRoot.getAttribute('viewBox');
  5342. if (vb == null || vb.length == 0)
  5343. {
  5344. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  5345. }
  5346. // Uses width and height from viewbox for
  5347. // missing width and height attributes
  5348. else if (isNaN(w) || isNaN(h))
  5349. {
  5350. var tokens = vb.split(' ');
  5351. if (tokens.length > 3)
  5352. {
  5353. w = parseFloat(tokens[2]);
  5354. h = parseFloat(tokens[3]);
  5355. }
  5356. }
  5357. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5358. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  5359. var cells = fn(data, file.type, x + index * gs, y + index * gs,
  5360. Math.max(1, Math.round(w * s)), Math.max(1, Math.round(h * s)),
  5361. file.name, resizeImages);
  5362. // Hack to fix width and height asynchronously
  5363. if (isNaN(w) || isNaN(h))
  5364. {
  5365. var img = new Image();
  5366. img.onload = mxUtils.bind(this, function()
  5367. {
  5368. w = Math.max(1, img.width);
  5369. h = Math.max(1, img.height);
  5370. cells[0].geometry.width = w;
  5371. cells[0].geometry.height = h;
  5372. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  5373. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5374. var semi = data.indexOf(';');
  5375. if (semi > 0)
  5376. {
  5377. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  5378. }
  5379. graph.setCellStyles('image', data, [cells[0]]);
  5380. });
  5381. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5382. }
  5383. return cells;
  5384. }
  5385. }
  5386. }
  5387. catch (e)
  5388. {
  5389. // ignores any SVG parsing errors
  5390. }
  5391. return null;
  5392. }));
  5393. }
  5394. }
  5395. }
  5396. else
  5397. {
  5398. // Checks if PNG+XML is available to bypass code below
  5399. var containsModel = false;
  5400. if (file.type == 'image/png')
  5401. {
  5402. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  5403. if (xml != null && xml.length > 0)
  5404. {
  5405. var img = new Image();
  5406. img.src = e.target.result;
  5407. barrier(index, mxUtils.bind(this, function()
  5408. {
  5409. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  5410. img.width, img.height, file.name);
  5411. }));
  5412. containsModel = true;
  5413. }
  5414. }
  5415. // Additional asynchronous step for finding image size
  5416. if (!containsModel)
  5417. {
  5418. // Cannot load local files in Chrome App
  5419. if (mxClient.IS_CHROMEAPP)
  5420. {
  5421. this.spinner.stop();
  5422. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  5423. mxResources.get('cancel'), mxUtils.bind(this, function()
  5424. {
  5425. // Hides the dialog
  5426. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  5427. {
  5428. // Redirects to import function
  5429. this.actions.get('import').funct();
  5430. })
  5431. );
  5432. }
  5433. else
  5434. {
  5435. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  5436. {
  5437. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  5438. {
  5439. barrier(index, mxUtils.bind(this, function()
  5440. {
  5441. // Refuses to insert images above a certain size as they kill the app
  5442. if (data2 != null && data2.length < maxBytes)
  5443. {
  5444. var s = (!resizeImages || !this.isResampleImage(e.target.result, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  5445. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  5446. }
  5447. else
  5448. {
  5449. this.handleError({message: mxResources.get('imageTooBig')});
  5450. return null;
  5451. }
  5452. }));
  5453. }), resizeImages, maxSize, resampleThreshold);
  5454. }), mxUtils.bind(this, function()
  5455. {
  5456. this.handleError({message: mxResources.get('invalidOrMissingFile')});
  5457. }));
  5458. }
  5459. }
  5460. }
  5461. }
  5462. else
  5463. {
  5464. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  5465. {
  5466. barrier(index, function()
  5467. {
  5468. return cells;
  5469. });
  5470. });
  5471. }
  5472. }
  5473. });
  5474. // Handles special cases
  5475. if (/(\.vsdx)($|\?)/i.test(file.name) || /(\.vssx)($|\?)/i.test(file.name) || /(\.vsd)($|\?)/i.test(file.name))
  5476. {
  5477. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  5478. {
  5479. barrier(index, function()
  5480. {
  5481. return cells;
  5482. });
  5483. }, file);
  5484. }
  5485. else if (file.type.substring(0, 5) == 'image')
  5486. {
  5487. reader.readAsDataURL(file);
  5488. }
  5489. else
  5490. {
  5491. reader.readAsText(file);
  5492. }
  5493. }))(i);
  5494. }
  5495. }
  5496. });
  5497. if (largeImages)
  5498. {
  5499. this.confirmImageResize(function(doResize)
  5500. {
  5501. resizeImages = doResize;
  5502. doImportFiles();
  5503. }, resizeDialog);
  5504. }
  5505. else
  5506. {
  5507. doImportFiles();
  5508. }
  5509. };
  5510. /**
  5511. * Parses the file using XHR2 via the server. File can be a blob or file object.
  5512. * Filename is an optional parameter for blobs (that do not have a filename).
  5513. */
  5514. EditorUi.prototype.confirmImageResize = function(fn, force)
  5515. {
  5516. force = (force != null) ? force : false;
  5517. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  5518. var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
  5519. var wrapper = function(remember, resize)
  5520. {
  5521. if (remember || force)
  5522. {
  5523. mxSettings.setResizeImages((remember) ? resize : null);
  5524. mxSettings.save();
  5525. }
  5526. resume();
  5527. fn(resize);
  5528. };
  5529. if (resizeImages != null && !force)
  5530. {
  5531. wrapper(false, resizeImages);
  5532. }
  5533. else
  5534. {
  5535. this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
  5536. function(remember)
  5537. {
  5538. wrapper(remember, true);
  5539. },
  5540. function(remember)
  5541. {
  5542. wrapper(remember, false);
  5543. }, mxResources.get('resize'), mxResources.get('actualSize'),
  5544. '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
  5545. '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
  5546. isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
  5547. (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
  5548. }
  5549. };
  5550. /**
  5551. * Parses the file using XHR2 via the server. File can be a blob or file object.
  5552. * Filename is an optional parameter for blobs (that do not have a filename).
  5553. */
  5554. EditorUi.prototype.parseFile = function(file, fn, filename)
  5555. {
  5556. filename = (filename != null) ? filename : file.name;
  5557. var formData = new FormData();
  5558. formData.append('format', 'xml');
  5559. formData.append('upfile', file, filename);
  5560. var xhr = new XMLHttpRequest();
  5561. xhr.open('POST', OPEN_URL);
  5562. xhr.onreadystatechange = function()
  5563. {
  5564. fn(xhr);
  5565. };
  5566. xhr.send(formData);
  5567. };
  5568. /**
  5569. *
  5570. */
  5571. EditorUi.prototype.isResampleImage = function(data, thresh)
  5572. {
  5573. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  5574. return data.length > thresh;
  5575. };
  5576. /**
  5577. * Resizes the given image if <maxImageBytes> is not null.
  5578. */
  5579. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  5580. {
  5581. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  5582. var w = Math.max(1, img.width);
  5583. var h = Math.max(1, img.height);
  5584. if (enabled && this.isResampleImage(data, thresh))
  5585. {
  5586. try
  5587. {
  5588. var factor = Math.max(w / maxSize, h / maxSize);
  5589. if (factor > 1)
  5590. {
  5591. var w2 = Math.round(w / factor);
  5592. var h2 = Math.round(h / factor);
  5593. var canvas = document.createElement('canvas');
  5594. canvas.width = w2;
  5595. canvas.height = h2;
  5596. var ctx = canvas.getContext('2d');
  5597. ctx.drawImage(img, 0, 0, w2, h2);
  5598. var tmp = canvas.toDataURL();
  5599. // Uses new image if smaller
  5600. if (tmp.length < data.length)
  5601. {
  5602. // Checks if the image is empty by comparing
  5603. // with an empty image of the same size
  5604. var canvas2 = document.createElement('canvas');
  5605. canvas2.width = w2;
  5606. canvas2.height = h2;
  5607. var tmp2 = canvas2.toDataURL();
  5608. if (tmp !== tmp2)
  5609. {
  5610. data = tmp;
  5611. w = w2;
  5612. h = h2;
  5613. }
  5614. }
  5615. }
  5616. }
  5617. catch (e)
  5618. {
  5619. // ignores image scaling errors
  5620. }
  5621. }
  5622. fn(data, w, h);
  5623. };
  5624. EditorUi.prototype.crcTable = [];
  5625. for (var n = 0; n < 256; n++)
  5626. {
  5627. var c = n;
  5628. for (var k = 0; k < 8; k++)
  5629. {
  5630. if ((c & 1) == 1)
  5631. {
  5632. c = 0xedb88320 ^ (c >>> 1);
  5633. }
  5634. else
  5635. {
  5636. c >>>= 1;
  5637. }
  5638. EditorUi.prototype.crcTable[n] = c;
  5639. }
  5640. }
  5641. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  5642. {
  5643. var c = crc;
  5644. for (var n = 0; n < len; n++)
  5645. {
  5646. c = EditorUi.prototype.crcTable[(c ^ data[off + n]) & 0xff] ^ (c >>> 8);
  5647. }
  5648. return c;
  5649. };
  5650. /**
  5651. * Adds the given text to the compressed or non-compressed text chunk.
  5652. */
  5653. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  5654. {
  5655. var base64 = data.substring(data.indexOf(',') + 1);
  5656. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  5657. var pos = 0;
  5658. function fread(d, count)
  5659. {
  5660. var start = pos;
  5661. pos += count;
  5662. return d.substring(start, pos);
  5663. };
  5664. // Reads unsigned long 32 bit big endian
  5665. function _freadint(d)
  5666. {
  5667. var bytes = fread(d, 4);
  5668. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  5669. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  5670. };
  5671. function writeInt(num)
  5672. {
  5673. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  5674. (num >> 8) & 0x000000ff, num & 0x000000ff);
  5675. };
  5676. // Checks signature
  5677. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  5678. {
  5679. if (error != null)
  5680. {
  5681. error();
  5682. }
  5683. return;
  5684. }
  5685. // Reads header chunk
  5686. fread(f,4);
  5687. if (fread(f,4) != 'IHDR')
  5688. {
  5689. if (error != null)
  5690. {
  5691. error();
  5692. }
  5693. return;
  5694. }
  5695. fread(f, 17);
  5696. var result = f.substring(0, pos);
  5697. do
  5698. {
  5699. var n = _freadint(f);
  5700. var chunk = fread(f,4);
  5701. if (chunk == 'IDAT')
  5702. {
  5703. result = f.substring(0, pos - 8);
  5704. var chunkData = key + String.fromCharCode(0) +
  5705. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  5706. value;
  5707. // FIXME: Wrong crc
  5708. var crc = 0xffffffff;
  5709. crc = this.updateCRC(crc, type, 0, 4);
  5710. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  5711. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  5712. result += f.substring(pos - 8, f.length);
  5713. break;
  5714. }
  5715. result += f.substring(pos - 8, pos - 4 + n);
  5716. fread(f,n);
  5717. fread(f,4);
  5718. }
  5719. while (n);
  5720. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  5721. }
  5722. /**
  5723. * Extracts the XML from the compressed or non-compressed text chunk.
  5724. */
  5725. EditorUi.prototype.extractGraphModelFromPng = function(data)
  5726. {
  5727. var result = null;
  5728. try
  5729. {
  5730. var base64 = data.substring(data.indexOf(',') + 1);
  5731. // Workaround for invalid character error in Safari
  5732. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  5733. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  5734. {
  5735. var value = binary.substring(pos + 8, pos + 8 + length);
  5736. if (type == 'zTXt')
  5737. {
  5738. var idx = value.indexOf(String.fromCharCode(0));
  5739. if (value.substring(0, idx) == 'mxGraphModel')
  5740. {
  5741. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  5742. var xmlData = this.editor.graph.bytesToString(pako.inflateRaw(
  5743. value.substring(idx + 2))).replace(/\+/g,' ');
  5744. if (xmlData != null && xmlData.length > 0)
  5745. {
  5746. result = xmlData;
  5747. }
  5748. }
  5749. }
  5750. // Uncompressed section is normally not used
  5751. else if (type == 'tEXt')
  5752. {
  5753. var vals = value.split(String.fromCharCode(0));
  5754. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  5755. {
  5756. result = vals[1];
  5757. }
  5758. }
  5759. if (result != null || type == 'IDAT')
  5760. {
  5761. // Stops processing the file as our text chunks
  5762. // are always placed before the data section
  5763. return true;
  5764. }
  5765. }));
  5766. }
  5767. catch (e)
  5768. {
  5769. // ignores decoding errors
  5770. }
  5771. if (result != null && result.charAt(0) == '%')
  5772. {
  5773. result = decodeURIComponent(result);
  5774. }
  5775. // Workaround for double encoded content
  5776. if (result != null && result.charAt(0) == '%')
  5777. {
  5778. result = decodeURIComponent(result);
  5779. }
  5780. return result;
  5781. };
  5782. /**
  5783. * Loads the image from the given URI.
  5784. *
  5785. * @param {number} dx X-coordinate of the translation.
  5786. * @param {number} dy Y-coordinate of the translation.
  5787. */
  5788. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  5789. {
  5790. var img = new Image();
  5791. img.onload = function()
  5792. {
  5793. onload(img);
  5794. }
  5795. if (onerror != null)
  5796. {
  5797. img.onerror = onerror;
  5798. }
  5799. img.src = uri;
  5800. };
  5801. // Initializes the user interface
  5802. var editorUiInit = EditorUi.prototype.init;
  5803. EditorUi.prototype.init = function()
  5804. {
  5805. // Must be set before UI is created in superclass
  5806. if (typeof window.mxSettings !== 'undefined')
  5807. {
  5808. this.formatWidth = mxSettings.getFormatWidth();
  5809. }
  5810. var ui = this;
  5811. var graph = this.editor.graph;
  5812. function pageLinkClicked(href)
  5813. {
  5814. var comma = href.indexOf(',');
  5815. if (comma > 0)
  5816. {
  5817. var page = ui.getPageById(href.substring(comma + 1));
  5818. if (page)
  5819. {
  5820. ui.selectPage(page)
  5821. }
  5822. }
  5823. };
  5824. graph.addListener('pageLinkClicked', function(sender, evt)
  5825. {
  5826. pageLinkClicked(evt.getProperty('href'));
  5827. });
  5828. // Sets help link for placeholders
  5829. if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
  5830. {
  5831. EditDataDialog.placeholderHelpLink = 'https://desk.draw.io/support/solutions/articles/16000051979';
  5832. }
  5833. // Passes current page to editor window
  5834. var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
  5835. this.editor.getEditBlankUrl = function(params)
  5836. {
  5837. params = (params != null) ? params : '';
  5838. if (ui.pages != null && ui.currentPage != null)
  5839. {
  5840. for (var i = 0; i < ui.pages.length; i++)
  5841. {
  5842. if (ui.pages[i] == ui.currentPage)
  5843. {
  5844. if (i > 0)
  5845. {
  5846. params += ((params.length > 0) ? '&' : '?') + 'page=' + i;
  5847. }
  5848. break;
  5849. }
  5850. }
  5851. }
  5852. if (urlParams['dev'] == '1')
  5853. {
  5854. params += ((params.length > 0) ? '&' : '?') + 'dev=1&drawdev=1';
  5855. }
  5856. return editorGetEditBlankUrl.apply(this, arguments);
  5857. };
  5858. // For chromeless mode and lightbox mode in viewer
  5859. // Must be overridden before supercall to be applied
  5860. // in case of chromeless initialization
  5861. var graphAddClickHandler = graph.addClickHandler;
  5862. graph.addClickHandler = function(highlight, beforeClick, onClick)
  5863. {
  5864. var tmp = beforeClick;
  5865. beforeClick = function(evt, href)
  5866. {
  5867. if (href == null)
  5868. {
  5869. var source = mxEvent.getSource(evt);
  5870. if (source.nodeName.toLowerCase() == 'a')
  5871. {
  5872. href = source.getAttribute('href');
  5873. }
  5874. }
  5875. if (href != null && graph.isPageLink(href) && (mxEvent.isTouchEvent(evt) ||
  5876. !mxEvent.isPopupTrigger(evt)))
  5877. {
  5878. pageLinkClicked(href);
  5879. mxEvent.consume(evt);
  5880. }
  5881. if (tmp != null)
  5882. {
  5883. tmp(evt, href);
  5884. }
  5885. };
  5886. // For some reason, local argument override is not enough in this case...
  5887. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  5888. };
  5889. editorUiInit.apply(this, arguments);
  5890. if (mxClient.IS_SVG)
  5891. {
  5892. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  5893. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  5894. }
  5895. // Overrides print dialog size
  5896. ui.actions.get('print').funct = function()
  5897. {
  5898. ui.showDialog(new PrintDialog(ui).container, 360,
  5899. (ui.pages != null && ui.pages.length > 1) ?
  5900. 420 : 360, true, true);
  5901. };
  5902. // Specifies the default filename
  5903. this.defaultFilename = mxResources.get('untitledDiagram');
  5904. // Adds placeholder for %page% and %pagenumber%
  5905. var graphGetGlobalVariable = graph.getGlobalVariable;
  5906. graph.getGlobalVariable = function(name)
  5907. {
  5908. if (name == 'page' && ui.currentPage != null)
  5909. {
  5910. return ui.currentPage.getName();
  5911. }
  5912. else if (name == 'pagenumber')
  5913. {
  5914. if (ui.currentPage != null && ui.pages != null)
  5915. {
  5916. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  5917. }
  5918. else
  5919. {
  5920. return 1;
  5921. }
  5922. }
  5923. return graphGetGlobalVariable.apply(this, arguments);
  5924. };
  5925. var graphCreateLinkForHint = graph.createLinkForHint;
  5926. graph.createLinkForHint = function(href, label)
  5927. {
  5928. var pageLink = graph.isPageLink(href);
  5929. if (pageLink)
  5930. {
  5931. var comma = href.indexOf(',');
  5932. if (comma > 0)
  5933. {
  5934. var page = ui.getPageById(href.substring(comma + 1));
  5935. if (page != null)
  5936. {
  5937. label = page.getName();
  5938. }
  5939. else
  5940. {
  5941. label = mxResources.get('pageNotFound');
  5942. }
  5943. }
  5944. }
  5945. var a = graphCreateLinkForHint.call(this, href, label);
  5946. if (pageLink)
  5947. {
  5948. mxEvent.addListener(a, 'click', function(evt)
  5949. {
  5950. pageLinkClicked(href);
  5951. mxEvent.consume(evt);
  5952. });
  5953. }
  5954. return a;
  5955. };
  5956. var graphLabelLinkClicked = graph.labelLinkClicked;
  5957. graph.labelLinkClicked = function(state, elt, evt)
  5958. {
  5959. var href = elt.getAttribute('href');
  5960. if (href != null && graph.isPageLink(href) && (mxEvent.isTouchEvent(evt) ||
  5961. !mxEvent.isPopupTrigger(evt)))
  5962. {
  5963. // Active links are moved to the hint
  5964. if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
  5965. {
  5966. pageLinkClicked(href);
  5967. // Resets rubberband after click on locked cell
  5968. graph.getRubberband().reset();
  5969. }
  5970. mxEvent.consume(evt);
  5971. }
  5972. else
  5973. {
  5974. graphLabelLinkClicked.apply(this, arguments);
  5975. }
  5976. };
  5977. // Overrides editor filename
  5978. this.editor.getOrCreateFilename = function()
  5979. {
  5980. var filename = ui.defaultFilename;
  5981. var file = ui.getCurrentFile();
  5982. if (file != null)
  5983. {
  5984. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  5985. }
  5986. return filename;
  5987. };
  5988. // Disables print action for standalone apps on iOS
  5989. // because there is no way to close the new window
  5990. // LATER: Use iframe for print, disable preview
  5991. var printAction = this.actions.get('print');
  5992. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  5993. printAction.visible = printAction.isEnabled();
  5994. // Scales pages/graph to fit available size
  5995. if (!this.editor.chromeless || this.editor.editable)
  5996. {
  5997. // Defines additional hotkeys
  5998. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  5999. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  6000. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  6001. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  6002. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  6003. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  6004. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  6005. // Handles copy paste of images from clipboard
  6006. if (!mxClient.IS_IE)
  6007. {
  6008. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  6009. {
  6010. var graph = this.editor.graph;
  6011. if (!mxEvent.isConsumed(evt))
  6012. {
  6013. try
  6014. {
  6015. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  6016. var containsText = false;
  6017. // Workaround for asynchronous paste event processing in textInput
  6018. // is to ignore this event if it contains text/html/rtf (see below).
  6019. // NOTE: Image is not pasted into textInput so can't listen there.
  6020. for (var i = 0; i < data.types.length; i++)
  6021. {
  6022. if (data.types[i].substring(0, 5) === 'text/')
  6023. {
  6024. containsText = true;
  6025. break;
  6026. }
  6027. }
  6028. if (!containsText)
  6029. {
  6030. var items = data.items;
  6031. for (index in items)
  6032. {
  6033. var item = items[index];
  6034. if (item.kind === 'file')
  6035. {
  6036. if (graph.isEditing())
  6037. {
  6038. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  6039. {
  6040. // Inserts image into current text box
  6041. graph.insertImage(data, w, h);
  6042. }, function()
  6043. {
  6044. // No post processing
  6045. }, function(file)
  6046. {
  6047. // Handles only images
  6048. return file.type.substring(0, 6) == 'image/';
  6049. }, function(queue)
  6050. {
  6051. // Invokes elements of queue in order
  6052. for (var i = 0; i < queue.length; i++)
  6053. {
  6054. queue[i]();
  6055. }
  6056. });
  6057. }
  6058. else
  6059. {
  6060. var pt = this.editor.graph.getInsertPoint();
  6061. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  6062. mxEvent.consume(evt);
  6063. }
  6064. break;
  6065. }
  6066. }
  6067. }
  6068. }
  6069. catch (e)
  6070. {
  6071. // ignore
  6072. }
  6073. }
  6074. }), false);
  6075. }
  6076. // Focused but invisible textarea during control or meta key events
  6077. var textInput = document.createElement('div');
  6078. textInput.style.position = 'absolute';
  6079. textInput.style.whiteSpace = 'nowrap';
  6080. textInput.style.overflow = 'hidden';
  6081. textInput.style.display = 'block';
  6082. textInput.contentEditable = true;
  6083. mxUtils.setOpacity(textInput, 0);
  6084. textInput.style.width = '1px';
  6085. textInput.style.height = '1px';
  6086. textInput.innerHTML = '&nbsp;';
  6087. var restoreFocus = false;
  6088. // Disables built-in cut, copy and paste shortcuts
  6089. this.keyHandler.bindControlKey(88, null);
  6090. this.keyHandler.bindControlKey(67, null);
  6091. this.keyHandler.bindControlKey(86, null);
  6092. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  6093. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  6094. {
  6095. // No dialog visible
  6096. var source = mxEvent.getSource(evt);
  6097. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  6098. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  6099. {
  6100. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  6101. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  6102. {
  6103. // Cannot use parentNode for check in IE
  6104. if (!restoreFocus)
  6105. {
  6106. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  6107. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  6108. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  6109. graph.container.appendChild(textInput);
  6110. restoreFocus = true;
  6111. // Workaround for selected document content in quirks mode
  6112. if (mxClient.IS_QUIRKS)
  6113. {
  6114. window.setTimeout(function()
  6115. {
  6116. textInput.focus();
  6117. document.execCommand('selectAll', false, null);
  6118. }, 0);
  6119. }
  6120. else
  6121. {
  6122. textInput.focus();
  6123. document.execCommand('selectAll', false, null);
  6124. }
  6125. }
  6126. }
  6127. }
  6128. }));
  6129. // Clears input and restores focus and selection
  6130. function clearInput()
  6131. {
  6132. window.setTimeout(function()
  6133. {
  6134. textInput.innerHTML = '&nbsp;';
  6135. textInput.focus();
  6136. document.execCommand('selectAll', false, null);
  6137. }, 0);
  6138. };
  6139. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  6140. {
  6141. // Workaround for asynchronous event read invalid in IE quirks mode
  6142. var keyCode = evt.keyCode;
  6143. // Asynchronous workaround for scroll to origin after paste if the
  6144. // Ctrl-key is not pressed for long enough in FF on Windows
  6145. window.setTimeout(mxUtils.bind(this, function()
  6146. {
  6147. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  6148. keyCode == 91 /* Meta */))
  6149. {
  6150. restoreFocus = false;
  6151. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  6152. {
  6153. graph.container.focus();
  6154. }
  6155. textInput.parentNode.removeChild(textInput);
  6156. }
  6157. }), 0);
  6158. }));
  6159. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  6160. {
  6161. if (graph.isEnabled())
  6162. {
  6163. mxClipboard.copy(graph);
  6164. this.copyCells(textInput);
  6165. clearInput();
  6166. }
  6167. }));
  6168. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  6169. {
  6170. if (graph.isEnabled())
  6171. {
  6172. this.copyCells(textInput, true);
  6173. clearInput();
  6174. }
  6175. }));
  6176. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  6177. {
  6178. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  6179. {
  6180. textInput.innerHTML = '&nbsp;';
  6181. textInput.focus();
  6182. window.setTimeout(mxUtils.bind(this, function()
  6183. {
  6184. this.pasteCells(evt, textInput);
  6185. textInput.innerHTML = '&nbsp;';
  6186. }), 0);
  6187. }
  6188. }), true);
  6189. // Needed for IE11
  6190. var isSelectionAllowed2 = this.isSelectionAllowed;
  6191. this.isSelectionAllowed = function(evt)
  6192. {
  6193. if (mxEvent.getSource(evt) == textInput)
  6194. {
  6195. return true;
  6196. }
  6197. return isSelectionAllowed2.apply(this, arguments);
  6198. };
  6199. };
  6200. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  6201. var x = document.body.clientWidth / 2 - 2;
  6202. // Holds the x-coordinate of the point
  6203. this.spinner = this.createSpinner(x, y, 24);
  6204. // Installs drag and drop handler for rich text editor
  6205. if (Graph.fileSupport)
  6206. {
  6207. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  6208. {
  6209. // Setup the dnd listeners
  6210. var graph = this.editor.graph;
  6211. var textElt = graph.cellEditor.text2;
  6212. var dropElt = null;
  6213. if (textElt != null)
  6214. {
  6215. mxEvent.addListener(textElt, 'dragleave', function(evt)
  6216. {
  6217. if (dropElt != null)
  6218. {
  6219. dropElt.parentNode.removeChild(dropElt);
  6220. dropElt = null;
  6221. }
  6222. evt.stopPropagation();
  6223. evt.preventDefault();
  6224. });
  6225. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  6226. {
  6227. // IE 10 does not implement pointer-events so it can't have a drop highlight
  6228. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  6229. {
  6230. dropElt = this.highlightElement(textElt);
  6231. }
  6232. evt.stopPropagation();
  6233. evt.preventDefault();
  6234. }));
  6235. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  6236. {
  6237. if (dropElt != null)
  6238. {
  6239. dropElt.parentNode.removeChild(dropElt);
  6240. dropElt = null;
  6241. }
  6242. if (evt.dataTransfer.files.length > 0)
  6243. {
  6244. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  6245. {
  6246. // Inserts image into current text box
  6247. graph.insertImage(data, w, h);
  6248. }, function()
  6249. {
  6250. // No post processing
  6251. }, function(file)
  6252. {
  6253. // Handles only images
  6254. return file.type.substring(0, 6) == 'image/';
  6255. }, function(queue)
  6256. {
  6257. // Invokes elements of queue in order
  6258. for (var i = 0; i < queue.length; i++)
  6259. {
  6260. queue[i]();
  6261. }
  6262. }, mxEvent.isControlDown(evt));
  6263. }
  6264. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  6265. {
  6266. var uri = evt.dataTransfer.getData('text/uri-list');
  6267. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  6268. {
  6269. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  6270. {
  6271. var w = Math.max(1, img.width);
  6272. var h = Math.max(1, img.height);
  6273. var maxSize = this.maxImageSize;
  6274. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6275. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  6276. }));
  6277. }
  6278. else
  6279. {
  6280. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  6281. }
  6282. }
  6283. else
  6284. {
  6285. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  6286. {
  6287. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  6288. }
  6289. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  6290. {
  6291. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  6292. }
  6293. }
  6294. evt.stopPropagation();
  6295. evt.preventDefault();
  6296. }));
  6297. }
  6298. }));
  6299. }
  6300. //Add ruler in test mode only
  6301. //TODO add the ruler containers correctly and make the vertical one dynamic as the side panel size can change
  6302. if (urlParams['ruler'] == '1' && typeof mxRuler !== 'undefined')
  6303. {
  6304. var hRulerDiv = document.createElement('div');
  6305. hRulerDiv.style.position = 'absolute';
  6306. hRulerDiv.style.top = '95px';
  6307. hRulerDiv.style.left = '250px';
  6308. hRulerDiv.style.width = '2000px';
  6309. hRulerDiv.style.height = '30px';
  6310. hRulerDiv.style.background = 'whiteSmoke';
  6311. document.body.appendChild(hRulerDiv);
  6312. var vRulerDiv = document.createElement('div');
  6313. vRulerDiv.style.position = 'absolute';
  6314. vRulerDiv.style.top = '125px';
  6315. vRulerDiv.style.left = '220px';
  6316. vRulerDiv.style.width = '30px';
  6317. vRulerDiv.style.height = '1000px';
  6318. vRulerDiv.style.background = 'whiteSmoke';
  6319. document.body.appendChild(vRulerDiv);
  6320. var square = document.createElement('div');
  6321. square.style.position = 'absolute';
  6322. square.style.top = '95px';
  6323. square.style.left = '220px';
  6324. square.style.width = '30px';
  6325. square.style.height = '30px';
  6326. square.style.background = 'whiteSmoke';
  6327. document.body.appendChild(square);
  6328. this.vRuler = new mxRuler(this.editor.graph, vRulerDiv, true);
  6329. this.hRuler = new mxRuler(this.editor.graph, hRulerDiv, false);
  6330. }
  6331. // Adds an element to edit the style in the footer in test mode
  6332. if (urlParams['test'] == '1')
  6333. {
  6334. var footer = document.getElementById('geFooter');
  6335. if (footer != null)
  6336. {
  6337. this.styleInput = document.createElement('input');
  6338. this.styleInput.setAttribute('type', 'text');
  6339. this.styleInput.style.position = 'absolute';
  6340. this.styleInput.style.top = '14px';
  6341. this.styleInput.style.left = '2px';
  6342. // Workaround for ignore right CSS property in FF
  6343. this.styleInput.style.width = '98%';
  6344. this.styleInput.style.visibility = 'hidden';
  6345. this.styleInput.style.opacity = '0.9';
  6346. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  6347. {
  6348. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  6349. }));
  6350. footer.appendChild(this.styleInput);
  6351. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  6352. {
  6353. if (this.editor.graph.getSelectionCount() > 0)
  6354. {
  6355. var cell = this.editor.graph.getSelectionCell();
  6356. var style = this.editor.graph.getModel().getStyle(cell);
  6357. this.styleInput.value = style || '';
  6358. this.styleInput.style.visibility = 'visible';
  6359. } else
  6360. {
  6361. this.styleInput.style.visibility = 'hidden';
  6362. }
  6363. }));
  6364. }
  6365. var isSelectionAllowed = this.isSelectionAllowed;
  6366. this.isSelectionAllowed = function(evt)
  6367. {
  6368. if (mxEvent.getSource(evt) == this.styleInput)
  6369. {
  6370. return true;
  6371. }
  6372. return isSelectionAllowed.apply(this, arguments);
  6373. };
  6374. }
  6375. // Removes info text in page
  6376. var info = document.getElementById('geInfo');
  6377. if (info != null)
  6378. {
  6379. info.parentNode.removeChild(info);
  6380. }
  6381. // Installs drag and drop handler for files
  6382. // Enables dropping files
  6383. if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
  6384. {
  6385. // Setup the dnd listeners
  6386. var dropElt = null;
  6387. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  6388. {
  6389. if (graph.isEnabled())
  6390. {
  6391. if (dropElt != null)
  6392. {
  6393. dropElt.parentNode.removeChild(dropElt);
  6394. dropElt = null;
  6395. }
  6396. evt.stopPropagation();
  6397. evt.preventDefault();
  6398. }
  6399. });
  6400. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  6401. {
  6402. // IE 10 does not implement pointer-events so it can't have a drop highlight
  6403. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  6404. {
  6405. dropElt = this.highlightElement(graph.container);
  6406. }
  6407. if (this.sidebar != null)
  6408. {
  6409. this.sidebar.hideTooltip();
  6410. }
  6411. evt.stopPropagation();
  6412. evt.preventDefault();
  6413. }));
  6414. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  6415. {
  6416. if (dropElt != null)
  6417. {
  6418. dropElt.parentNode.removeChild(dropElt);
  6419. dropElt = null;
  6420. }
  6421. if (graph.isEnabled())
  6422. {
  6423. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  6424. var tr = graph.view.translate;
  6425. var scale = graph.view.scale;
  6426. var x = pt.x / scale - tr.x;
  6427. var y = pt.y / scale - tr.y;
  6428. if (mxEvent.isAltDown(evt))
  6429. {
  6430. x = 0;
  6431. y = 0;
  6432. }
  6433. if (evt.dataTransfer.files.length > 0)
  6434. {
  6435. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  6436. mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  6437. }
  6438. else
  6439. {
  6440. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  6441. evt.dataTransfer.getData('text/uri-list') : null;
  6442. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  6443. if (data != null)
  6444. {
  6445. graph.setSelectionCells(this.importXml(data, x, y, true));
  6446. }
  6447. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  6448. {
  6449. var html = evt.dataTransfer.getData('text/html');
  6450. var div = document.createElement('div');
  6451. div.innerHTML = html;
  6452. // The default is based on the extension
  6453. var asImage = null;
  6454. // Extracts single image
  6455. var imgs = div.getElementsByTagName('img');
  6456. if (imgs != null && imgs.length == 1)
  6457. {
  6458. html = imgs[0].getAttribute('src');
  6459. // Handles special case where the src attribute has no valid extension
  6460. // in which case the text would be inserted as text with a link
  6461. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  6462. {
  6463. asImage = true;
  6464. }
  6465. }
  6466. else
  6467. {
  6468. // Extracts single link
  6469. var a = div.getElementsByTagName('a');
  6470. if (a != null && a.length == 1)
  6471. {
  6472. html = a[0].getAttribute('href');
  6473. }
  6474. }
  6475. var resizeImages = true;
  6476. var doInsert = mxUtils.bind(this, function()
  6477. {
  6478. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage, null, resizeImages));
  6479. });
  6480. if (asImage && html.length > this.resampleThreshold)
  6481. {
  6482. this.confirmImageResize(function(doResize)
  6483. {
  6484. resizeImages = doResize;
  6485. doInsert();
  6486. }, mxEvent.isControlDown(evt));
  6487. }
  6488. else
  6489. {
  6490. doInsert();
  6491. }
  6492. }
  6493. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  6494. {
  6495. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  6496. {
  6497. var w = Math.max(1, img.width);
  6498. var h = Math.max(1, img.height);
  6499. var maxSize = this.maxImageSize;
  6500. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6501. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  6502. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6503. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  6504. }), mxUtils.bind(this, function(img)
  6505. {
  6506. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  6507. }));
  6508. }
  6509. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  6510. {
  6511. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  6512. }
  6513. }
  6514. }
  6515. evt.stopPropagation();
  6516. evt.preventDefault();
  6517. }), false);
  6518. }
  6519. this.initPages();
  6520. // Embedded mode
  6521. if (urlParams['embed'] == '1')
  6522. {
  6523. this.initializeEmbedMode();
  6524. }
  6525. this.installSettings();
  6526. };
  6527. /**
  6528. *
  6529. */
  6530. EditorUi.prototype.isSettingsEnabled = function()
  6531. {
  6532. return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
  6533. };
  6534. /**
  6535. * Creates the format panel and adds overrides.
  6536. */
  6537. EditorUi.prototype.installSettings = function()
  6538. {
  6539. if (this.isSettingsEnabled())
  6540. {
  6541. // Gets recent colors from settings
  6542. ColorDialog.recentColors = mxSettings.getRecentColors();
  6543. /**
  6544. * Persists current edge style.
  6545. */
  6546. this.editor.graph.currentEdgeStyle = mxSettings.getCurrentEdgeStyle();
  6547. this.editor.graph.currentVertexStyle = mxSettings.getCurrentVertexStyle();
  6548. // Updates UI to reflect current edge style
  6549. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  6550. this.addListener('styleChanged', mxUtils.bind(this, function(sender, evt)
  6551. {
  6552. mxSettings.setCurrentEdgeStyle(this.editor.graph.currentEdgeStyle);
  6553. mxSettings.setCurrentVertexStyle(this.editor.graph.currentVertexStyle);
  6554. mxSettings.save();
  6555. }));
  6556. /**
  6557. * Persists copy on connect switch.
  6558. */
  6559. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  6560. this.fireEvent(new mxEventObject('copyConnectChanged'));
  6561. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  6562. {
  6563. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  6564. mxSettings.save();
  6565. }));
  6566. /**
  6567. * Persists default page format.
  6568. */
  6569. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  6570. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  6571. {
  6572. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  6573. mxSettings.save();
  6574. }));
  6575. /**
  6576. * Persists default grid color.
  6577. */
  6578. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  6579. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  6580. {
  6581. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  6582. mxSettings.save();
  6583. }));
  6584. /**
  6585. * Persists autosave switch in Chrome app.
  6586. */
  6587. if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
  6588. {
  6589. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  6590. {
  6591. mxSettings.setAutosave(this.editor.autosave);
  6592. mxSettings.save();
  6593. }));
  6594. this.editor.autosave = mxSettings.getAutosave();
  6595. }
  6596. /**
  6597. *
  6598. */
  6599. if (this.sidebar != null)
  6600. {
  6601. this.sidebar.showPalette('search', mxSettings.settings.search);
  6602. }
  6603. /**
  6604. * Shows scratchpad if never shown.
  6605. */
  6606. if ((!this.editor.chromeless || this.editor.editable) &&
  6607. this.sidebar != null && (mxSettings.settings.isNew ||
  6608. parseInt(mxSettings.settings.version || 0) <= 8))
  6609. {
  6610. this.toggleScratchpad();
  6611. mxSettings.save();
  6612. }
  6613. // Saves app defaults for UI
  6614. this.addListener('formatWidthChanged', function()
  6615. {
  6616. mxSettings.setFormatWidth(this.formatWidth);
  6617. mxSettings.save();
  6618. });
  6619. }
  6620. };
  6621. /**
  6622. * Creates the format panel and adds overrides.
  6623. */
  6624. EditorUi.prototype.copyCells = function(elt, removeCells)
  6625. {
  6626. var graph = this.editor.graph;
  6627. if (!graph.isSelectionEmpty())
  6628. {
  6629. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  6630. // LATER: Add span with XML in data attribute
  6631. // var span = document.createElement('span');
  6632. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  6633. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  6634. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  6635. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  6636. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  6637. if (removeCells)
  6638. {
  6639. graph.removeCells(cells, false);
  6640. graph.lastPasteXml = null;
  6641. }
  6642. else
  6643. {
  6644. graph.lastPasteXml = xml;
  6645. graph.pasteCounter = 0;
  6646. }
  6647. elt.focus();
  6648. document.execCommand('selectAll', false, null);
  6649. }
  6650. else
  6651. {
  6652. // Disables copy on focused element
  6653. elt.innerHTML = '';
  6654. }
  6655. };
  6656. /**
  6657. * Creates the format panel and adds overrides.
  6658. */
  6659. EditorUi.prototype.pasteCells = function(evt, elt)
  6660. {
  6661. if (!mxEvent.isConsumed(evt))
  6662. {
  6663. var spans = elt.getElementsByTagName('span');
  6664. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  6665. 'application/vnd.lucid.chart.objects')
  6666. {
  6667. var content = spans[0].getAttribute('data-lucid-content');
  6668. if (content != null && content.length > 0)
  6669. {
  6670. this.importLucidChart(content, 0, 0);
  6671. mxEvent.consume(evt);
  6672. }
  6673. }
  6674. else
  6675. {
  6676. var graph = this.editor.graph;
  6677. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  6678. mxUtils.getTextContent(elt) : elt.textContent);
  6679. var compat = false;
  6680. // Workaround for junk after XML in VM
  6681. try
  6682. {
  6683. var idx = xml.lastIndexOf('%3E');
  6684. if (idx >= 0 && idx < xml.length - 3)
  6685. {
  6686. xml = xml.substring(0, idx + 3);
  6687. }
  6688. }
  6689. catch (e)
  6690. {
  6691. // ignore
  6692. }
  6693. // Checks for embedded XML content
  6694. try
  6695. {
  6696. var spans = elt.getElementsByTagName('span');
  6697. var tmp = (spans != null && spans.length > 0) ?
  6698. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  6699. decodeURIComponent(xml);
  6700. if (this.isCompatibleString(tmp))
  6701. {
  6702. compat = true;
  6703. xml = tmp;
  6704. }
  6705. }
  6706. catch (e)
  6707. {
  6708. // ignore
  6709. }
  6710. if (graph.lastPasteXml == xml)
  6711. {
  6712. graph.pasteCounter++;
  6713. }
  6714. else
  6715. {
  6716. graph.lastPasteXml = xml;
  6717. graph.pasteCounter = 0;
  6718. }
  6719. var dx = graph.pasteCounter * graph.gridSize;
  6720. if (xml != null && xml.length > 0)
  6721. {
  6722. if (compat || this.isCompatibleString(xml))
  6723. {
  6724. graph.setSelectionCells(this.importXml(xml, dx, dx));
  6725. }
  6726. else
  6727. {
  6728. var pt = graph.getInsertPoint();
  6729. if (graph.isMouseInsertPoint())
  6730. {
  6731. dx = 0;
  6732. // No offset for insert at mouse position
  6733. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  6734. {
  6735. graph.pasteCounter--;
  6736. }
  6737. }
  6738. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  6739. }
  6740. if (!graph.isSelectionEmpty())
  6741. {
  6742. graph.scrollCellToVisible(graph.getSelectionCell());
  6743. if (this.hoverIcons != null)
  6744. {
  6745. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  6746. }
  6747. try
  6748. {
  6749. mxEvent.consume(evt);
  6750. }
  6751. catch (e)
  6752. {
  6753. // ignore event no longer exists in async handler in IE8-
  6754. }
  6755. }
  6756. }
  6757. }
  6758. }
  6759. };
  6760. /**
  6761. * Adds a file drop handler for opening local files.
  6762. */
  6763. EditorUi.prototype.addFileDropHandler = function(elts)
  6764. {
  6765. // Installs drag and drop handler for files
  6766. if (Graph.fileSupport)
  6767. {
  6768. var dropElt = null;
  6769. for (var i = 0; i < elts.length; i++)
  6770. {
  6771. // Setup the dnd listeners
  6772. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  6773. {
  6774. if (dropElt != null)
  6775. {
  6776. dropElt.parentNode.removeChild(dropElt);
  6777. dropElt = null;
  6778. }
  6779. evt.stopPropagation();
  6780. evt.preventDefault();
  6781. });
  6782. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  6783. {
  6784. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  6785. {
  6786. // IE 10 does not implement pointer-events so it can't have a drop highlight
  6787. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  6788. {
  6789. dropElt = this.highlightElement();
  6790. }
  6791. }
  6792. evt.stopPropagation();
  6793. evt.preventDefault();
  6794. }));
  6795. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  6796. {
  6797. if (dropElt != null)
  6798. {
  6799. dropElt.parentNode.removeChild(dropElt);
  6800. dropElt = null;
  6801. }
  6802. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  6803. {
  6804. if (evt.dataTransfer.files.length > 0)
  6805. {
  6806. this.hideDialog();
  6807. // Never open files in embed mode
  6808. if (urlParams['embed'] == '1')
  6809. {
  6810. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  6811. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  6812. }
  6813. else
  6814. {
  6815. this.openFiles(evt.dataTransfer.files, true);
  6816. }
  6817. }
  6818. else
  6819. {
  6820. // Handles open special files via text drag and drop
  6821. var data = this.extractGraphModelFromEvent(evt);
  6822. // Tries additional and async parsing of text content such as HTML, Gliffy data
  6823. if (data == null)
  6824. {
  6825. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  6826. if (provider != null)
  6827. {
  6828. if (document.documentMode == 10 || document.documentMode == 11)
  6829. {
  6830. data = provider.getData('Text');
  6831. }
  6832. else
  6833. {
  6834. var data = null;
  6835. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  6836. {
  6837. var data = evt.dataTransfer.getData('text/uri-list');
  6838. }
  6839. else
  6840. {
  6841. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  6842. }
  6843. if (data != null && data.length > 0)
  6844. {
  6845. var div = document.createElement('div');
  6846. div.innerHTML = data;
  6847. // Extracts single image
  6848. var imgs = div.getElementsByTagName('img');
  6849. if (imgs.length > 0)
  6850. {
  6851. data = imgs[0].getAttribute('src');
  6852. }
  6853. }
  6854. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  6855. {
  6856. data = provider.getData('text/plain');
  6857. }
  6858. }
  6859. if (data != null)
  6860. {
  6861. // Checks for embedded XML in PNG
  6862. if (data.substring(0, 22) == 'data:image/png;base64,')
  6863. {
  6864. var xml = this.extractGraphModelFromPng(data);
  6865. if (xml != null && xml.length > 0)
  6866. {
  6867. this.openLocalFile(xml, null, true);
  6868. }
  6869. }
  6870. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  6871. {
  6872. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  6873. {
  6874. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  6875. {
  6876. this.openLocalFile(req.getText(), null, true);
  6877. }
  6878. }));
  6879. }
  6880. else if (/^https?:\/\//.test(data))
  6881. {
  6882. if (this.getCurrentFile() == null)
  6883. {
  6884. window.location.hash = '#U' + encodeURIComponent(data);
  6885. }
  6886. else
  6887. {
  6888. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  6889. 'https://www.draw.io/' : 'https://' + location.host + '/') +
  6890. window.location.search + '#U' + encodeURIComponent(data));
  6891. }
  6892. }
  6893. }
  6894. }
  6895. }
  6896. else
  6897. {
  6898. this.openLocalFile(data, null, true);
  6899. }
  6900. }
  6901. }
  6902. evt.stopPropagation();
  6903. evt.preventDefault();
  6904. }));
  6905. }
  6906. }
  6907. };
  6908. /**
  6909. * Highlights the given element
  6910. */
  6911. EditorUi.prototype.highlightElement = function(elt)
  6912. {
  6913. var x = 0;
  6914. var y = 0;
  6915. var w = 0;
  6916. var h = 0;
  6917. if (elt == null)
  6918. {
  6919. var b = document.body;
  6920. var d = document.documentElement;
  6921. w = (b.clientWidth || d.clientWidth) - 3;
  6922. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  6923. }
  6924. else
  6925. {
  6926. x = elt.offsetTop;
  6927. y = elt.offsetLeft;
  6928. w = elt.clientWidth;
  6929. h = elt.clientHeight;
  6930. }
  6931. var hl = document.createElement('div');
  6932. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  6933. hl.style.border = '3px dotted rgb(254, 137, 12)';
  6934. hl.style.pointerEvents = 'none';
  6935. hl.style.position = 'absolute';
  6936. hl.style.top = x + 'px';
  6937. hl.style.left = y + 'px';
  6938. hl.style.width = Math.max(0, w - 3) + 'px';
  6939. hl.style.height = Math.max(0, h - 3) + 'px';
  6940. if (elt != null && elt.parentNode == this.editor.graph.container)
  6941. {
  6942. this.editor.graph.container.appendChild(hl);
  6943. }
  6944. else
  6945. {
  6946. document.body.appendChild(hl);
  6947. }
  6948. return hl;
  6949. };
  6950. /**
  6951. * Highlights the given element
  6952. */
  6953. EditorUi.prototype.stringToCells = function(xml)
  6954. {
  6955. var doc = mxUtils.parseXml(xml);
  6956. var node = this.editor.extractGraphModel(doc.documentElement);
  6957. var cells = [];
  6958. if (node != null)
  6959. {
  6960. var codec = new mxCodec(node.ownerDocument);
  6961. var model = new mxGraphModel();
  6962. codec.decode(node, model);
  6963. var parent = model.getChildAt(model.getRoot(), 0);
  6964. for (var j = 0; j < model.getChildCount(parent); j++)
  6965. {
  6966. cells.push(model.getChildAt(parent, j));
  6967. }
  6968. }
  6969. return cells;
  6970. };
  6971. /**
  6972. * Opens the given files in the editor.
  6973. */
  6974. EditorUi.prototype.openFiles = function(files, temp)
  6975. {
  6976. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6977. {
  6978. for (var i = 0; i < files.length; i++)
  6979. {
  6980. (mxUtils.bind(this, function(file)
  6981. {
  6982. var reader = new FileReader();
  6983. reader.onload = mxUtils.bind(this, function(e)
  6984. {
  6985. var data = e.target.result;
  6986. var name = file.name;
  6987. if (name != null && name.length > 0)
  6988. {
  6989. if (!this.useCanvasForExport && /(\.png)$/i.test(name))
  6990. {
  6991. name = name.substring(0, name.length - 4) + '.xml';
  6992. }
  6993. var handleResult = mxUtils.bind(this, function(xml)
  6994. {
  6995. var dot = name.lastIndexOf('.');
  6996. if (dot >= 0)
  6997. {
  6998. name = name.substring(0, name.lastIndexOf('.')) + '.xml';
  6999. }
  7000. else
  7001. {
  7002. name = name + '.xml';
  7003. }
  7004. if (xml.substring(0, 10) == '<mxlibrary')
  7005. {
  7006. // Creates new temporary file if library is dropped in splash screen
  7007. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  7008. {
  7009. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  7010. }
  7011. try
  7012. {
  7013. this.loadLibrary(new LocalLibrary(this, xml, name));
  7014. }
  7015. catch (e)
  7016. {
  7017. this.handleError(e, mxResources.get('errorLoadingFile'));
  7018. }
  7019. }
  7020. else
  7021. {
  7022. this.openLocalFile(xml, name, temp);
  7023. }
  7024. });
  7025. if (/(\.vsdx)($|\?)/i.test(name) || /(\.vssx)($|\?)/i.test(name) || /(\.vsd)($|\?)/i.test(name))
  7026. {
  7027. this.importVisio(file, mxUtils.bind(this, function(xml)
  7028. {
  7029. this.spinner.stop();
  7030. handleResult(xml);
  7031. }));
  7032. }
  7033. else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  7034. this.isRemoteFileFormat(data, name))
  7035. {
  7036. this.parseFile(file, mxUtils.bind(this, function(xhr)
  7037. {
  7038. if (xhr.readyState == 4)
  7039. {
  7040. this.spinner.stop();
  7041. if (xhr.status >= 200 && xhr.status <= 299)
  7042. {
  7043. handleResult(xhr.responseText);
  7044. }
  7045. else
  7046. {
  7047. this.handleError({message: mxResources.get((xhr.status == 413) ?
  7048. 'drawingTooLarge' : 'invalidOrMissingFile')},
  7049. mxResources.get('errorLoadingFile'));
  7050. }
  7051. }
  7052. }));
  7053. }
  7054. else if (data.substring(0, 26) == '{"state":"{\\"Properties\\":')
  7055. {
  7056. if (/(\.json)$/i.test(name))
  7057. {
  7058. name = name.substring(0, name.length - 5) + '.xml';
  7059. }
  7060. // LATER: Add import step that produces cells and use callback
  7061. this.openLocalFile(this.emptyDiagramXml, name, temp);
  7062. this.importLucidChart(data, 0, 0, null, mxUtils.bind(this, function()
  7063. {
  7064. this.editor.undoManager.clear();
  7065. this.spinner.stop();
  7066. }));
  7067. }
  7068. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  7069. {
  7070. this.spinner.stop();
  7071. // Creates new temporary file if library is dropped in splash screen
  7072. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  7073. {
  7074. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  7075. }
  7076. try
  7077. {
  7078. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  7079. }
  7080. catch (e)
  7081. {
  7082. this.handleError(e, mxResources.get('errorLoadingFile'));
  7083. }
  7084. }
  7085. else
  7086. {
  7087. if (file.type.substring(0, 9) == 'image/png')
  7088. {
  7089. data = this.extractGraphModelFromPng(data);
  7090. }
  7091. this.spinner.stop();
  7092. this.openLocalFile(data, name, temp);
  7093. }
  7094. }
  7095. });
  7096. reader.onerror = mxUtils.bind(this, function(e)
  7097. {
  7098. this.spinner.stop();
  7099. this.handleError(e);
  7100. window.openFile = null;
  7101. });
  7102. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  7103. {
  7104. reader.readAsDataURL(file);
  7105. }
  7106. else
  7107. {
  7108. reader.readAsText(file);
  7109. }
  7110. }))(files[i]);
  7111. }
  7112. }
  7113. };
  7114. /**
  7115. * Shows the layers dialog if the graph has more than one layer.
  7116. */
  7117. EditorUi.prototype.openLocalFile = function(data, name, temp)
  7118. {
  7119. var currentFile = this.getCurrentFile();
  7120. var fn = mxUtils.bind(this, function()
  7121. {
  7122. window.openFile = null;
  7123. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  7124. {
  7125. var doc = mxUtils.parseXml(data);
  7126. if (doc != null)
  7127. {
  7128. this.editor.setGraphXml(doc.documentElement);
  7129. this.editor.graph.selectAll();
  7130. }
  7131. }
  7132. else
  7133. {
  7134. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  7135. }
  7136. });
  7137. if (data != null && data.length > 0)
  7138. {
  7139. if (currentFile == null || (!currentFile.isModified() &&
  7140. (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)))
  7141. {
  7142. fn();
  7143. }
  7144. else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) &&
  7145. currentFile != null && currentFile.isModified())
  7146. {
  7147. this.confirm(mxResources.get('allChangesLost'), null, fn,
  7148. mxResources.get('cancel'), mxResources.get('discardChanges'));
  7149. }
  7150. else
  7151. {
  7152. window.openFile = new OpenFile(function()
  7153. {
  7154. window.openFile = null;
  7155. });
  7156. window.openFile.setData(data, name);
  7157. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  7158. {
  7159. this.confirm(mxResources.get('allChangesLost'), null, fn,
  7160. mxResources.get('cancel'), mxResources.get('discardChanges'));
  7161. }));
  7162. }
  7163. }
  7164. };
  7165. /**
  7166. * Returns a list of all shapes used in the current file.
  7167. */
  7168. EditorUi.prototype.getBasenames = function()
  7169. {
  7170. var basenames = {};
  7171. if (this.pages != null)
  7172. {
  7173. for (var i = 0; i < this.pages.length; i++)
  7174. {
  7175. this.updatePageRoot(this.pages[i]);
  7176. this.addBasenamesForCell(this.pages[i].root, basenames);
  7177. }
  7178. }
  7179. else
  7180. {
  7181. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  7182. }
  7183. var result = [];
  7184. for (var key in basenames)
  7185. {
  7186. result.push(key);
  7187. }
  7188. return result;
  7189. };
  7190. /**
  7191. * Returns a list of all shapes used in the current file.
  7192. */
  7193. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  7194. {
  7195. function addName(name)
  7196. {
  7197. if (name != null)
  7198. {
  7199. // LATER: Check if this case exists
  7200. var dot = name.lastIndexOf('.');
  7201. if (dot > 0)
  7202. {
  7203. name = name.substring(dot + 1, name.length);
  7204. }
  7205. if (basenames[name] == null)
  7206. {
  7207. basenames[name] = true;
  7208. }
  7209. }
  7210. };
  7211. var graph = this.editor.graph;
  7212. var style = graph.getCellStyle(cell);
  7213. var shape = style[mxConstants.STYLE_SHAPE];
  7214. addName(mxStencilRegistry.getBasenameForStencil(shape));
  7215. // Adds package names for markers in edges
  7216. if (graph.model.isEdge(cell))
  7217. {
  7218. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  7219. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  7220. }
  7221. var childCount = graph.model.getChildCount(cell);
  7222. for (var i = 0; i < childCount; i++)
  7223. {
  7224. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  7225. }
  7226. };
  7227. /**
  7228. * Shows the layers dialog if the graph has more than one layer.
  7229. */
  7230. EditorUi.prototype.setGraphEnabled = function(enabled)
  7231. {
  7232. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  7233. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  7234. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  7235. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  7236. this.hsplit.style.display = (enabled) ? '' : 'none';
  7237. this.editor.graph.setEnabled(enabled);
  7238. if (this.tabContainer != null)
  7239. {
  7240. this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
  7241. }
  7242. };
  7243. /**
  7244. * Shows the layers dialog if the graph has more than one layer.
  7245. */
  7246. EditorUi.prototype.initializeEmbedMode = function()
  7247. {
  7248. this.setGraphEnabled(false);
  7249. var parent = window.opener || window.parent;
  7250. if (parent != window)
  7251. {
  7252. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  7253. {
  7254. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  7255. {
  7256. this.spinner.stop();
  7257. this.addEmbedButtons();
  7258. this.setGraphEnabled(true);
  7259. if (xml != null && xml.length > 0)
  7260. {
  7261. this.setFileData(xml);
  7262. if (!this.editor.isChromelessView())
  7263. {
  7264. this.showLayersDialog();
  7265. }
  7266. else if (this.editor.graph.isLightboxView())
  7267. {
  7268. this.lightboxFit();
  7269. }
  7270. if (this.chromelessResize)
  7271. {
  7272. this.chromelessResize();
  7273. }
  7274. }
  7275. else
  7276. {
  7277. this.editor.graph.model.clear();
  7278. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  7279. }
  7280. this.editor.undoManager.clear();
  7281. this.editor.modified = (modified != null) ? modified : false;
  7282. this.updateUi();
  7283. // Workaround for no initial focus in FF
  7284. // (does not work in Conf Cloud with FF)
  7285. if (window.self !== window.top)
  7286. {
  7287. window.focus();
  7288. }
  7289. if (this.format != null)
  7290. {
  7291. this.format.refresh();
  7292. }
  7293. }));
  7294. }
  7295. }
  7296. };
  7297. /**
  7298. * Shows the layers dialog if the graph has more than one layer.
  7299. */
  7300. EditorUi.prototype.showLayersDialog = function()
  7301. {
  7302. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  7303. {
  7304. if (this.actions.layersWindow == null)
  7305. {
  7306. this.actions.get('layers').funct();
  7307. }
  7308. else
  7309. {
  7310. this.actions.layersWindow.window.setVisible(true);
  7311. }
  7312. }
  7313. };
  7314. /**
  7315. * Tries to find a public URL for the given file.
  7316. */
  7317. EditorUi.prototype.getPublicUrl = function(file, fn)
  7318. {
  7319. if (file != null)
  7320. {
  7321. file.getPublicUrl(fn);
  7322. }
  7323. else
  7324. {
  7325. fn(null);
  7326. }
  7327. };
  7328. /**
  7329. * Adds the buttons for embedded mode.
  7330. */
  7331. EditorUi.prototype.createLoadMessage = function(eventName)
  7332. {
  7333. var graph = this.editor.graph;
  7334. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  7335. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds(), bounds: graph.getGraphBounds()};
  7336. };
  7337. /**
  7338. * Adds the buttons for embedded mode.
  7339. */
  7340. EditorUi.prototype.installMessageHandler = function(fn)
  7341. {
  7342. var changeListener = null;
  7343. var ignoreChange = false;
  7344. var autosave = false;
  7345. var lastData = null;
  7346. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  7347. {
  7348. if (!this.editor.modified || urlParams['modified'] == '0')
  7349. {
  7350. this.editor.setStatus('');
  7351. }
  7352. else if (urlParams['modified'] != null)
  7353. {
  7354. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  7355. }
  7356. });
  7357. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  7358. // Receives XML message from opener and puts it into the graph
  7359. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  7360. {
  7361. var validSource = window.opener || window.parent;
  7362. if (evt.source != validSource)
  7363. {
  7364. return;
  7365. }
  7366. var data = evt.data;
  7367. function extractDiagramXml(data)
  7368. {
  7369. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  7370. {
  7371. try
  7372. {
  7373. if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  7374. {
  7375. data = atob(data.substring(26));
  7376. }
  7377. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  7378. {
  7379. data = data.substring(24);
  7380. }
  7381. if (data != null)
  7382. {
  7383. if (data.charAt(0) == '%')
  7384. {
  7385. data = decodeURIComponent(data);
  7386. }
  7387. else if (data.charAt(0) != '<')
  7388. {
  7389. data = this.editor.graph.decompress(data);
  7390. }
  7391. }
  7392. }
  7393. catch (e)
  7394. {
  7395. // ignore compression errors and use empty data
  7396. }
  7397. }
  7398. return data;
  7399. };
  7400. if (urlParams['proto'] == 'json')
  7401. {
  7402. try
  7403. {
  7404. data = JSON.parse(data);
  7405. }
  7406. catch (e)
  7407. {
  7408. data = null;
  7409. }
  7410. if (data == null)
  7411. {
  7412. // Ignore
  7413. return;
  7414. }
  7415. else if (data.action == 'dialog')
  7416. {
  7417. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  7418. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  7419. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  7420. if (data.modified != null)
  7421. {
  7422. this.editor.modified = data.modified;
  7423. }
  7424. return;
  7425. }
  7426. else if (data.action == 'prompt')
  7427. {
  7428. this.spinner.stop();
  7429. var dlg = new FilenameDialog(this, data.defaultValue || '',
  7430. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  7431. {
  7432. if (value != null)
  7433. {
  7434. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  7435. }
  7436. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  7437. this.showDialog(dlg.container, 300, 80, true, false);
  7438. dlg.init();
  7439. return;
  7440. }
  7441. else if (data.action == 'draft')
  7442. {
  7443. var tmp = null;
  7444. if (data.xml.substring(0, 22) == 'data:image/png;base64,')
  7445. {
  7446. tmp = this.extractGraphModelFromPng(data.xml);
  7447. }
  7448. else
  7449. {
  7450. tmp = extractDiagramXml(data.xml);
  7451. }
  7452. this.spinner.stop();
  7453. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  7454. tmp, mxUtils.bind(this, function()
  7455. {
  7456. this.hideDialog();
  7457. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  7458. }), mxUtils.bind(this, function()
  7459. {
  7460. this.hideDialog();
  7461. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  7462. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  7463. (data.discardKey) ? mxResources.get(data.discardKey) : null,
  7464. (data.ignore) ? mxUtils.bind(this, function()
  7465. {
  7466. this.hideDialog();
  7467. parent.postMessage(JSON.stringify({event: 'draft', result: 'ignore', message: data}), '*');
  7468. }) : null);
  7469. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  7470. {
  7471. if (cancel)
  7472. {
  7473. this.actions.get('exit').funct();
  7474. }
  7475. }));
  7476. try
  7477. {
  7478. dlg.init();
  7479. }
  7480. catch (e)
  7481. {
  7482. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  7483. }
  7484. return;
  7485. }
  7486. else if (data.action == 'template')
  7487. {
  7488. this.spinner.stop();
  7489. var enableRecentDocs = data.enableRecent == 1;
  7490. var enableSearchDocs = data.enableSearch == 1;
  7491. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  7492. {
  7493. xml = xml || this.emptyDiagramXml;
  7494. // LATER: Add autosave option in template message
  7495. if (data.callback != null)
  7496. {
  7497. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  7498. blank: xml == this.emptyDiagramXml, name: name}), '*');
  7499. }
  7500. else
  7501. {
  7502. fn(xml, evt, xml != this.emptyDiagramXml);
  7503. // Workaround for status updated before modified applied
  7504. if (!this.editor.modified)
  7505. {
  7506. this.editor.setStatus('');
  7507. }
  7508. }
  7509. }), null, null, null, null, null, null, null,
  7510. enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
  7511. {
  7512. this.recentReadyCallback = recentReadyCallback;
  7513. parent.postMessage(JSON.stringify({event: 'recentDocs'}), '*');
  7514. }) : null,
  7515. enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
  7516. {
  7517. this.searchReadyCallback = searchReadyCallback;
  7518. parent.postMessage(JSON.stringify({event: 'searchDocs', searchStr: searchStr}), '*');
  7519. }) : null,
  7520. function(url, info, name)
  7521. {
  7522. parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
  7523. name: name}), '*');
  7524. });
  7525. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  7526. {
  7527. if (cancel)
  7528. {
  7529. this.actions.get('exit').funct();
  7530. }
  7531. }));
  7532. dlg.init();
  7533. return;
  7534. }
  7535. else if (data.action == 'searchDocsList')
  7536. {
  7537. this.searchReadyCallback(data.list, data.errorMsg);
  7538. }
  7539. else if (data.action == 'recentDocsList')
  7540. {
  7541. this.recentReadyCallback(data.list, data.errorMsg);
  7542. }
  7543. else if (data.action == 'status')
  7544. {
  7545. if (data.messageKey != null)
  7546. {
  7547. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  7548. }
  7549. else if (data.message != null)
  7550. {
  7551. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  7552. }
  7553. if (data.modified != null)
  7554. {
  7555. this.editor.modified = data.modified;
  7556. }
  7557. return;
  7558. }
  7559. else if (data.action == 'spinner')
  7560. {
  7561. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  7562. if (data.show != null && !data.show)
  7563. {
  7564. this.spinner.stop();
  7565. }
  7566. else
  7567. {
  7568. this.spinner.spin(document.body, msg)
  7569. }
  7570. return;
  7571. }
  7572. else if (data.action == 'export')
  7573. {
  7574. if (data.format == 'png' || data.format == 'xmlpng')
  7575. {
  7576. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  7577. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  7578. {
  7579. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  7580. this.editor.graph.setEnabled(false);
  7581. var graph = this.editor.graph;
  7582. var postDataBack = mxUtils.bind(this, function(uri)
  7583. {
  7584. this.editor.graph.setEnabled(true);
  7585. this.spinner.stop();
  7586. var msg = this.createLoadMessage('export');
  7587. msg.format = data.format;
  7588. msg.message = data;
  7589. msg.data = uri;
  7590. msg.xml = encodeURIComponent(xml);
  7591. parent.postMessage(JSON.stringify(msg), '*');
  7592. });
  7593. var processUri = mxUtils.bind(this, function(uri)
  7594. {
  7595. if (uri == null)
  7596. {
  7597. uri = Editor.blankImage;
  7598. }
  7599. if (data.format == 'xmlpng')
  7600. {
  7601. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  7602. atob(this.editor.graph.compress(xml)));
  7603. }
  7604. // Removes temporary graph from DOM
  7605. if (graph != this.editor.graph)
  7606. {
  7607. graph.container.parentNode.removeChild(graph.container);
  7608. }
  7609. postDataBack(uri);
  7610. });
  7611. // LATER: Uses external export if current page (not first page) has mathEnabled
  7612. if (this.isExportToCanvas())
  7613. {
  7614. // Exports PNG for first page while other page is visible by creating a graph
  7615. // LATER: Add caching for the graph or SVG while not on first page
  7616. if (this.pages != null && this.currentPage != this.pages[0])
  7617. {
  7618. graph = this.createTemporaryGraph(graph.getStylesheet());
  7619. var graphGetGlobalVariable = graph.getGlobalVariable;
  7620. var page = this.pages[0];
  7621. graph.getGlobalVariable = function(name)
  7622. {
  7623. if (name == 'page')
  7624. {
  7625. return page.getName();
  7626. }
  7627. else if (name == 'pagenumber')
  7628. {
  7629. return 1;
  7630. }
  7631. return graphGetGlobalVariable.apply(this, arguments);
  7632. };
  7633. document.body.appendChild(graph.container);
  7634. graph.model.setRoot(page.root);
  7635. }
  7636. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  7637. {
  7638. processUri(canvas.toDataURL('image/png'));
  7639. }), null, null, null, mxUtils.bind(this, function()
  7640. {
  7641. processUri(null);
  7642. }), null, null, null, null, null, null, graph);
  7643. }
  7644. else
  7645. {
  7646. // Data from server is base64 encoded to avoid binary XHR
  7647. // Double encoding for XML arg is needed for UTF8 encoding
  7648. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  7649. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  7650. encodeURIComponent(encodeURIComponent(xml)));
  7651. req.send(mxUtils.bind(this, function(req)
  7652. {
  7653. // Temp graph was never created at this point so we can
  7654. // skip processUri since it already contains the XML
  7655. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  7656. {
  7657. postDataBack('data:image/png;base64,' + req.getText());
  7658. }
  7659. else
  7660. {
  7661. processUri(null);
  7662. }
  7663. }), mxUtils.bind(this, function()
  7664. {
  7665. processUri(null);
  7666. }));
  7667. }
  7668. }
  7669. }
  7670. else
  7671. {
  7672. // SVG is generated from graph so parse optional XML
  7673. if (data.xml != null && data.xml.length > 0)
  7674. {
  7675. this.setFileData(data.xml);
  7676. }
  7677. var msg = this.createLoadMessage('export');
  7678. // Forces new HTML format if pages exists
  7679. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  7680. (this.pages != null && this.pages.length > 1))))
  7681. {
  7682. var node = this.getXmlFileData();
  7683. msg.xml = mxUtils.getXml(node);
  7684. msg.data = this.getFileData(null, null, true, null, null, null, node);
  7685. msg.format = data.format;
  7686. }
  7687. else if (data.format == 'html')
  7688. {
  7689. var xml = this.editor.getGraphXml();
  7690. msg.data = this.getHtml(xml, this.editor.graph);
  7691. msg.xml = mxUtils.getXml(xml);
  7692. msg.format = data.format;
  7693. }
  7694. else
  7695. {
  7696. // Creates a preview with no alt text for unsupported browsers
  7697. mxSvgCanvas2D.prototype.foAltText = null;
  7698. var bg = this.editor.graph.background;
  7699. if (bg == mxConstants.NONE)
  7700. {
  7701. bg = null;
  7702. }
  7703. msg.xml = this.getFileData(true);
  7704. msg.format = 'svg';
  7705. if (data.embedImages || data.embedImages == null)
  7706. {
  7707. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  7708. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  7709. {
  7710. this.editor.graph.setEnabled(false);
  7711. if (data.format == 'xmlsvg')
  7712. {
  7713. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  7714. {
  7715. this.editor.graph.setEnabled(true);
  7716. this.spinner.stop();
  7717. msg.data = this.createSvgDataUri(svg);
  7718. parent.postMessage(JSON.stringify(msg), '*');
  7719. }));
  7720. }
  7721. else
  7722. {
  7723. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  7724. {
  7725. this.editor.graph.setEnabled(true);
  7726. this.spinner.stop();
  7727. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  7728. parent.postMessage(JSON.stringify(msg), '*');
  7729. }));
  7730. }
  7731. }
  7732. return;
  7733. }
  7734. else
  7735. {
  7736. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  7737. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  7738. msg.data = this.createSvgDataUri(svg);
  7739. }
  7740. }
  7741. parent.postMessage(JSON.stringify(msg), '*');
  7742. }
  7743. return;
  7744. }
  7745. else if (data.action == 'load')
  7746. {
  7747. autosave = data.autosave == 1;
  7748. this.hideDialog();
  7749. if (data.modified != null && urlParams['modified'] == null)
  7750. {
  7751. urlParams['modified'] = data.modified;
  7752. }
  7753. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  7754. {
  7755. urlParams['saveAndExit'] = data.saveAndExit;
  7756. }
  7757. if (data.title != null && this.buttonContainer != null)
  7758. {
  7759. var tmp = document.createElement('span');
  7760. mxUtils.write(tmp, data.title);
  7761. if (uiTheme == 'atlas')
  7762. {
  7763. this.buttonContainer.style.paddingRight = '12px';
  7764. this.buttonContainer.style.paddingTop = '12px';
  7765. }
  7766. else if (uiTheme != 'min')
  7767. {
  7768. this.buttonContainer.style.paddingRight = '38px';
  7769. this.buttonContainer.style.paddingTop = '6px';
  7770. }
  7771. if (this.embedFilenameSpan != null)
  7772. {
  7773. this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
  7774. }
  7775. this.buttonContainer.appendChild(tmp);
  7776. this.embedFilenameSpan = tmp;
  7777. }
  7778. if (data.xmlpng != null)
  7779. {
  7780. data = this.extractGraphModelFromPng(data.xmlpng);
  7781. }
  7782. else if (data.xml != null && data.xml.substring(0, 22) == 'data:image/png;base64,')
  7783. {
  7784. data = this.extractGraphModelFromPng(data.xml);
  7785. }
  7786. else
  7787. {
  7788. data = data.xml;
  7789. }
  7790. }
  7791. else
  7792. {
  7793. // Unknown message must stop execution
  7794. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  7795. return;
  7796. }
  7797. }
  7798. data = extractDiagramXml(data);
  7799. ignoreChange = true;
  7800. try
  7801. {
  7802. fn(data, evt);
  7803. }
  7804. catch (e)
  7805. {
  7806. this.handleError(e);
  7807. }
  7808. ignoreChange = false;
  7809. if (urlParams['modified'] != null)
  7810. {
  7811. this.editor.setStatus('');
  7812. }
  7813. var getData = mxUtils.bind(this, function()
  7814. {
  7815. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  7816. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  7817. });;
  7818. lastData = getData();
  7819. if (autosave && changeListener == null)
  7820. {
  7821. changeListener = mxUtils.bind(this, function(sender, eventObject)
  7822. {
  7823. var data = getData();
  7824. if (data != lastData && !ignoreChange)
  7825. {
  7826. var msg = this.createLoadMessage('autosave');
  7827. msg.xml = data;
  7828. data = JSON.stringify(msg);
  7829. var parent = window.opener || window.parent;
  7830. parent.postMessage(data, '*');
  7831. }
  7832. lastData = data;
  7833. });
  7834. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  7835. // Some options trigger autosave
  7836. this.editor.graph.addListener('gridSizeChanged', changeListener);
  7837. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  7838. this.addListener('pageFormatChanged', changeListener);
  7839. this.addListener('pageScaleChanged', changeListener);
  7840. this.addListener('backgroundColorChanged', changeListener);
  7841. this.addListener('backgroundImageChanged', changeListener);
  7842. this.addListener('foldingEnabledChanged', changeListener);
  7843. this.addListener('mathEnabledChanged', changeListener);
  7844. this.addListener('gridEnabledChanged', changeListener);
  7845. this.addListener('guidesEnabledChanged', changeListener);
  7846. this.addListener('pageViewChanged', changeListener);
  7847. }
  7848. // Sends the bounds of the graph to the host after parsing
  7849. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  7850. {
  7851. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  7852. }
  7853. }));
  7854. // Requests data from the sender. This is a workaround for not allowing
  7855. // the opener to listen for the onload event if not in the same origin.
  7856. var parent = window.opener || window.parent;
  7857. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  7858. parent.postMessage(msg, '*');
  7859. };
  7860. /**
  7861. * Adds the buttons for embedded mode.
  7862. */
  7863. EditorUi.prototype.addEmbedButtons = function()
  7864. {
  7865. if (this.menubar != null)
  7866. {
  7867. var div = document.createElement('div');
  7868. div.style.display = 'inline-block';
  7869. div.style.position = 'absolute';
  7870. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  7871. div.style.paddingLeft = '8px';
  7872. div.style.paddingBottom = '2px';
  7873. var button = document.createElement('button');
  7874. mxUtils.write(button, mxResources.get('save'));
  7875. button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
  7876. button.className = 'geBigButton';
  7877. button.style.fontSize = '12px';
  7878. button.style.padding = '4px 6px 4px 6px';
  7879. button.style.borderRadius = '3px';
  7880. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  7881. {
  7882. this.actions.get('save').funct();
  7883. }));
  7884. div.appendChild(button);
  7885. if (urlParams['saveAndExit'] == '1')
  7886. {
  7887. button = document.createElement('a');
  7888. mxUtils.write(button, mxResources.get('saveAndExit'));
  7889. button.setAttribute('title', mxResources.get('saveAndExit'));
  7890. button.style.fontSize = '12px';
  7891. button.style.marginLeft = '6px';
  7892. button.style.padding = '4px';
  7893. button.style.cursor = 'pointer';
  7894. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  7895. {
  7896. this.actions.get('saveAndExit').funct();
  7897. }));
  7898. div.appendChild(button);
  7899. }
  7900. button = document.createElement('a');
  7901. mxUtils.write(button, mxResources.get('exit'));
  7902. button.setAttribute('title', mxResources.get('exit'));
  7903. button.style.fontSize = '12px';
  7904. button.style.marginLeft = '6px';
  7905. button.style.marginRight = '20px';
  7906. button.style.padding = '4px';
  7907. button.style.cursor = 'pointer';
  7908. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  7909. {
  7910. this.actions.get('exit').funct();
  7911. }));
  7912. div.appendChild(button);
  7913. this.toolbar.container.appendChild(div);
  7914. this.toolbar.staticElements.push(div);
  7915. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  7916. }
  7917. };
  7918. /**
  7919. *
  7920. */
  7921. EditorUi.prototype.showImportCsvDialog = function()
  7922. {
  7923. if (this.importCsvDialog == null)
  7924. {
  7925. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  7926. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  7927. {
  7928. this.importCsv(newValue);
  7929. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  7930. }
  7931. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  7932. this.importCsvDialog.init();
  7933. };
  7934. /**
  7935. * TODO: Move to Editor
  7936. */
  7937. EditorUi.prototype.importCsv = function(text)
  7938. {
  7939. try
  7940. {
  7941. var lines = text.split('\n');
  7942. var cells = [];
  7943. if (lines.length > 0)
  7944. {
  7945. // Internal lookup table
  7946. var lookups = {};
  7947. // Default values
  7948. var style = null;
  7949. var identity = null;
  7950. var namespace = '';
  7951. var width = 'auto';
  7952. var height = 'auto';
  7953. var left = null;
  7954. var top = null;
  7955. var edgespacing = 40;
  7956. var nodespacing = 40;
  7957. var padding = 0;
  7958. var graph = this.editor.graph;
  7959. var view = graph.view;
  7960. var bds = graph.getGraphBounds();
  7961. // Delayed after optional layout
  7962. var afterInsert = function()
  7963. {
  7964. graph.setSelectionCells(select);
  7965. graph.scrollCellToVisible(graph.getSelectionCell());
  7966. };
  7967. // Computes unscaled, untranslated graph bounds
  7968. var pt = graph.getFreeInsertPoint();
  7969. var x0 = pt.x;
  7970. var y0 = pt.y;
  7971. var y = y0;
  7972. // Default label value depends on column names
  7973. var label = null;
  7974. // Default layout to run.
  7975. var layout = 'auto';
  7976. // Name of the attribute that contains the parent reference
  7977. var parent = null;
  7978. // Name of the attribute that contains the references for creating edges
  7979. var edges = [];
  7980. // Name of the column for hyperlinks
  7981. var link = null;
  7982. // String array of names to remove from metadata
  7983. var ignore = null;
  7984. // Read processing instructions first
  7985. var index = 0;
  7986. while (index < lines.length && lines[index].charAt(0) == '#')
  7987. {
  7988. var text = lines[index];
  7989. index++;
  7990. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  7991. lines[index].charAt(0) == '#')
  7992. {
  7993. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  7994. index++;
  7995. }
  7996. if (text.charAt(1) != '#')
  7997. {
  7998. // Processing instruction
  7999. var idx = text.indexOf(':');
  8000. if (idx > 0)
  8001. {
  8002. var key = mxUtils.trim(text.substring(1, idx));
  8003. var value = mxUtils.trim(text.substring(idx + 1));
  8004. if (key == 'label')
  8005. {
  8006. label = graph.sanitizeHtml(value);
  8007. }
  8008. else if (key == 'style')
  8009. {
  8010. style = value;
  8011. }
  8012. else if (key == 'identity' && value.length > 0 && value != '-')
  8013. {
  8014. identity = value;
  8015. }
  8016. else if (key == 'namespace' && value.length > 0 && value != '-')
  8017. {
  8018. namespace = value;
  8019. }
  8020. else if (key == 'width')
  8021. {
  8022. width = value;
  8023. }
  8024. else if (key == 'height')
  8025. {
  8026. height = value;
  8027. }
  8028. else if (key == 'left' && value.length > 0)
  8029. {
  8030. left = value;
  8031. }
  8032. else if (key == 'top' && value.length > 0)
  8033. {
  8034. top = value;
  8035. }
  8036. else if (key == 'ignore')
  8037. {
  8038. ignore = value.split(',');
  8039. }
  8040. else if (key == 'connect')
  8041. {
  8042. edges.push(JSON.parse(value));
  8043. }
  8044. else if (key == 'link')
  8045. {
  8046. link = value;
  8047. }
  8048. else if (key == 'padding')
  8049. {
  8050. padding = parseFloat(value);
  8051. }
  8052. else if (key == 'edgespacing')
  8053. {
  8054. edgespacing = parseFloat(value);
  8055. }
  8056. else if (key == 'nodespacing')
  8057. {
  8058. nodespacing = parseFloat(value);
  8059. }
  8060. else if (key == 'layout')
  8061. {
  8062. layout = value;
  8063. }
  8064. }
  8065. }
  8066. }
  8067. var keys = this.editor.csvToArray(lines[index]);
  8068. // Converts name of identity to index of column
  8069. var identityIndex = null;
  8070. if (identity != null)
  8071. {
  8072. for (var i = 0; i < keys.length; i++)
  8073. {
  8074. if (identity == keys[i])
  8075. {
  8076. identityIndex = i;
  8077. break;
  8078. }
  8079. }
  8080. }
  8081. if (label == null)
  8082. {
  8083. label = '%' + keys[0] + '%';
  8084. }
  8085. if (edges != null)
  8086. {
  8087. for (var e = 0; e < edges.length; e++)
  8088. {
  8089. if (lookups[edges[e].to] == null)
  8090. {
  8091. lookups[edges[e].to] = {};
  8092. }
  8093. }
  8094. }
  8095. graph.model.beginUpdate();
  8096. try
  8097. {
  8098. for (var i = index + 1; i < lines.length; i++)
  8099. {
  8100. var values = this.editor.csvToArray(lines[i]);
  8101. if (values.length == keys.length)
  8102. {
  8103. var cell = null;
  8104. var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
  8105. if (id != null)
  8106. {
  8107. cell = graph.model.getCell(id);
  8108. }
  8109. if (cell == null)
  8110. {
  8111. var cell = new mxCell(label, new mxGeometry(x0, y,
  8112. 0, 0), style || 'whiteSpace=wrap;html=1;');
  8113. cell.vertex = true;
  8114. cell.id = id;
  8115. }
  8116. for (var j = 0; j < values.length; j++)
  8117. {
  8118. graph.setAttributeForCell(cell, keys[j], values[j]);
  8119. }
  8120. graph.setAttributeForCell(cell, 'placeholders', '1');
  8121. cell.style = graph.replacePlaceholders(cell, cell.style);
  8122. for (var e = 0; e < edges.length; e++)
  8123. {
  8124. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  8125. }
  8126. if (link != null && link != 'link')
  8127. {
  8128. graph.setLinkForCell(cell, cell.getAttribute(link));
  8129. // Removes attribute
  8130. graph.setAttributeForCell(cell, link, null);
  8131. }
  8132. // Sets the size
  8133. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
  8134. var size = this.editor.graph.getPreferredSizeForCell(cell);
  8135. if (cell.vertex)
  8136. {
  8137. if (left != null && cell.getAttribute(left) != null)
  8138. {
  8139. cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
  8140. }
  8141. if (top != null && cell.getAttribute(top) != null)
  8142. {
  8143. cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
  8144. }
  8145. if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
  8146. {
  8147. cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
  8148. }
  8149. else
  8150. {
  8151. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  8152. }
  8153. if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
  8154. {
  8155. cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
  8156. }
  8157. else
  8158. {
  8159. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  8160. }
  8161. y += cell.geometry.height + nodespacing;
  8162. }
  8163. cells.push(graph.addCell(cell));
  8164. }
  8165. }
  8166. var roots = cells.slice();
  8167. var select = cells.slice();
  8168. for (var e = 0; e < edges.length; e++)
  8169. {
  8170. var edge = edges[e];
  8171. for (var i = 0; i < cells.length; i++)
  8172. {
  8173. var cell = cells[i];
  8174. var tmp = cell.getAttribute(edge.from);
  8175. if (tmp != null)
  8176. {
  8177. // Removes attribute
  8178. graph.setAttributeForCell(cell, edge.from, null);
  8179. var refs = tmp.split(',');
  8180. for (var j = 0; j < refs.length; j++)
  8181. {
  8182. var ref = lookups[edge.to][refs[j]];
  8183. if (ref != null)
  8184. {
  8185. var label = edge.label;
  8186. if (edge.fromlabel != null)
  8187. {
  8188. label = (cell.getAttribute(edge.fromlabel) || '') + (label || '');
  8189. }
  8190. if (edge.tolabel != null)
  8191. {
  8192. label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
  8193. }
  8194. select.push(graph.insertEdge(null, null, label || '',
  8195. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  8196. edge.style || graph.createCurrentEdgeStyle()));
  8197. mxUtils.remove((edge.invert) ? cell : ref, roots);
  8198. }
  8199. }
  8200. }
  8201. }
  8202. }
  8203. // Removes ignored attributes after processing above
  8204. if (ignore != null)
  8205. {
  8206. for (var i = 0; i < cells.length; i++)
  8207. {
  8208. var cell = cells[i];
  8209. for (var j = 0; j < ignore.length; j++)
  8210. {
  8211. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  8212. }
  8213. }
  8214. }
  8215. var edgeLayout = new mxParallelEdgeLayout(graph);
  8216. edgeLayout.spacing = edgespacing;
  8217. var postProcess = function()
  8218. {
  8219. edgeLayout.execute(graph.getDefaultParent());
  8220. // Aligns cells to grid and/or rounds positions
  8221. for (var i = 0; i < cells.length; i++)
  8222. {
  8223. var geo = graph.getCellGeometry(cells[i]);
  8224. geo.x = Math.round(graph.snap(geo.x));
  8225. geo.y = Math.round(graph.snap(geo.y));
  8226. if (width == 'auto')
  8227. {
  8228. geo.width = Math.round(graph.snap(geo.width));
  8229. }
  8230. if (height == 'auto')
  8231. {
  8232. geo.height = Math.round(graph.snap(geo.height));
  8233. }
  8234. }
  8235. };
  8236. if (layout == 'circle')
  8237. {
  8238. var circleLayout = new mxCircleLayout(graph);
  8239. circleLayout.resetEdges = false;
  8240. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  8241. // Ignore other cells
  8242. circleLayout.isVertexIgnored = function(vertex)
  8243. {
  8244. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  8245. mxUtils.indexOf(cells, vertex) < 0;
  8246. };
  8247. this.executeLayout(function()
  8248. {
  8249. circleLayout.execute(graph.getDefaultParent());
  8250. postProcess();
  8251. }, true, afterInsert);
  8252. afterInsert = null;
  8253. }
  8254. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  8255. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  8256. {
  8257. // Required for layouts to work with new cells
  8258. graph.view.validate();
  8259. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  8260. treeLayout.levelDistance = nodespacing;
  8261. treeLayout.edgeRouting = false;
  8262. treeLayout.resetEdges = false;
  8263. this.executeLayout(function()
  8264. {
  8265. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  8266. }, true, afterInsert);
  8267. afterInsert = null;
  8268. }
  8269. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  8270. (layout == 'auto' && roots.length == 1))
  8271. {
  8272. // Required for layouts to work with new cells
  8273. graph.view.validate();
  8274. var flowLayout = new mxHierarchicalLayout(graph,
  8275. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  8276. flowLayout.intraCellSpacing = nodespacing;
  8277. flowLayout.disableEdgeStyle = false;
  8278. this.executeLayout(function()
  8279. {
  8280. flowLayout.execute(graph.getDefaultParent(), select);
  8281. // Workaround for flow layout moving cells to origin
  8282. graph.moveCells(select, x0, y0);
  8283. }, true, afterInsert);
  8284. afterInsert = null;
  8285. }
  8286. else if (layout == 'organic' || (layout == 'auto' &&
  8287. select.length > cells.length))
  8288. {
  8289. // Required for layouts to work with new cells
  8290. graph.view.validate();
  8291. var organicLayout = new mxFastOrganicLayout(graph);
  8292. organicLayout.forceConstant = nodespacing * 3;
  8293. organicLayout.resetEdges = false;
  8294. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  8295. // Ignore other cells
  8296. organicLayout.isVertexIgnored = function(vertex)
  8297. {
  8298. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  8299. mxUtils.indexOf(cells, vertex) < 0;
  8300. };
  8301. var edgeLayout = new mxParallelEdgeLayout(graph);
  8302. edgeLayout.spacing = edgespacing;
  8303. this.executeLayout(function()
  8304. {
  8305. organicLayout.execute(graph.getDefaultParent());
  8306. postProcess();
  8307. }, true, afterInsert);
  8308. afterInsert = null;
  8309. }
  8310. this.hideDialog();
  8311. }
  8312. finally
  8313. {
  8314. graph.model.endUpdate();
  8315. }
  8316. if (afterInsert != null)
  8317. {
  8318. afterInsert();
  8319. }
  8320. }
  8321. }
  8322. catch (e)
  8323. {
  8324. this.handleError(e);
  8325. }
  8326. };
  8327. /**
  8328. * Translates this point by the given vector.
  8329. *
  8330. * @param {number} dx X-coordinate of the translation.
  8331. * @param {number} dy Y-coordinate of the translation.
  8332. */
  8333. EditorUi.prototype.getSearch = function(exclude)
  8334. {
  8335. var result = '';
  8336. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  8337. {
  8338. var amp = '?';
  8339. for (var key in urlParams)
  8340. {
  8341. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  8342. {
  8343. result += amp + key + '=' + urlParams[key];
  8344. amp = '&';
  8345. }
  8346. }
  8347. }
  8348. else
  8349. {
  8350. result = window.location.search;
  8351. }
  8352. return result;
  8353. };
  8354. /**
  8355. * Returns the URL for a copy of this editor with no state.
  8356. */
  8357. EditorUi.prototype.getUrl = function(pathname)
  8358. {
  8359. var href = (pathname != null) ? pathname : window.location.pathname;
  8360. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  8361. if (urlParams['offline'] == '1')
  8362. {
  8363. href += window.location.search;
  8364. }
  8365. else
  8366. {
  8367. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  8368. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  8369. // Removes template URL parameter for new blank diagram
  8370. for (var key in urlParams)
  8371. {
  8372. if (mxUtils.indexOf(ignored, key) < 0)
  8373. {
  8374. if (parms == 0)
  8375. {
  8376. href += '?';
  8377. }
  8378. else
  8379. {
  8380. href += '&';
  8381. }
  8382. if (urlParams[key] != null)
  8383. {
  8384. href += key + '=' + urlParams[key];
  8385. parms++;
  8386. }
  8387. }
  8388. }
  8389. }
  8390. return href;
  8391. };
  8392. /**
  8393. * Overrides link dialog.
  8394. */
  8395. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  8396. {
  8397. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  8398. this.showDialog(dlg.container, 440, 130, true, true);
  8399. dlg.init();
  8400. };
  8401. /**
  8402. * Overrides createOutline
  8403. */
  8404. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  8405. EditorUi.prototype.createOutline = function(wnd)
  8406. {
  8407. var outline = editorUiCreateOutline.apply(this, arguments);
  8408. var graph = this.editor.graph;
  8409. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  8410. outline.getSourceGraphBounds = function()
  8411. {
  8412. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  8413. {
  8414. var pb = this.source.getPagePadding();
  8415. var s = this.source.view.scale;
  8416. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  8417. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  8418. return result;
  8419. }
  8420. return outlineGetSourceGraphBounds.apply(this, arguments);
  8421. };
  8422. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  8423. outline.getSourceContainerSize = function()
  8424. {
  8425. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  8426. {
  8427. var pad = this.source.getPagePadding();
  8428. var s = this.source.view.scale;
  8429. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  8430. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  8431. }
  8432. return outlineGetSourceContainerSize.apply(this, arguments);
  8433. };
  8434. outline.getOutlineOffset = function(scale)
  8435. {
  8436. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  8437. {
  8438. var pb = this.source.getPagePadding();
  8439. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  8440. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  8441. // Why is vertical offset negative relative to dy
  8442. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  8443. }
  8444. return new mxPoint(8 / scale, 8 / scale);
  8445. };
  8446. var outlineInit = outline.init;
  8447. outline.init = function()
  8448. {
  8449. outlineInit.apply(this, arguments);
  8450. // Problem: Need to override a function in the view but the view is created
  8451. // with the graph so a refresh of the page is needed to see this change.
  8452. outline.outline.view.getBackgroundPageBounds = function()
  8453. {
  8454. var layout = graph.getPageLayout();
  8455. var page = graph.getPageSize();
  8456. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  8457. this.scale * (this.translate.y + layout.y * page.height),
  8458. this.scale * layout.width * page.width,
  8459. this.scale * layout.height * page.height);
  8460. };
  8461. outline.outline.view.validateBackgroundPage();
  8462. };
  8463. this.editor.addListener('pageSelected', function(sender, evt)
  8464. {
  8465. var change = evt.getProperty('change');
  8466. var graph = outline.source;
  8467. var g = outline.outline;
  8468. g.pageScale = graph.pageScale;
  8469. g.pageFormat = graph.pageFormat;
  8470. g.background = graph.background;
  8471. g.pageVisible = graph.pageVisible;
  8472. g.background = graph.background;
  8473. var current = mxUtils.getCurrentStyle(graph.container);
  8474. g.container.style.backgroundColor = current.backgroundColor;
  8475. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  8476. {
  8477. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  8478. }
  8479. outline.outline.view.clear(change.previousPage.root, true);
  8480. outline.outline.view.validate();
  8481. });
  8482. return outline;
  8483. };
  8484. /**
  8485. * Returns the number of storage options enabled
  8486. */
  8487. EditorUi.prototype.getServiceCount = function(allowBrowser, splash)
  8488. {
  8489. var serviceCount = 0;
  8490. if (this.drive != null || typeof window.DriveClient === 'function')
  8491. {
  8492. serviceCount++
  8493. }
  8494. if (!splash && (this.dropbox != null || typeof window.DropboxClient === 'function'))
  8495. {
  8496. serviceCount++
  8497. }
  8498. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  8499. {
  8500. serviceCount++
  8501. }
  8502. if (!splash && (this.gitHub != null))
  8503. {
  8504. serviceCount++
  8505. }
  8506. if (!splash && (this.trello != null || typeof window.TrelloClient === 'function'))
  8507. {
  8508. serviceCount++
  8509. }
  8510. if (allowBrowser && isLocalStorage && (urlParams['browser'] == '1' || mxClient.IS_IOS))
  8511. {
  8512. serviceCount++
  8513. }
  8514. if (!mxClient.IS_IOS)
  8515. {
  8516. serviceCount++
  8517. }
  8518. return serviceCount;
  8519. }
  8520. /**
  8521. * Updates action and menu states depending on the file.
  8522. */
  8523. EditorUi.prototype.updateUi = function()
  8524. {
  8525. this.updateButtonContainer();
  8526. this.updateActionStates();
  8527. // Action states that only need update for new files
  8528. var file = this.getCurrentFile();
  8529. var active = file != null || (urlParams['embed'] == '1' &&
  8530. this.editor.graph.isEnabled());
  8531. this.menus.get('viewPanels').setEnabled(active);
  8532. this.menus.get('viewZoom').setEnabled(active);
  8533. var restricted = (urlParams['embed'] != '1' ||
  8534. !this.editor.graph.isEnabled()) &&
  8535. (file == null || file.isRestricted());
  8536. this.actions.get('makeCopy').setEnabled(!restricted);
  8537. this.actions.get('print').setEnabled(!restricted);
  8538. this.menus.get('exportAs').setEnabled(!restricted);
  8539. this.menus.get('embed').setEnabled(!restricted);
  8540. // Disables libraries and extras menu in embed mode
  8541. // while waiting for file data
  8542. var libsEnabled = urlParams['embed'] != '1' ||
  8543. this.editor.graph.isEnabled();
  8544. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  8545. this.menus.get('newLibrary').setEnabled(libsEnabled);
  8546. this.menus.get('extras').setEnabled(libsEnabled);
  8547. // Disables actions in the toolbar
  8548. var editable = (urlParams['embed'] == '1' &&
  8549. this.editor.graph.isEnabled()) ||
  8550. (file != null && file.isEditable());
  8551. this.actions.get('image').setEnabled(active);
  8552. this.actions.get('zoomIn').setEnabled(active);
  8553. this.actions.get('zoomOut').setEnabled(active);
  8554. this.actions.get('resetView').setEnabled(active);
  8555. // Disables menus
  8556. this.menus.get('edit').setEnabled(active);
  8557. this.menus.get('view').setEnabled(active);
  8558. this.menus.get('importFrom').setEnabled(editable);
  8559. this.menus.get('arrange').setEnabled(editable);
  8560. // Disables connection drop downs in toolbar
  8561. if (this.toolbar != null)
  8562. {
  8563. if (this.toolbar.edgeShapeMenu != null)
  8564. {
  8565. this.toolbar.edgeShapeMenu.setEnabled(editable);
  8566. }
  8567. if (this.toolbar.edgeStyleMenu != null)
  8568. {
  8569. this.toolbar.edgeStyleMenu.setEnabled(editable);
  8570. }
  8571. }
  8572. if (this.isAppCache())
  8573. {
  8574. var appCache = applicationCache;
  8575. // NOTE: HTML5 Cache is deprecated
  8576. if (appCache != null && this.offlineStatus == null)
  8577. {
  8578. this.offlineStatus = document.createElement('div');
  8579. this.offlineStatus.className = 'geItem';
  8580. this.offlineStatus.style.position = 'absolute';
  8581. this.offlineStatus.style.fontSize = '8pt';
  8582. this.offlineStatus.style.top = '2px';
  8583. this.offlineStatus.style.right = '12px';
  8584. this.offlineStatus.style.color = '#666';
  8585. this.offlineStatus.style.margin = '4px';
  8586. this.offlineStatus.style.padding = '2px';
  8587. this.offlineStatus.style.verticalAlign = 'middle';
  8588. this.offlineStatus.innerHTML = '';
  8589. this.menubarContainer.appendChild(this.offlineStatus);
  8590. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  8591. {
  8592. var img = this.offlineStatus.getElementsByTagName('img');
  8593. if (img != null && img.length > 0)
  8594. {
  8595. this.alert(img[0].getAttribute('title'));
  8596. }
  8597. }));
  8598. var appCache = window.applicationCache;
  8599. var lastStatus = null;
  8600. var updateStatus = mxUtils.bind(this, function()
  8601. {
  8602. var newStatus = appCache.status;
  8603. var html = '';
  8604. if (newStatus == appCache.CHECKING)
  8605. {
  8606. newStatus = appCache.DOWNLOADING;
  8607. }
  8608. switch (newStatus)
  8609. {
  8610. case appCache.UNCACHED: // UNCACHED == 0
  8611. html = '';
  8612. break;
  8613. case appCache.IDLE: // IDLE == 1
  8614. html = (uiTheme == 'min') ? '' : '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  8615. break;
  8616. case appCache.DOWNLOADING: // DOWNLOADING == 3
  8617. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  8618. break;
  8619. case appCache.UPDATEREADY: // UPDATEREADY == 4
  8620. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  8621. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  8622. break;
  8623. case appCache.OBSOLETE: // OBSOLETE == 5
  8624. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  8625. break;
  8626. default:
  8627. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  8628. break;
  8629. }
  8630. if (newStatus != lastStatus)
  8631. {
  8632. this.offlineStatus.innerHTML = html;
  8633. lastStatus = newStatus;
  8634. }
  8635. });
  8636. mxEvent.addListener(appCache, 'checking', updateStatus);
  8637. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  8638. mxEvent.addListener(appCache, 'downloading', updateStatus);
  8639. mxEvent.addListener(appCache, 'progress', updateStatus);
  8640. mxEvent.addListener(appCache, 'cached', updateStatus);
  8641. mxEvent.addListener(appCache, 'updateready', updateStatus);
  8642. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  8643. mxEvent.addListener(appCache, 'error', updateStatus);
  8644. updateStatus();
  8645. }
  8646. }
  8647. else
  8648. {
  8649. this.updateUserElement();
  8650. }
  8651. };
  8652. /**
  8653. * Hook for subclassers
  8654. */
  8655. EditorUi.prototype.updateButtonContainer = function()
  8656. {
  8657. // do nothing
  8658. };
  8659. /**
  8660. * Hook for subclassers
  8661. */
  8662. EditorUi.prototype.updateUserElement = function()
  8663. {
  8664. // do nothing
  8665. };
  8666. /**
  8667. * Returns true if a diagram is cative and editable.
  8668. */
  8669. EditorUi.prototype.isDiagramActive = function()
  8670. {
  8671. var file = this.getCurrentFile();
  8672. return (file != null && file.isEditable()) ||
  8673. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  8674. };
  8675. /**
  8676. * Updates action states depending on the selection.
  8677. */
  8678. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  8679. EditorUi.prototype.updateActionStates = function()
  8680. {
  8681. editorUiUpdateActionStates.apply(this, arguments);
  8682. var graph = this.editor.graph;
  8683. var active = this.isDiagramActive();
  8684. var file = this.getCurrentFile();
  8685. this.actions.get('pageSetup').setEnabled(active);
  8686. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  8687. this.actions.get('guides').setEnabled(active);
  8688. this.actions.get('editData').setEnabled(active);
  8689. this.actions.get('shadowVisible').setEnabled(active);
  8690. this.actions.get('connectionArrows').setEnabled(active);
  8691. this.actions.get('connectionPoints').setEnabled(active);
  8692. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  8693. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  8694. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  8695. this.actions.get('createShape').setEnabled(active);
  8696. this.actions.get('createRevision').setEnabled(active);
  8697. this.actions.get('moveToFolder').setEnabled(file != null);
  8698. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  8699. this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
  8700. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  8701. this.actions.get('tags').setEnabled(active && (file == null || !file.isRestricted()));
  8702. this.actions.get('rename').setEnabled(file != null && file.isRenamable());
  8703. this.actions.get('close').setEnabled(file != null);
  8704. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  8705. var state = graph.view.getState(graph.getSelectionCell());
  8706. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  8707. };
  8708. /**
  8709. * Overridden to remove export dialog in chromeless lightbox.
  8710. */
  8711. var editoUiDestroy = EditorUi.prototype.destroy;
  8712. EditorUi.prototype.destroy = function()
  8713. {
  8714. if (this.exportDialog != null)
  8715. {
  8716. this.exportDialog.parentNode.removeChild(this.exportDialog);
  8717. this.exportDialog = null;
  8718. }
  8719. editoUiDestroy.apply(this, arguments);
  8720. };
  8721. /**
  8722. * Overrides export dialog for using ui functions for save and setting global switches.
  8723. */
  8724. if (window.ExportDialog != null)
  8725. {
  8726. ExportDialog.showXmlOption = false;
  8727. ExportDialog.showGifOption = false;
  8728. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  8729. {
  8730. var graph = editorUi.editor.graph;
  8731. if (format == 'xml')
  8732. {
  8733. editorUi.hideDialog();
  8734. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  8735. }
  8736. else if (format == 'svg')
  8737. {
  8738. editorUi.hideDialog();
  8739. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  8740. }
  8741. else
  8742. {
  8743. var data = editorUi.getFileData(true, null, null, null, null, true);
  8744. var bounds = graph.getGraphBounds();
  8745. var w = Math.floor(bounds.width * s / graph.view.scale);
  8746. var h = Math.floor(bounds.height * s / graph.view.scale);
  8747. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  8748. {
  8749. editorUi.hideDialog();
  8750. editorUi.saveRequest(name, format,
  8751. function(newTitle, base64)
  8752. {
  8753. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  8754. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  8755. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  8756. '&border=' + b + '&xml=' + encodeURIComponent(data));
  8757. });
  8758. }
  8759. else
  8760. {
  8761. mxUtils.alert(mxResources.get('drawingTooLarge'));
  8762. }
  8763. }
  8764. };
  8765. }
  8766. })();