EditorUi.js 236 KB

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