EditorUi.js 222 KB

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