EditorUi.js 266 KB

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