EditorUi.js 311 KB

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