EditorUi.js 265 KB

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