EditorUi.js 233 KB

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