EditorUi.js 263 KB

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