EditorUi.js 239 KB

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