EditorUi.js 252 KB

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