EditorUi.js 247 KB

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