EditorUi.js 227 KB

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