EditorUi.js 267 KB

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