EditorUi.js 259 KB

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