You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Escalator.java 269KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.v7.client.widgets;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.ListIterator;
  25. import java.util.Map;
  26. import java.util.Map.Entry;
  27. import java.util.TreeMap;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. import com.google.gwt.animation.client.Animation;
  31. import com.google.gwt.animation.client.AnimationScheduler;
  32. import com.google.gwt.animation.client.AnimationScheduler.AnimationCallback;
  33. import com.google.gwt.animation.client.AnimationScheduler.AnimationHandle;
  34. import com.google.gwt.core.client.Duration;
  35. import com.google.gwt.core.client.JavaScriptObject;
  36. import com.google.gwt.core.client.JsArray;
  37. import com.google.gwt.core.client.Scheduler;
  38. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  39. import com.google.gwt.dom.client.DivElement;
  40. import com.google.gwt.dom.client.Document;
  41. import com.google.gwt.dom.client.Element;
  42. import com.google.gwt.dom.client.NativeEvent;
  43. import com.google.gwt.dom.client.Node;
  44. import com.google.gwt.dom.client.NodeList;
  45. import com.google.gwt.dom.client.Style;
  46. import com.google.gwt.dom.client.Style.Display;
  47. import com.google.gwt.dom.client.Style.Unit;
  48. import com.google.gwt.dom.client.TableCellElement;
  49. import com.google.gwt.dom.client.TableRowElement;
  50. import com.google.gwt.dom.client.TableSectionElement;
  51. import com.google.gwt.dom.client.Touch;
  52. import com.google.gwt.event.shared.HandlerRegistration;
  53. import com.google.gwt.logging.client.LogConfiguration;
  54. import com.google.gwt.user.client.Command;
  55. import com.google.gwt.user.client.DOM;
  56. import com.google.gwt.user.client.Window;
  57. import com.google.gwt.user.client.ui.RequiresResize;
  58. import com.google.gwt.user.client.ui.RootPanel;
  59. import com.google.gwt.user.client.ui.UIObject;
  60. import com.google.gwt.user.client.ui.Widget;
  61. import com.vaadin.client.BrowserInfo;
  62. import com.vaadin.client.DeferredWorker;
  63. import com.vaadin.client.Profiler;
  64. import com.vaadin.client.WidgetUtil;
  65. import com.vaadin.client.ui.SubPartAware;
  66. import com.vaadin.shared.Range;
  67. import com.vaadin.shared.util.SharedUtil;
  68. import com.vaadin.v7.client.widget.escalator.Cell;
  69. import com.vaadin.v7.client.widget.escalator.ColumnConfiguration;
  70. import com.vaadin.v7.client.widget.escalator.EscalatorUpdater;
  71. import com.vaadin.v7.client.widget.escalator.FlyweightCell;
  72. import com.vaadin.v7.client.widget.escalator.FlyweightRow;
  73. import com.vaadin.v7.client.widget.escalator.PositionFunction;
  74. import com.vaadin.v7.client.widget.escalator.PositionFunction.AbsolutePosition;
  75. import com.vaadin.v7.client.widget.escalator.PositionFunction.Translate3DPosition;
  76. import com.vaadin.v7.client.widget.escalator.PositionFunction.TranslatePosition;
  77. import com.vaadin.v7.client.widget.escalator.PositionFunction.WebkitTranslate3DPosition;
  78. import com.vaadin.v7.client.widget.escalator.Row;
  79. import com.vaadin.v7.client.widget.escalator.RowContainer;
  80. import com.vaadin.v7.client.widget.escalator.RowContainer.BodyRowContainer;
  81. import com.vaadin.v7.client.widget.escalator.RowVisibilityChangeEvent;
  82. import com.vaadin.v7.client.widget.escalator.RowVisibilityChangeHandler;
  83. import com.vaadin.v7.client.widget.escalator.ScrollbarBundle;
  84. import com.vaadin.v7.client.widget.escalator.ScrollbarBundle.HorizontalScrollbarBundle;
  85. import com.vaadin.v7.client.widget.escalator.ScrollbarBundle.VerticalScrollbarBundle;
  86. import com.vaadin.v7.client.widget.escalator.Spacer;
  87. import com.vaadin.v7.client.widget.escalator.SpacerUpdater;
  88. import com.vaadin.v7.client.widget.escalator.events.RowHeightChangedEvent;
  89. import com.vaadin.v7.client.widget.grid.events.ScrollEvent;
  90. import com.vaadin.v7.client.widget.grid.events.ScrollHandler;
  91. import com.vaadin.v7.client.widgets.Escalator.JsniUtil.TouchHandlerBundle;
  92. import com.vaadin.v7.shared.ui.grid.HeightMode;
  93. import com.vaadin.v7.shared.ui.grid.ScrollDestination;
  94. /*-
  95. Maintenance Notes! Reading these might save your day.
  96. (note for editors: line width is 80 chars, including the
  97. one-space indentation)
  98. == Row Container Structure
  99. AbstractRowContainer
  100. |-- AbstractStaticRowContainer
  101. | |-- HeaderRowContainer
  102. | `-- FooterContainer
  103. `---- BodyRowContainerImpl
  104. AbstractRowContainer is intended to contain all common logic
  105. between RowContainers. It manages the bookkeeping of row
  106. count, makes sure that all individual cells are rendered
  107. the same way, and so on.
  108. AbstractStaticRowContainer has some special logic that is
  109. required by all RowContainers that don't scroll (hence the
  110. word "static"). HeaderRowContainer and FooterRowContainer
  111. are pretty thin special cases of a StaticRowContainer
  112. (mostly relating to positioning of the root element).
  113. BodyRowContainerImpl could also be split into an additional
  114. "AbstractScrollingRowContainer", but I felt that no more
  115. inner classes were needed. So it contains both logic
  116. required for making things scroll about, and equivalent
  117. special cases for layouting, as are found in
  118. Header/FooterRowContainers.
  119. == The Three Indices
  120. Each RowContainer can be thought to have three levels of
  121. indices for any given displayed row (but the distinction
  122. matters primarily for the BodyRowContainerImpl, because of
  123. the way it scrolls through data):
  124. - Logical index
  125. - Physical (or DOM) index
  126. - Visual index
  127. LOGICAL INDEX is the index that is linked to the data
  128. source. If you want your data source to represent a SQL
  129. database with 10 000 rows, the 7 000:th row in the SQL has a
  130. logical index of 6 999, since the index is 0-based (unless
  131. that data source does some funky logic).
  132. PHYSICAL INDEX is the index for a row that you see in a
  133. browser's DOM inspector. If your row is the second <tr>
  134. element within a <tbody> tag, it has a physical index of 1
  135. (because of 0-based indices). In Header and
  136. FooterRowContainers, you are safe to assume that the logical
  137. index is the same as the physical index. But because the
  138. BodyRowContainerImpl never displays large data sources
  139. entirely in the DOM, a physical index usually has no
  140. apparent direct relationship with its logical index.
  141. VISUAL INDEX is the index relating to the order that you
  142. see a row in, in the browser, as it is rendered. The
  143. topmost row is 0, the second is 1, and so on. The visual
  144. index is similar to the physical index in the sense that
  145. Header and FooterRowContainers can assume a 1:1
  146. relationship between visual index and logical index. And
  147. again, BodyRowContainerImpl has no such relationship. The
  148. body's visual index has additionally no apparent
  149. relationship with its physical index. Because the <tr> tags
  150. are reused in the body and visually repositioned with CSS
  151. as the user scrolls, the relationship between physical
  152. index and visual index is quickly broken. You can get an
  153. element's visual index via the field
  154. BodyRowContainerImpl.visualRowOrder.
  155. Currently, the physical and visual indices are kept in sync
  156. _most of the time_ by a deferred rearrangement of rows.
  157. They become desynced when scrolling. This is to help screen
  158. readers to read the contents from the DOM in a natural
  159. order. See BodyRowContainerImpl.DeferredDomSorter for more
  160. about that.
  161. */
  162. /**
  163. * A workaround-class for GWT and JSNI.
  164. * <p>
  165. * GWT is unable to handle some method calls to Java methods in inner-classes
  166. * from within JSNI blocks. Having that inner class extend a non-inner-class (or
  167. * implement such an interface), makes it possible for JSNI to indirectly refer
  168. * to the inner class, by invoking methods and fields in the non-inner-class
  169. * API.
  170. *
  171. * @see Escalator.Scroller
  172. */
  173. abstract class JsniWorkaround {
  174. /**
  175. * A JavaScript function that handles the scroll DOM event, and passes it on
  176. * to Java code.
  177. *
  178. * @see #createScrollListenerFunction(Escalator)
  179. * @see Escalator#onScroll()
  180. * @see Escalator.Scroller#onScroll()
  181. */
  182. protected final JavaScriptObject scrollListenerFunction;
  183. /**
  184. * A JavaScript function that handles the mousewheel DOM event, and passes
  185. * it on to Java code.
  186. *
  187. * @see #createMousewheelListenerFunction(Escalator)
  188. * @see Escalator#onScroll()
  189. * @see Escalator.Scroller#onScroll()
  190. */
  191. protected final JavaScriptObject mousewheelListenerFunction;
  192. /**
  193. * A JavaScript function that handles the touch start DOM event, and passes
  194. * it on to Java code.
  195. *
  196. * @see TouchHandlerBundle#touchStart(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  197. */
  198. protected JavaScriptObject touchStartFunction;
  199. /**
  200. * A JavaScript function that handles the touch move DOM event, and passes
  201. * it on to Java code.
  202. *
  203. * @see TouchHandlerBundle#touchMove(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  204. */
  205. protected JavaScriptObject touchMoveFunction;
  206. /**
  207. * A JavaScript function that handles the touch end and cancel DOM events,
  208. * and passes them on to Java code.
  209. *
  210. * @see TouchHandlerBundle#touchEnd(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  211. */
  212. protected JavaScriptObject touchEndFunction;
  213. protected TouchHandlerBundle touchHandlerBundle;
  214. protected JsniWorkaround(final Escalator escalator) {
  215. scrollListenerFunction = createScrollListenerFunction(escalator);
  216. mousewheelListenerFunction = createMousewheelListenerFunction(
  217. escalator);
  218. touchHandlerBundle = new TouchHandlerBundle(escalator);
  219. touchStartFunction = touchHandlerBundle.getTouchStartHandler();
  220. touchMoveFunction = touchHandlerBundle.getTouchMoveHandler();
  221. touchEndFunction = touchHandlerBundle.getTouchEndHandler();
  222. }
  223. /**
  224. * A method that constructs the JavaScript function that will be stored into
  225. * {@link #scrollListenerFunction}.
  226. *
  227. * @param esc
  228. * a reference to the current instance of {@link Escalator}
  229. * @see Escalator#onScroll()
  230. */
  231. protected abstract JavaScriptObject createScrollListenerFunction(
  232. Escalator esc);
  233. /**
  234. * A method that constructs the JavaScript function that will be stored into
  235. * {@link #mousewheelListenerFunction}.
  236. *
  237. * @param esc
  238. * a reference to the current instance of {@link Escalator}
  239. * @see Escalator#onScroll()
  240. */
  241. protected abstract JavaScriptObject createMousewheelListenerFunction(
  242. Escalator esc);
  243. }
  244. /**
  245. * A low-level table-like widget that features a scrolling virtual viewport and
  246. * lazily generated rows.
  247. *
  248. * @since 7.4
  249. * @author Vaadin Ltd
  250. */
  251. public class Escalator extends Widget
  252. implements RequiresResize, DeferredWorker, SubPartAware {
  253. // todo comments legend
  254. /*
  255. * [[optimize]]: There's an opportunity to rewrite the code in such a way
  256. * that it _might_ perform better (remember to measure, implement,
  257. * re-measure)
  258. */
  259. /*
  260. * [[mpixscroll]]: This code will require alterations that are relevant for
  261. * supporting the scrolling through more pixels than some browsers normally
  262. * would support. (i.e. when we support more than "a million" pixels in the
  263. * escalator DOM). NOTE: these bits can most often also be identified by
  264. * searching for code that call scrollElem.getScrollTop();.
  265. */
  266. /*
  267. * [[spacer]]: Code that is important to make spacers work.
  268. */
  269. /**
  270. * A utility class that contains utility methods that are usually called
  271. * from JSNI.
  272. * <p>
  273. * The methods are moved in this class to minimize the amount of JSNI code
  274. * as much as feasible.
  275. */
  276. static class JsniUtil {
  277. public static class TouchHandlerBundle {
  278. public static final String POINTER_EVENT_TYPE_TOUCH = "touch";
  279. /**
  280. * A <a href=
  281. * "http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html"
  282. * >JavaScriptObject overlay</a> for the
  283. * <a href="http://www.w3.org/TR/touch-events/">JavaScript
  284. * TouchEvent</a> object.
  285. * <p>
  286. * This needs to be used in the touch event handlers, since GWT's
  287. * {@link com.google.gwt.event.dom.client.TouchEvent TouchEvent}
  288. * can't be cast from the JSNI call, and the
  289. * {@link com.google.gwt.dom.client.NativeEvent NativeEvent} isn't
  290. * properly populated with the correct values.
  291. */
  292. private static final class CustomTouchEvent
  293. extends JavaScriptObject {
  294. protected CustomTouchEvent() {
  295. }
  296. public native NativeEvent getNativeEvent()
  297. /*-{
  298. return this;
  299. }-*/;
  300. public native int getPageX()
  301. /*-{
  302. return this.targetTouches[0].pageX;
  303. }-*/;
  304. public native int getPageY()
  305. /*-{
  306. return this.targetTouches[0].pageY;
  307. }-*/;
  308. public native String getPointerType()
  309. /*-{
  310. return this.pointerType;
  311. }-*/;
  312. }
  313. private final Escalator escalator;
  314. public TouchHandlerBundle(final Escalator escalator) {
  315. this.escalator = escalator;
  316. }
  317. public native JavaScriptObject getTouchStartHandler()
  318. /*-{
  319. // we need to store "this", since it won't be preserved on call.
  320. var self = this;
  321. return $entry(function (e) {
  322. self.@com.vaadin.v7.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchStart(*)(e);
  323. });
  324. }-*/;
  325. public native JavaScriptObject getTouchMoveHandler()
  326. /*-{
  327. // we need to store "this", since it won't be preserved on call.
  328. var self = this;
  329. return $entry(function (e) {
  330. self.@com.vaadin.v7.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchMove(*)(e);
  331. });
  332. }-*/;
  333. public native JavaScriptObject getTouchEndHandler()
  334. /*-{
  335. // we need to store "this", since it won't be preserved on call.
  336. var self = this;
  337. return $entry(function (e) {
  338. self.@com.vaadin.v7.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchEnd(*)(e);
  339. });
  340. }-*/;
  341. // Duration of the inertial scrolling simulation. Devices with
  342. // larger screens take longer durations.
  343. private static final int DURATION = Window.getClientHeight();
  344. // multiply scroll velocity with repeated touching
  345. private int acceleration = 1;
  346. private boolean touching = false;
  347. // Two movement objects for storing status and processing touches
  348. private Movement yMov, xMov;
  349. static final double MIN_VEL = 0.6, MAX_VEL = 4, F_VEL = 1500,
  350. F_ACC = 0.7,
  351. F_AXIS = 1;
  352. // The object to deal with one direction scrolling
  353. private class Movement {
  354. final List<Double> speeds = new ArrayList<Double>();
  355. final ScrollbarBundle scroll;
  356. double position, offset, velocity, prevPos, prevTime, delta;
  357. boolean run, vertical;
  358. public Movement(boolean vertical) {
  359. this.vertical = vertical;
  360. scroll = vertical ? escalator.verticalScrollbar
  361. : escalator.horizontalScrollbar;
  362. }
  363. public void startTouch(CustomTouchEvent event) {
  364. speeds.clear();
  365. prevPos = pagePosition(event);
  366. prevTime = Duration.currentTimeMillis();
  367. }
  368. public void moveTouch(CustomTouchEvent event) {
  369. double pagePosition = pagePosition(event);
  370. if (pagePosition > -1) {
  371. delta = prevPos - pagePosition;
  372. double now = Duration.currentTimeMillis();
  373. double ellapsed = now - prevTime;
  374. velocity = delta / ellapsed;
  375. // if last speed was so low, reset speeds and start
  376. // storing again
  377. if (!speeds.isEmpty() && !validSpeed(speeds.get(0))) {
  378. speeds.clear();
  379. run = true;
  380. }
  381. speeds.add(0, velocity);
  382. prevTime = now;
  383. prevPos = pagePosition;
  384. }
  385. }
  386. public void endTouch(CustomTouchEvent event) {
  387. // Compute average speed
  388. velocity = 0;
  389. for (double s : speeds) {
  390. velocity += s / speeds.size();
  391. }
  392. position = scroll.getScrollPos();
  393. // Compute offset, and adjust it with an easing curve so as
  394. // movement is smoother.
  395. offset = F_VEL * velocity * acceleration
  396. * easingInOutCos(velocity, MAX_VEL);
  397. // Enable or disable inertia movement in this axis
  398. run = validSpeed(velocity);
  399. if (run) {
  400. event.getNativeEvent().preventDefault();
  401. }
  402. }
  403. void validate(Movement other) {
  404. if (!run || other.velocity > 0
  405. && Math.abs(velocity / other.velocity) < F_AXIS) {
  406. delta = offset = 0;
  407. run = false;
  408. }
  409. }
  410. void stepAnimation(double progress) {
  411. scroll.setScrollPos(position + offset * progress);
  412. }
  413. int pagePosition(CustomTouchEvent event) {
  414. // Use native event's screen x and y for IE11 and Edge
  415. // since there is no touches for these browsers (#18737)
  416. if (isCurrentBrowserIE11OrEdge()) {
  417. return vertical
  418. ? event.getNativeEvent().getClientY()
  419. + Window.getScrollTop()
  420. : event.getNativeEvent().getClientX()
  421. + Window.getScrollLeft();
  422. }
  423. JsArray<Touch> a = event.getNativeEvent().getTouches();
  424. return vertical ? a.get(0).getPageY() : a.get(0).getPageX();
  425. }
  426. boolean validSpeed(double speed) {
  427. return Math.abs(speed) > MIN_VEL;
  428. }
  429. }
  430. // Using GWT animations which take care of native animation frames.
  431. private Animation animation = new Animation() {
  432. @Override
  433. public void onUpdate(double progress) {
  434. xMov.stepAnimation(progress);
  435. yMov.stepAnimation(progress);
  436. }
  437. @Override
  438. public double interpolate(double progress) {
  439. return easingOutCirc(progress);
  440. };
  441. @Override
  442. public void onComplete() {
  443. touching = false;
  444. escalator.body.domSorter.reschedule();
  445. };
  446. @Override
  447. public void run(int duration) {
  448. if (xMov.run || yMov.run) {
  449. super.run(duration);
  450. } else {
  451. onComplete();
  452. }
  453. };
  454. };
  455. public void touchStart(final CustomTouchEvent event) {
  456. if (allowTouch(event)) {
  457. if (yMov == null) {
  458. yMov = new Movement(true);
  459. xMov = new Movement(false);
  460. }
  461. if (animation.isRunning()) {
  462. acceleration += F_ACC;
  463. event.getNativeEvent().preventDefault();
  464. animation.cancel();
  465. } else {
  466. acceleration = 1;
  467. }
  468. xMov.startTouch(event);
  469. yMov.startTouch(event);
  470. touching = true;
  471. } else {
  472. touching = false;
  473. animation.cancel();
  474. acceleration = 1;
  475. }
  476. }
  477. public void touchMove(final CustomTouchEvent event) {
  478. if (touching) {
  479. xMov.moveTouch(event);
  480. yMov.moveTouch(event);
  481. xMov.validate(yMov);
  482. yMov.validate(xMov);
  483. event.getNativeEvent().preventDefault();
  484. moveScrollFromEvent(escalator, xMov.delta, yMov.delta,
  485. event.getNativeEvent());
  486. }
  487. }
  488. public void touchEnd(final CustomTouchEvent event) {
  489. if (touching) {
  490. xMov.endTouch(event);
  491. yMov.endTouch(event);
  492. xMov.validate(yMov);
  493. yMov.validate(xMov);
  494. // Adjust duration so as longer movements take more duration
  495. boolean vert = !xMov.run || yMov.run
  496. && Math.abs(yMov.offset) > Math.abs(xMov.offset);
  497. double delta = Math.abs((vert ? yMov : xMov).offset);
  498. animation.run((int) (3 * DURATION * easingOutExp(delta)));
  499. }
  500. }
  501. // Allow touchStart for IE11 and Edge even though there is no touch
  502. // (#18737),
  503. // otherwise allow touch only if there is a single touch in the
  504. // event
  505. private boolean allowTouch(
  506. final TouchHandlerBundle.CustomTouchEvent event) {
  507. if (isCurrentBrowserIE11OrEdge()) {
  508. return (POINTER_EVENT_TYPE_TOUCH
  509. .equals(event.getPointerType()));
  510. } else {
  511. return (event.getNativeEvent().getTouches().length() == 1);
  512. }
  513. }
  514. private double easingInOutCos(double val, double max) {
  515. return 0.5 - 0.5 * Math.cos(Math.PI * Math.signum(val)
  516. * Math.min(Math.abs(val), max) / max);
  517. }
  518. private double easingOutExp(double delta) {
  519. return (1 - Math.pow(2, -delta / 1000));
  520. }
  521. private double easingOutCirc(double progress) {
  522. return Math.sqrt(1 - (progress - 1) * (progress - 1));
  523. }
  524. }
  525. public static void moveScrollFromEvent(final Escalator escalator,
  526. final double deltaX, final double deltaY,
  527. final NativeEvent event) {
  528. if (!Double.isNaN(deltaX)) {
  529. escalator.horizontalScrollbar.setScrollPosByDelta(deltaX);
  530. }
  531. if (!Double.isNaN(deltaY)) {
  532. escalator.verticalScrollbar.setScrollPosByDelta(deltaY);
  533. }
  534. /*
  535. * TODO: only prevent if not scrolled to end/bottom. Or no? UX team
  536. * needs to decide.
  537. */
  538. final boolean warrantedYScroll = deltaY != 0
  539. && escalator.verticalScrollbar.showsScrollHandle();
  540. final boolean warrantedXScroll = deltaX != 0
  541. && escalator.horizontalScrollbar.showsScrollHandle();
  542. if (warrantedYScroll || warrantedXScroll) {
  543. event.preventDefault();
  544. }
  545. }
  546. }
  547. /**
  548. * ScrollDestination case-specific handling logic.
  549. */
  550. private static double getScrollPos(final ScrollDestination destination,
  551. final double targetStartPx, final double targetEndPx,
  552. final double viewportStartPx, final double viewportEndPx,
  553. final double padding) {
  554. final double viewportLength = viewportEndPx - viewportStartPx;
  555. switch (destination) {
  556. /*
  557. * Scroll as little as possible to show the target element. If the
  558. * element fits into view, this works as START or END depending on the
  559. * current scroll position. If the element does not fit into view, this
  560. * works as START.
  561. */
  562. case ANY: {
  563. final double startScrollPos = targetStartPx - padding;
  564. final double endScrollPos = targetEndPx + padding - viewportLength;
  565. if (startScrollPos < viewportStartPx) {
  566. return startScrollPos;
  567. } else if (targetEndPx + padding > viewportEndPx) {
  568. return endScrollPos;
  569. } else {
  570. // NOOP, it's already visible
  571. return viewportStartPx;
  572. }
  573. }
  574. /*
  575. * Scrolls so that the element is shown at the end of the viewport. The
  576. * viewport will, however, not scroll before its first element.
  577. */
  578. case END: {
  579. return targetEndPx + padding - viewportLength;
  580. }
  581. /*
  582. * Scrolls so that the element is shown in the middle of the viewport.
  583. * The viewport will, however, not scroll beyond its contents, given
  584. * more elements than what the viewport is able to show at once. Under
  585. * no circumstances will the viewport scroll before its first element.
  586. */
  587. case MIDDLE: {
  588. final double targetMiddle = targetStartPx
  589. + (targetEndPx - targetStartPx) / 2;
  590. return targetMiddle - viewportLength / 2;
  591. }
  592. /*
  593. * Scrolls so that the element is shown at the start of the viewport.
  594. * The viewport will, however, not scroll beyond its contents.
  595. */
  596. case START: {
  597. return targetStartPx - padding;
  598. }
  599. /*
  600. * Throw an error if we're here. This can only mean that
  601. * ScrollDestination has been carelessly amended..
  602. */
  603. default: {
  604. throw new IllegalArgumentException(
  605. "Internal: ScrollDestination has been modified, "
  606. + "but Escalator.getScrollPos has not been updated "
  607. + "to match new values.");
  608. }
  609. }
  610. }
  611. /** An inner class that handles all logic related to scrolling. */
  612. private class Scroller extends JsniWorkaround {
  613. private double lastScrollTop = 0;
  614. private double lastScrollLeft = 0;
  615. public Scroller() {
  616. super(Escalator.this);
  617. }
  618. @Override
  619. protected native JavaScriptObject createScrollListenerFunction(
  620. Escalator esc)
  621. /*-{
  622. var vScroll = esc.@com.vaadin.v7.client.widgets.Escalator::verticalScrollbar;
  623. var vScrollElem = vScroll.@com.vaadin.v7.client.widget.escalator.ScrollbarBundle::getElement()();
  624. var hScroll = esc.@com.vaadin.v7.client.widgets.Escalator::horizontalScrollbar;
  625. var hScrollElem = hScroll.@com.vaadin.v7.client.widget.escalator.ScrollbarBundle::getElement()();
  626. return $entry(function(e) {
  627. var target = e.target;
  628. // in case the scroll event was native (i.e. scrollbars were dragged, or
  629. // the scrollTop/Left was manually modified), the bundles have old cache
  630. // values. We need to make sure that the caches are kept up to date.
  631. if (target === vScrollElem) {
  632. vScroll.@com.vaadin.v7.client.widget.escalator.ScrollbarBundle::updateScrollPosFromDom()();
  633. } else if (target === hScrollElem) {
  634. hScroll.@com.vaadin.v7.client.widget.escalator.ScrollbarBundle::updateScrollPosFromDom()();
  635. } else {
  636. $wnd.console.error("unexpected scroll target: "+target);
  637. }
  638. });
  639. }-*/;
  640. @Override
  641. protected native JavaScriptObject createMousewheelListenerFunction(
  642. Escalator esc)
  643. /*-{
  644. return $entry(function(e) {
  645. var deltaX = e.deltaX ? e.deltaX : -0.5*e.wheelDeltaX;
  646. var deltaY = e.deltaY ? e.deltaY : -0.5*e.wheelDeltaY;
  647. // Delta mode 0 is in pixels; we don't need to do anything...
  648. // A delta mode of 1 means we're scrolling by lines instead of pixels
  649. // We need to scale the number of lines by the default line height
  650. if (e.deltaMode === 1) {
  651. var brc = esc.@com.vaadin.v7.client.widgets.Escalator::body;
  652. deltaY *= brc.@com.vaadin.v7.client.widgets.Escalator.AbstractRowContainer::getDefaultRowHeight()();
  653. }
  654. // Other delta modes aren't supported
  655. if ((e.deltaMode !== undefined) && (e.deltaMode >= 2 || e.deltaMode < 0)) {
  656. var msg = "Unsupported wheel delta mode \"" + e.deltaMode + "\"";
  657. // Print warning message
  658. esc.@com.vaadin.v7.client.widgets.Escalator::logWarning(*)(msg);
  659. }
  660. // IE8 has only delta y
  661. if (isNaN(deltaY)) {
  662. deltaY = -0.5*e.wheelDelta;
  663. }
  664. @com.vaadin.v7.client.widgets.Escalator.JsniUtil::moveScrollFromEvent(*)(esc, deltaX, deltaY, e);
  665. });
  666. }-*/;
  667. /**
  668. * Recalculates the virtual viewport represented by the scrollbars, so
  669. * that the sizes of the scroll handles appear correct in the browser
  670. */
  671. public void recalculateScrollbarsForVirtualViewport() {
  672. double scrollContentHeight = body.calculateTotalRowHeight()
  673. + body.spacerContainer.getSpacerHeightsSum();
  674. double scrollContentWidth = columnConfiguration.calculateRowWidth();
  675. double tableWrapperHeight = heightOfEscalator;
  676. double tableWrapperWidth = widthOfEscalator;
  677. boolean verticalScrollNeeded = scrollContentHeight > tableWrapperHeight
  678. + WidgetUtil.PIXEL_EPSILON - header.getHeightOfSection()
  679. - footer.getHeightOfSection();
  680. boolean horizontalScrollNeeded = scrollContentWidth > tableWrapperWidth
  681. + WidgetUtil.PIXEL_EPSILON;
  682. // One dimension got scrollbars, but not the other. Recheck time!
  683. if (verticalScrollNeeded != horizontalScrollNeeded) {
  684. if (!verticalScrollNeeded && horizontalScrollNeeded) {
  685. verticalScrollNeeded = scrollContentHeight > tableWrapperHeight
  686. + WidgetUtil.PIXEL_EPSILON
  687. - header.getHeightOfSection()
  688. - footer.getHeightOfSection()
  689. - horizontalScrollbar.getScrollbarThickness();
  690. } else {
  691. horizontalScrollNeeded = scrollContentWidth > tableWrapperWidth
  692. + WidgetUtil.PIXEL_EPSILON
  693. - verticalScrollbar.getScrollbarThickness();
  694. }
  695. }
  696. // let's fix the table wrapper size, since it's now stable.
  697. if (verticalScrollNeeded) {
  698. tableWrapperWidth -= verticalScrollbar.getScrollbarThickness();
  699. tableWrapperWidth = Math.max(0, tableWrapperWidth);
  700. }
  701. if (horizontalScrollNeeded) {
  702. tableWrapperHeight -= horizontalScrollbar
  703. .getScrollbarThickness();
  704. tableWrapperHeight = Math.max(0, tableWrapperHeight);
  705. }
  706. tableWrapper.getStyle().setHeight(tableWrapperHeight, Unit.PX);
  707. tableWrapper.getStyle().setWidth(tableWrapperWidth, Unit.PX);
  708. double footerHeight = footer.getHeightOfSection();
  709. double headerHeight = header.getHeightOfSection();
  710. double vScrollbarHeight = Math.max(0,
  711. tableWrapperHeight - footerHeight - headerHeight);
  712. verticalScrollbar.setOffsetSize(vScrollbarHeight);
  713. verticalScrollbar.setScrollSize(scrollContentHeight);
  714. /*
  715. * If decreasing the amount of frozen columns, and scrolled to the
  716. * right, the scroll position might reset. So we need to remember
  717. * the scroll position, and re-apply it once the scrollbar size has
  718. * been adjusted.
  719. */
  720. double prevScrollPos = horizontalScrollbar.getScrollPos();
  721. double unfrozenPixels = columnConfiguration
  722. .getCalculatedColumnsWidth(Range.between(
  723. columnConfiguration.getFrozenColumnCount(),
  724. columnConfiguration.getColumnCount()));
  725. double frozenPixels = scrollContentWidth - unfrozenPixels;
  726. double hScrollOffsetWidth = tableWrapperWidth - frozenPixels;
  727. horizontalScrollbar.setOffsetSize(hScrollOffsetWidth);
  728. horizontalScrollbar.setScrollSize(unfrozenPixels);
  729. horizontalScrollbar.getElement().getStyle().setLeft(frozenPixels,
  730. Unit.PX);
  731. horizontalScrollbar.setScrollPos(prevScrollPos);
  732. /*
  733. * only show the scrollbar wrapper if the scrollbar itself is
  734. * visible.
  735. */
  736. if (horizontalScrollbar.showsScrollHandle()) {
  737. horizontalScrollbarDeco.getStyle().clearDisplay();
  738. } else {
  739. horizontalScrollbarDeco.getStyle().setDisplay(Display.NONE);
  740. }
  741. /*
  742. * only show corner background divs if the vertical scrollbar is
  743. * visible.
  744. */
  745. Style hCornerStyle = headerDeco.getStyle();
  746. Style fCornerStyle = footerDeco.getStyle();
  747. if (verticalScrollbar.showsScrollHandle()) {
  748. hCornerStyle.clearDisplay();
  749. fCornerStyle.clearDisplay();
  750. if (horizontalScrollbar.showsScrollHandle()) {
  751. double offset = horizontalScrollbar.getScrollbarThickness();
  752. fCornerStyle.setBottom(offset, Unit.PX);
  753. } else {
  754. fCornerStyle.clearBottom();
  755. }
  756. } else {
  757. hCornerStyle.setDisplay(Display.NONE);
  758. fCornerStyle.setDisplay(Display.NONE);
  759. }
  760. }
  761. /**
  762. * Logical scrolling event handler for the entire widget.
  763. */
  764. public void onScroll() {
  765. final double scrollTop = verticalScrollbar.getScrollPos();
  766. final double scrollLeft = horizontalScrollbar.getScrollPos();
  767. if (lastScrollLeft != scrollLeft) {
  768. for (int i = 0; i < columnConfiguration.frozenColumns; i++) {
  769. header.updateFreezePosition(i, scrollLeft);
  770. body.updateFreezePosition(i, scrollLeft);
  771. footer.updateFreezePosition(i, scrollLeft);
  772. }
  773. position.set(headElem, -scrollLeft, 0);
  774. /*
  775. * TODO [[optimize]]: cache this value in case the instanceof
  776. * check has undesirable overhead. This could also be a
  777. * candidate for some deferred binding magic so that e.g.
  778. * AbsolutePosition is not even considered in permutations that
  779. * we know support something better. That would let the compiler
  780. * completely remove the entire condition since it knows that
  781. * the if will never be true.
  782. */
  783. if (position instanceof AbsolutePosition) {
  784. /*
  785. * we don't want to put "top: 0" on the footer, since it'll
  786. * render wrong, as we already have
  787. * "bottom: $footer-height".
  788. */
  789. footElem.getStyle().setLeft(-scrollLeft, Unit.PX);
  790. } else {
  791. position.set(footElem, -scrollLeft, 0);
  792. }
  793. lastScrollLeft = scrollLeft;
  794. }
  795. body.setBodyScrollPosition(scrollLeft, scrollTop);
  796. lastScrollTop = scrollTop;
  797. body.updateEscalatorRowsOnScroll();
  798. body.spacerContainer.updateSpacerDecosVisibility();
  799. /*
  800. * TODO [[optimize]]: Might avoid a reflow by first calculating new
  801. * scrolltop and scrolleft, then doing the escalator magic based on
  802. * those numbers and only updating the positions after that.
  803. */
  804. }
  805. public native void attachScrollListener(Element element)
  806. /*
  807. * Attaching events with JSNI instead of the GWT event mechanism because
  808. * GWT didn't provide enough details in events, or triggering the event
  809. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  810. * and skill, it could be done with better success. JavaScript overlay
  811. * types might work. This might also get rid of the JsniWorkaround
  812. * class.
  813. */
  814. /*-{
  815. if (element.addEventListener) {
  816. element.addEventListener("scroll", this.@com.vaadin.v7.client.widgets.JsniWorkaround::scrollListenerFunction);
  817. } else {
  818. element.attachEvent("onscroll", this.@com.vaadin.v7.client.widgets.JsniWorkaround::scrollListenerFunction);
  819. }
  820. }-*/;
  821. public native void detachScrollListener(Element element)
  822. /*
  823. * Detaching events with JSNI instead of the GWT event mechanism because
  824. * GWT didn't provide enough details in events, or triggering the event
  825. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  826. * and skill, it could be done with better success. JavaScript overlay
  827. * types might work. This might also get rid of the JsniWorkaround
  828. * class.
  829. */
  830. /*-{
  831. if (element.addEventListener) {
  832. element.removeEventListener("scroll", this.@com.vaadin.v7.client.widgets.JsniWorkaround::scrollListenerFunction);
  833. } else {
  834. element.detachEvent("onscroll", this.@com.vaadin.v7.client.widgets.JsniWorkaround::scrollListenerFunction);
  835. }
  836. }-*/;
  837. public native void attachMousewheelListener(Element element)
  838. /*
  839. * Attaching events with JSNI instead of the GWT event mechanism because
  840. * GWT didn't provide enough details in events, or triggering the event
  841. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  842. * and skill, it could be done with better success. JavaScript overlay
  843. * types might work. This might also get rid of the JsniWorkaround
  844. * class.
  845. */
  846. /*-{
  847. // firefox likes "wheel", while others use "mousewheel"
  848. var eventName = 'onmousewheel' in element ? 'mousewheel' : 'wheel';
  849. element.addEventListener(eventName, this.@com.vaadin.v7.client.widgets.JsniWorkaround::mousewheelListenerFunction);
  850. }-*/;
  851. public native void detachMousewheelListener(Element element)
  852. /*
  853. * Detaching events with JSNI instead of the GWT event mechanism because
  854. * GWT didn't provide enough details in events, or triggering the event
  855. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  856. * and skill, it could be done with better success. JavaScript overlay
  857. * types might work. This might also get rid of the JsniWorkaround
  858. * class.
  859. */
  860. /*-{
  861. // firefox likes "wheel", while others use "mousewheel"
  862. var eventName = element.onwheel===undefined?"mousewheel":"wheel";
  863. element.removeEventListener(eventName, this.@com.vaadin.v7.client.widgets.JsniWorkaround::mousewheelListenerFunction);
  864. }-*/;
  865. public native void attachTouchListeners(Element element)
  866. /*
  867. * Detaching events with JSNI instead of the GWT event mechanism because
  868. * GWT didn't provide enough details in events, or triggering the event
  869. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  870. * and skill, it could be done with better success. JavaScript overlay
  871. * types might work. This might also get rid of the JsniWorkaround
  872. * class.
  873. */
  874. /*-{
  875. element.addEventListener("touchstart", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchStartFunction);
  876. element.addEventListener("touchmove", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchMoveFunction);
  877. element.addEventListener("touchend", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  878. element.addEventListener("touchcancel", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  879. }-*/;
  880. public native void detachTouchListeners(Element element)
  881. /*
  882. * Detaching events with JSNI instead of the GWT event mechanism because
  883. * GWT didn't provide enough details in events, or triggering the event
  884. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  885. * and skill, it could be done with better success. JavaScript overlay
  886. * types might work. This might also get rid of the JsniWorkaround
  887. * class.
  888. */
  889. /*-{
  890. element.removeEventListener("touchstart", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchStartFunction);
  891. element.removeEventListener("touchmove", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchMoveFunction);
  892. element.removeEventListener("touchend", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  893. element.removeEventListener("touchcancel", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  894. }-*/;
  895. /**
  896. * Using pointerdown, pointermove, pointerup, and pointercancel for IE11
  897. * and Edge instead of touch* listeners (#18737)
  898. *
  899. * @param element
  900. */
  901. public native void attachPointerEventListeners(Element element)
  902. /*
  903. * Attaching events with JSNI instead of the GWT event mechanism because
  904. * GWT didn't provide enough details in events, or triggering the event
  905. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  906. * and skill, it could be done with better success. JavaScript overlay
  907. * types might work. This might also get rid of the JsniWorkaround
  908. * class.
  909. */
  910. /*-{
  911. element.addEventListener("pointerdown", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchStartFunction);
  912. element.addEventListener("pointermove", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchMoveFunction);
  913. element.addEventListener("pointerup", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  914. element.addEventListener("pointercancel", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  915. }-*/;
  916. /**
  917. * Using pointerdown, pointermove, pointerup, and pointercancel for IE11
  918. * and Edge instead of touch* listeners (#18737)
  919. *
  920. * @param element
  921. */
  922. public native void detachPointerEventListeners(Element element)
  923. /*
  924. * Detaching events with JSNI instead of the GWT event mechanism because
  925. * GWT didn't provide enough details in events, or triggering the event
  926. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  927. * and skill, it could be done with better success. JavaScript overlay
  928. * types might work. This might also get rid of the JsniWorkaround
  929. * class.
  930. */
  931. /*-{
  932. element.removeEventListener("pointerdown", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchStartFunction);
  933. element.removeEventListener("pointermove", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchMoveFunction);
  934. element.removeEventListener("pointerup", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  935. element.removeEventListener("pointercancel", this.@com.vaadin.v7.client.widgets.JsniWorkaround::touchEndFunction);
  936. }-*/;
  937. public void scrollToColumn(final int columnIndex,
  938. final ScrollDestination destination, final int padding) {
  939. assert columnIndex >= columnConfiguration.frozenColumns : "Can't scroll to a frozen column";
  940. /*
  941. * To cope with frozen columns, we just pretend those columns are
  942. * not there at all when calculating the position of the target
  943. * column and the boundaries of the viewport. The resulting
  944. * scrollLeft will be correct without compensation since the DOM
  945. * structure effectively means that scrollLeft also ignores the
  946. * frozen columns.
  947. */
  948. final double frozenPixels = columnConfiguration
  949. .getCalculatedColumnsWidth(Range.withLength(0,
  950. columnConfiguration.frozenColumns));
  951. final double targetStartPx = columnConfiguration
  952. .getCalculatedColumnsWidth(Range.withLength(0, columnIndex))
  953. - frozenPixels;
  954. final double targetEndPx = targetStartPx
  955. + columnConfiguration.getColumnWidthActual(columnIndex);
  956. final double viewportStartPx = getScrollLeft();
  957. double viewportEndPx = viewportStartPx + WidgetUtil
  958. .getRequiredWidthBoundingClientRectDouble(getElement())
  959. - frozenPixels;
  960. if (verticalScrollbar.showsScrollHandle()) {
  961. viewportEndPx -= WidgetUtil.getNativeScrollbarSize();
  962. }
  963. final double scrollLeft = getScrollPos(destination, targetStartPx,
  964. targetEndPx, viewportStartPx, viewportEndPx, padding);
  965. /*
  966. * note that it doesn't matter if the scroll would go beyond the
  967. * content, since the browser will adjust for that, and everything
  968. * fall into line accordingly.
  969. */
  970. setScrollLeft(scrollLeft);
  971. }
  972. public void scrollToRow(final int rowIndex,
  973. final ScrollDestination destination, final double padding) {
  974. final double targetStartPx = (body.getDefaultRowHeight() * rowIndex)
  975. + body.spacerContainer
  976. .getSpacerHeightsSumUntilIndex(rowIndex);
  977. final double targetEndPx = targetStartPx
  978. + body.getDefaultRowHeight();
  979. final double viewportStartPx = getScrollTop();
  980. final double viewportEndPx = viewportStartPx
  981. + body.getHeightOfSection();
  982. final double scrollTop = getScrollPos(destination, targetStartPx,
  983. targetEndPx, viewportStartPx, viewportEndPx, padding);
  984. /*
  985. * note that it doesn't matter if the scroll would go beyond the
  986. * content, since the browser will adjust for that, and everything
  987. * falls into line accordingly.
  988. */
  989. setScrollTop(scrollTop);
  990. }
  991. }
  992. public abstract class AbstractRowContainer implements RowContainer {
  993. private EscalatorUpdater updater = EscalatorUpdater.NULL;
  994. private int rows;
  995. /**
  996. * The table section element ({@code <thead>}, {@code <tbody>} or
  997. * {@code <tfoot>}) the rows (i.e. <code>&lt;tr&gt;</code> tags) are
  998. * contained in.
  999. */
  1000. protected final TableSectionElement root;
  1001. /**
  1002. * The primary style name of the escalator. Most commonly provided by
  1003. * Escalator as "v-escalator".
  1004. */
  1005. private String primaryStyleName = null;
  1006. private boolean defaultRowHeightShouldBeAutodetected = true;
  1007. private double defaultRowHeight = INITIAL_DEFAULT_ROW_HEIGHT;
  1008. public AbstractRowContainer(
  1009. final TableSectionElement rowContainerElement) {
  1010. root = rowContainerElement;
  1011. }
  1012. @Override
  1013. public TableSectionElement getElement() {
  1014. return root;
  1015. }
  1016. /**
  1017. * Gets the tag name of an element to represent a cell in a row.
  1018. * <p>
  1019. * Usually {@code "th"} or {@code "td"}.
  1020. * <p>
  1021. * <em>Note:</em> To actually <em>create</em> such an element, use
  1022. * {@link #createCellElement(int, int)} instead.
  1023. *
  1024. * @return the tag name for the element to represent cells as
  1025. * @see #createCellElement(int, int)
  1026. */
  1027. protected abstract String getCellElementTagName();
  1028. @Override
  1029. public EscalatorUpdater getEscalatorUpdater() {
  1030. return updater;
  1031. }
  1032. /**
  1033. * {@inheritDoc}
  1034. * <p>
  1035. * <em>Implementation detail:</em> This method does no DOM modifications
  1036. * (i.e. is very cheap to call) if there is no data for rows or columns
  1037. * when this method is called.
  1038. *
  1039. * @see #hasColumnAndRowData()
  1040. */
  1041. @Override
  1042. public void setEscalatorUpdater(
  1043. final EscalatorUpdater escalatorUpdater) {
  1044. if (escalatorUpdater == null) {
  1045. throw new IllegalArgumentException(
  1046. "escalator updater cannot be null");
  1047. }
  1048. updater = escalatorUpdater;
  1049. if (hasColumnAndRowData() && getRowCount() > 0) {
  1050. refreshRows(0, getRowCount());
  1051. }
  1052. }
  1053. /**
  1054. * {@inheritDoc}
  1055. * <p>
  1056. * <em>Implementation detail:</em> This method does no DOM modifications
  1057. * (i.e. is very cheap to call) if there are no rows in the DOM when
  1058. * this method is called.
  1059. *
  1060. * @see #hasSomethingInDom()
  1061. */
  1062. @Override
  1063. public void removeRows(final int index, final int numberOfRows) {
  1064. assertArgumentsAreValidAndWithinRange(index, numberOfRows);
  1065. rows -= numberOfRows;
  1066. if (!isAttached()) {
  1067. return;
  1068. }
  1069. if (hasSomethingInDom()) {
  1070. paintRemoveRows(index, numberOfRows);
  1071. }
  1072. }
  1073. /**
  1074. * Removes those row elements from the DOM that correspond to the given
  1075. * range of logical indices. This may be fewer than {@code numberOfRows}
  1076. * , even zero, if not all the removed rows are actually visible.
  1077. * <p>
  1078. * The implementation must call {@link #paintRemoveRow(Element, int)}
  1079. * for each row that is removed from the DOM.
  1080. *
  1081. * @param index
  1082. * the logical index of the first removed row
  1083. * @param numberOfRows
  1084. * number of logical rows to remove
  1085. */
  1086. protected abstract void paintRemoveRows(final int index,
  1087. final int numberOfRows);
  1088. /**
  1089. * Removes a row element from the DOM, invoking
  1090. * {@link #getEscalatorUpdater()}
  1091. * {@link EscalatorUpdater#preDetach(Row, Iterable) preDetach} and
  1092. * {@link EscalatorUpdater#postDetach(Row, Iterable) postDetach} before
  1093. * and after removing the row, respectively.
  1094. * <p>
  1095. * This method must be called for each removed DOM row by any
  1096. * {@link #paintRemoveRows(int, int)} implementation.
  1097. *
  1098. * @param tr
  1099. * the row element to remove.
  1100. */
  1101. protected void paintRemoveRow(final TableRowElement tr,
  1102. final int logicalRowIndex) {
  1103. flyweightRow.setup(tr, logicalRowIndex,
  1104. columnConfiguration.getCalculatedColumnWidths());
  1105. getEscalatorUpdater().preDetach(flyweightRow,
  1106. flyweightRow.getCells());
  1107. tr.removeFromParent();
  1108. getEscalatorUpdater().postDetach(flyweightRow,
  1109. flyweightRow.getCells());
  1110. /*
  1111. * the "assert" guarantees that this code is run only during
  1112. * development/debugging.
  1113. */
  1114. assert flyweightRow.teardown();
  1115. }
  1116. protected void assertArgumentsAreValidAndWithinRange(final int index,
  1117. final int numberOfRows)
  1118. throws IllegalArgumentException, IndexOutOfBoundsException {
  1119. if (numberOfRows < 1) {
  1120. throw new IllegalArgumentException(
  1121. "Number of rows must be 1 or greater (was "
  1122. + numberOfRows + ")");
  1123. }
  1124. if (index < 0 || index + numberOfRows > getRowCount()) {
  1125. throw new IndexOutOfBoundsException("The given " + "row range ("
  1126. + index + ".." + (index + numberOfRows)
  1127. + ") was outside of the current number of rows ("
  1128. + getRowCount() + ")");
  1129. }
  1130. }
  1131. @Override
  1132. public int getRowCount() {
  1133. return rows;
  1134. }
  1135. /**
  1136. * This method calculates the current row count directly from the DOM.
  1137. * <p>
  1138. * While Escalator is stable, this value should equal to
  1139. * {@link #getRowCount()}, but while row counts are being updated, these
  1140. * two values might differ for a short while.
  1141. * <p>
  1142. * Any extra content, such as spacers for the body, should not be
  1143. * included in this count.
  1144. *
  1145. * @since 7.5.0
  1146. *
  1147. * @return the actual DOM count of rows
  1148. */
  1149. public abstract int getDomRowCount();
  1150. /**
  1151. * {@inheritDoc}
  1152. * <p>
  1153. * <em>Implementation detail:</em> This method does no DOM modifications
  1154. * (i.e. is very cheap to call) if there is no data for columns when
  1155. * this method is called.
  1156. *
  1157. * @see #hasColumnAndRowData()
  1158. */
  1159. @Override
  1160. public void insertRows(final int index, final int numberOfRows) {
  1161. if (index < 0 || index > getRowCount()) {
  1162. throw new IndexOutOfBoundsException("The given index (" + index
  1163. + ") was outside of the current number of rows (0.."
  1164. + getRowCount() + ")");
  1165. }
  1166. if (numberOfRows < 1) {
  1167. throw new IllegalArgumentException(
  1168. "Number of rows must be 1 or greater (was "
  1169. + numberOfRows + ")");
  1170. }
  1171. rows += numberOfRows;
  1172. /*
  1173. * only add items in the DOM if the widget itself is attached to the
  1174. * DOM. We can't calculate sizes otherwise.
  1175. */
  1176. if (isAttached()) {
  1177. paintInsertRows(index, numberOfRows);
  1178. if (rows == numberOfRows) {
  1179. /*
  1180. * We are inserting the first rows in this container. We
  1181. * potentially need to set the widths for the cells for the
  1182. * first time.
  1183. */
  1184. Map<Integer, Double> colWidths = new HashMap<Integer, Double>();
  1185. for (int i = 0; i < getColumnConfiguration()
  1186. .getColumnCount(); i++) {
  1187. Double width = Double.valueOf(
  1188. getColumnConfiguration().getColumnWidth(i));
  1189. Integer col = Integer.valueOf(i);
  1190. colWidths.put(col, width);
  1191. }
  1192. getColumnConfiguration().setColumnWidths(colWidths);
  1193. }
  1194. }
  1195. }
  1196. /**
  1197. * Actually add rows into the DOM, now that everything can be
  1198. * calculated.
  1199. *
  1200. * @param visualIndex
  1201. * the DOM index to add rows into
  1202. * @param numberOfRows
  1203. * the number of rows to insert
  1204. */
  1205. protected abstract void paintInsertRows(final int visualIndex,
  1206. final int numberOfRows);
  1207. protected List<TableRowElement> paintInsertStaticRows(
  1208. final int visualIndex, final int numberOfRows) {
  1209. assert isAttached() : "Can't paint rows if Escalator is not attached";
  1210. final List<TableRowElement> addedRows = new ArrayList<TableRowElement>();
  1211. if (numberOfRows < 1) {
  1212. return addedRows;
  1213. }
  1214. Node referenceRow;
  1215. if (root.getChildCount() != 0 && visualIndex != 0) {
  1216. // get the row node we're inserting stuff after
  1217. referenceRow = root.getChild(visualIndex - 1);
  1218. } else {
  1219. // index is 0, so just prepend.
  1220. referenceRow = null;
  1221. }
  1222. for (int row = visualIndex; row < visualIndex
  1223. + numberOfRows; row++) {
  1224. final TableRowElement tr = TableRowElement.as(DOM.createTR());
  1225. addedRows.add(tr);
  1226. tr.addClassName(getStylePrimaryName() + "-row");
  1227. for (int col = 0; col < columnConfiguration
  1228. .getColumnCount(); col++) {
  1229. final double colWidth = columnConfiguration
  1230. .getColumnWidthActual(col);
  1231. final TableCellElement cellElem = createCellElement(
  1232. colWidth);
  1233. tr.appendChild(cellElem);
  1234. // Set stylename and position if new cell is frozen
  1235. if (col < columnConfiguration.frozenColumns) {
  1236. cellElem.addClassName("frozen");
  1237. position.set(cellElem, scroller.lastScrollLeft, 0);
  1238. }
  1239. if (columnConfiguration.frozenColumns > 0
  1240. && col == columnConfiguration.frozenColumns - 1) {
  1241. cellElem.addClassName("last-frozen");
  1242. }
  1243. }
  1244. referenceRow = paintInsertRow(referenceRow, tr, row);
  1245. }
  1246. reapplyRowWidths();
  1247. recalculateSectionHeight();
  1248. return addedRows;
  1249. }
  1250. /**
  1251. * Inserts a single row into the DOM, invoking
  1252. * {@link #getEscalatorUpdater()}
  1253. * {@link EscalatorUpdater#preAttach(Row, Iterable) preAttach} and
  1254. * {@link EscalatorUpdater#postAttach(Row, Iterable) postAttach} before
  1255. * and after inserting the row, respectively. The row should have its
  1256. * cells already inserted.
  1257. *
  1258. * @param referenceRow
  1259. * the row after which to insert or null if insert as first
  1260. * @param tr
  1261. * the row to be inserted
  1262. * @param logicalRowIndex
  1263. * the logical index of the inserted row
  1264. * @return the inserted row to be used as the new reference
  1265. */
  1266. protected Node paintInsertRow(Node referenceRow,
  1267. final TableRowElement tr, int logicalRowIndex) {
  1268. flyweightRow.setup(tr, logicalRowIndex,
  1269. columnConfiguration.getCalculatedColumnWidths());
  1270. getEscalatorUpdater().preAttach(flyweightRow,
  1271. flyweightRow.getCells());
  1272. referenceRow = insertAfterReferenceAndUpdateIt(root, tr,
  1273. referenceRow);
  1274. getEscalatorUpdater().postAttach(flyweightRow,
  1275. flyweightRow.getCells());
  1276. updater.update(flyweightRow, flyweightRow.getCells());
  1277. /*
  1278. * the "assert" guarantees that this code is run only during
  1279. * development/debugging.
  1280. */
  1281. assert flyweightRow.teardown();
  1282. return referenceRow;
  1283. }
  1284. private Node insertAfterReferenceAndUpdateIt(final Element parent,
  1285. final Element elem, final Node referenceNode) {
  1286. if (referenceNode != null) {
  1287. parent.insertAfter(elem, referenceNode);
  1288. } else {
  1289. /*
  1290. * referencenode being null means we have offset 0, i.e. make it
  1291. * the first row
  1292. */
  1293. /*
  1294. * TODO [[optimize]]: Is insertFirst or append faster for an
  1295. * empty root?
  1296. */
  1297. parent.insertFirst(elem);
  1298. }
  1299. return elem;
  1300. }
  1301. protected abstract void recalculateSectionHeight();
  1302. /**
  1303. * Returns the height of all rows in the row container.
  1304. */
  1305. protected double calculateTotalRowHeight() {
  1306. return getDefaultRowHeight() * getRowCount();
  1307. }
  1308. /**
  1309. * {@inheritDoc}
  1310. * <p>
  1311. * <em>Implementation detail:</em> This method does no DOM modifications
  1312. * (i.e. is very cheap to call) if there is no data for columns when
  1313. * this method is called.
  1314. *
  1315. * @see #hasColumnAndRowData()
  1316. */
  1317. @Override
  1318. // overridden because of JavaDoc
  1319. public void refreshRows(final int index, final int numberOfRows) {
  1320. Range rowRange = Range.withLength(index, numberOfRows);
  1321. Range colRange = Range.withLength(0,
  1322. getColumnConfiguration().getColumnCount());
  1323. refreshCells(rowRange, colRange);
  1324. }
  1325. protected abstract void refreshCells(Range logicalRowRange,
  1326. Range colRange);
  1327. void refreshRow(TableRowElement tr, int logicalRowIndex) {
  1328. refreshRow(tr, logicalRowIndex, Range.withLength(0,
  1329. getColumnConfiguration().getColumnCount()));
  1330. }
  1331. void refreshRow(final TableRowElement tr, final int logicalRowIndex,
  1332. Range colRange) {
  1333. flyweightRow.setup(tr, logicalRowIndex,
  1334. columnConfiguration.getCalculatedColumnWidths());
  1335. Iterable<FlyweightCell> cellsToUpdate = flyweightRow
  1336. .getCells(colRange.getStart(), colRange.length());
  1337. updater.update(flyweightRow, cellsToUpdate);
  1338. /*
  1339. * the "assert" guarantees that this code is run only during
  1340. * development/debugging.
  1341. */
  1342. assert flyweightRow.teardown();
  1343. }
  1344. /**
  1345. * Create and setup an empty cell element.
  1346. *
  1347. * @param width
  1348. * the width of the cell, in pixels
  1349. *
  1350. * @return a set-up empty cell element
  1351. */
  1352. public TableCellElement createCellElement(final double width) {
  1353. final TableCellElement cellElem = TableCellElement
  1354. .as(DOM.createElement(getCellElementTagName()));
  1355. final double height = getDefaultRowHeight();
  1356. assert height >= 0 : "defaultRowHeight was negative. There's a setter leak somewhere.";
  1357. cellElem.getStyle().setHeight(height, Unit.PX);
  1358. if (width >= 0) {
  1359. cellElem.getStyle().setWidth(width, Unit.PX);
  1360. }
  1361. cellElem.addClassName(getStylePrimaryName() + "-cell");
  1362. return cellElem;
  1363. }
  1364. @Override
  1365. public TableRowElement getRowElement(int index) {
  1366. return getTrByVisualIndex(index);
  1367. }
  1368. /**
  1369. * Gets the child element that is visually at a certain index.
  1370. *
  1371. * @param index
  1372. * the index of the element to retrieve
  1373. * @return the element at position {@code index}
  1374. * @throws IndexOutOfBoundsException
  1375. * if {@code index} is not valid within {@link #root}
  1376. */
  1377. protected abstract TableRowElement getTrByVisualIndex(int index)
  1378. throws IndexOutOfBoundsException;
  1379. protected void paintRemoveColumns(final int offset,
  1380. final int numberOfColumns) {
  1381. for (int i = 0; i < getDomRowCount(); i++) {
  1382. TableRowElement row = getTrByVisualIndex(i);
  1383. flyweightRow.setup(row, i,
  1384. columnConfiguration.getCalculatedColumnWidths());
  1385. Iterable<FlyweightCell> attachedCells = flyweightRow
  1386. .getCells(offset, numberOfColumns);
  1387. getEscalatorUpdater().preDetach(flyweightRow, attachedCells);
  1388. for (int j = 0; j < numberOfColumns; j++) {
  1389. row.getCells().getItem(offset).removeFromParent();
  1390. }
  1391. Iterable<FlyweightCell> detachedCells = flyweightRow
  1392. .getUnattachedCells(offset, numberOfColumns);
  1393. getEscalatorUpdater().postDetach(flyweightRow, detachedCells);
  1394. assert flyweightRow.teardown();
  1395. }
  1396. }
  1397. protected void paintInsertColumns(final int offset,
  1398. final int numberOfColumns, boolean frozen) {
  1399. for (int row = 0; row < getDomRowCount(); row++) {
  1400. final TableRowElement tr = getTrByVisualIndex(row);
  1401. int logicalRowIndex = getLogicalRowIndex(tr);
  1402. paintInsertCells(tr, logicalRowIndex, offset, numberOfColumns);
  1403. }
  1404. reapplyRowWidths();
  1405. if (frozen) {
  1406. for (int col = offset; col < offset + numberOfColumns; col++) {
  1407. setColumnFrozen(col, true);
  1408. }
  1409. }
  1410. }
  1411. /**
  1412. * Inserts new cell elements into a single row element, invoking
  1413. * {@link #getEscalatorUpdater()}
  1414. * {@link EscalatorUpdater#preAttach(Row, Iterable) preAttach} and
  1415. * {@link EscalatorUpdater#postAttach(Row, Iterable) postAttach} before
  1416. * and after inserting the cells, respectively.
  1417. * <p>
  1418. * Precondition: The row must be already attached to the DOM and the
  1419. * FlyweightCell instances corresponding to the new columns added to
  1420. * {@code flyweightRow}.
  1421. *
  1422. * @param tr
  1423. * the row in which to insert the cells
  1424. * @param logicalRowIndex
  1425. * the index of the row
  1426. * @param offset
  1427. * the index of the first cell
  1428. * @param numberOfCells
  1429. * the number of cells to insert
  1430. */
  1431. private void paintInsertCells(final TableRowElement tr,
  1432. int logicalRowIndex, final int offset,
  1433. final int numberOfCells) {
  1434. assert root.isOrHasChild(
  1435. tr) : "The row must be attached to the document";
  1436. flyweightRow.setup(tr, logicalRowIndex,
  1437. columnConfiguration.getCalculatedColumnWidths());
  1438. Iterable<FlyweightCell> cells = flyweightRow
  1439. .getUnattachedCells(offset, numberOfCells);
  1440. for (FlyweightCell cell : cells) {
  1441. final double colWidth = columnConfiguration
  1442. .getColumnWidthActual(cell.getColumn());
  1443. final TableCellElement cellElem = createCellElement(colWidth);
  1444. cell.setElement(cellElem);
  1445. }
  1446. getEscalatorUpdater().preAttach(flyweightRow, cells);
  1447. Node referenceCell;
  1448. if (offset != 0) {
  1449. referenceCell = tr.getChild(offset - 1);
  1450. } else {
  1451. referenceCell = null;
  1452. }
  1453. for (FlyweightCell cell : cells) {
  1454. referenceCell = insertAfterReferenceAndUpdateIt(tr,
  1455. cell.getElement(), referenceCell);
  1456. }
  1457. getEscalatorUpdater().postAttach(flyweightRow, cells);
  1458. getEscalatorUpdater().update(flyweightRow, cells);
  1459. assert flyweightRow.teardown();
  1460. }
  1461. public void setColumnFrozen(int column, boolean frozen) {
  1462. toggleFrozenColumnClass(column, frozen, "frozen");
  1463. if (frozen) {
  1464. updateFreezePosition(column, scroller.lastScrollLeft);
  1465. }
  1466. }
  1467. private void toggleFrozenColumnClass(int column, boolean frozen,
  1468. String className) {
  1469. final NodeList<TableRowElement> childRows = root.getRows();
  1470. for (int row = 0; row < childRows.getLength(); row++) {
  1471. final TableRowElement tr = childRows.getItem(row);
  1472. if (!rowCanBeFrozen(tr)) {
  1473. continue;
  1474. }
  1475. TableCellElement cell = tr.getCells().getItem(column);
  1476. if (frozen) {
  1477. cell.addClassName(className);
  1478. } else {
  1479. cell.removeClassName(className);
  1480. position.reset(cell);
  1481. }
  1482. }
  1483. }
  1484. public void setColumnLastFrozen(int column, boolean lastFrozen) {
  1485. toggleFrozenColumnClass(column, lastFrozen, "last-frozen");
  1486. }
  1487. public void updateFreezePosition(int column, double scrollLeft) {
  1488. final NodeList<TableRowElement> childRows = root.getRows();
  1489. for (int row = 0; row < childRows.getLength(); row++) {
  1490. final TableRowElement tr = childRows.getItem(row);
  1491. if (rowCanBeFrozen(tr)) {
  1492. TableCellElement cell = tr.getCells().getItem(column);
  1493. position.set(cell, scrollLeft, 0);
  1494. }
  1495. }
  1496. }
  1497. /**
  1498. * Checks whether a row is an element, or contains such elements, that
  1499. * can be frozen.
  1500. * <p>
  1501. * In practice, this applies for all header and footer rows. For body
  1502. * rows, it applies for all rows except spacer rows.
  1503. *
  1504. * @since 7.5.0
  1505. *
  1506. * @param tr
  1507. * the row element to check for if it is or has elements that
  1508. * can be frozen
  1509. * @return <code>true</code> if this the given element, or any of its
  1510. * descendants, can be frozen
  1511. */
  1512. protected abstract boolean rowCanBeFrozen(TableRowElement tr);
  1513. /**
  1514. * Iterates through all the cells in a column and returns the width of
  1515. * the widest element in this RowContainer.
  1516. *
  1517. * @param index
  1518. * the index of the column to inspect
  1519. * @return the pixel width of the widest element in the indicated column
  1520. */
  1521. public double calculateMaxColWidth(int index) {
  1522. TableRowElement row = TableRowElement
  1523. .as(root.getFirstChildElement());
  1524. double maxWidth = 0;
  1525. while (row != null) {
  1526. final TableCellElement cell = row.getCells().getItem(index);
  1527. final boolean isVisible = !cell.getStyle().getDisplay()
  1528. .equals(Display.NONE.getCssName());
  1529. if (isVisible) {
  1530. maxWidth = Math.max(maxWidth, WidgetUtil
  1531. .getRequiredWidthBoundingClientRectDouble(cell));
  1532. }
  1533. row = TableRowElement.as(row.getNextSiblingElement());
  1534. }
  1535. return maxWidth;
  1536. }
  1537. /**
  1538. * Reapplies all the cells' widths according to the calculated widths in
  1539. * the column configuration.
  1540. */
  1541. public void reapplyColumnWidths() {
  1542. Element row = root.getFirstChildElement();
  1543. while (row != null) {
  1544. // Only handle non-spacer rows
  1545. if (!body.spacerContainer.isSpacer(row)) {
  1546. Element cell = row.getFirstChildElement();
  1547. int columnIndex = 0;
  1548. while (cell != null) {
  1549. final double width = getCalculatedColumnWidthWithColspan(
  1550. cell, columnIndex);
  1551. /*
  1552. * TODO Should Escalator implement ProvidesResize at
  1553. * some point, this is where we need to do that.
  1554. */
  1555. cell.getStyle().setWidth(width, Unit.PX);
  1556. cell = cell.getNextSiblingElement();
  1557. columnIndex++;
  1558. }
  1559. }
  1560. row = row.getNextSiblingElement();
  1561. }
  1562. reapplyRowWidths();
  1563. }
  1564. private double getCalculatedColumnWidthWithColspan(final Element cell,
  1565. final int columnIndex) {
  1566. final int colspan = cell.getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  1567. Range spannedColumns = Range.withLength(columnIndex, colspan);
  1568. /*
  1569. * Since browsers don't explode with overflowing colspans, escalator
  1570. * shouldn't either.
  1571. */
  1572. if (spannedColumns.getEnd() > columnConfiguration
  1573. .getColumnCount()) {
  1574. spannedColumns = Range.between(columnIndex,
  1575. columnConfiguration.getColumnCount());
  1576. }
  1577. return columnConfiguration
  1578. .getCalculatedColumnsWidth(spannedColumns);
  1579. }
  1580. /**
  1581. * Applies the total length of the columns to each row element.
  1582. * <p>
  1583. * <em>Note:</em> In contrast to {@link #reapplyColumnWidths()}, this
  1584. * method only modifies the width of the {@code
  1585. *
  1586. <tr>
  1587. * } element, not the cells within.
  1588. */
  1589. protected void reapplyRowWidths() {
  1590. double rowWidth = columnConfiguration.calculateRowWidth();
  1591. if (rowWidth < 0) {
  1592. return;
  1593. }
  1594. Element row = root.getFirstChildElement();
  1595. while (row != null) {
  1596. // IF there is a rounding error when summing the columns, we
  1597. // need to round the tr width up to ensure that columns fit and
  1598. // do not wrap
  1599. // E.g.122.95+123.25+103.75+209.25+83.52+88.57+263.45+131.21+126.85+113.13=1365.9299999999998
  1600. // For this we must set 1365.93 or the last column will wrap
  1601. row.getStyle().setWidth(WidgetUtil.roundSizeUp(rowWidth),
  1602. Unit.PX);
  1603. row = row.getNextSiblingElement();
  1604. }
  1605. }
  1606. /**
  1607. * The primary style name for the container.
  1608. *
  1609. * @param primaryStyleName
  1610. * the style name to use as prefix for all row and cell style
  1611. * names.
  1612. */
  1613. protected void setStylePrimaryName(String primaryStyleName) {
  1614. String oldStyle = getStylePrimaryName();
  1615. if (SharedUtil.equals(oldStyle, primaryStyleName)) {
  1616. return;
  1617. }
  1618. this.primaryStyleName = primaryStyleName;
  1619. // Update already rendered rows and cells
  1620. Element row = root.getRows().getItem(0);
  1621. while (row != null) {
  1622. UIObject.setStylePrimaryName(row, primaryStyleName + "-row");
  1623. Element cell = TableRowElement.as(row).getCells().getItem(0);
  1624. while (cell != null) {
  1625. assert TableCellElement.is(cell);
  1626. UIObject.setStylePrimaryName(cell,
  1627. primaryStyleName + "-cell");
  1628. cell = cell.getNextSiblingElement();
  1629. }
  1630. row = row.getNextSiblingElement();
  1631. }
  1632. }
  1633. /**
  1634. * Returns the primary style name of the container.
  1635. *
  1636. * @return The primary style name or <code>null</code> if not set.
  1637. */
  1638. protected String getStylePrimaryName() {
  1639. return primaryStyleName;
  1640. }
  1641. @Override
  1642. public void setDefaultRowHeight(double px)
  1643. throws IllegalArgumentException {
  1644. if (px < 1) {
  1645. throw new IllegalArgumentException(
  1646. "Height must be positive. " + px + " was given.");
  1647. }
  1648. defaultRowHeightShouldBeAutodetected = false;
  1649. defaultRowHeight = px;
  1650. reapplyDefaultRowHeights();
  1651. }
  1652. @Override
  1653. public double getDefaultRowHeight() {
  1654. return defaultRowHeight;
  1655. }
  1656. /**
  1657. * The default height of rows has (most probably) changed.
  1658. * <p>
  1659. * Make sure that the displayed rows with a default height are updated
  1660. * in height and top position.
  1661. * <p>
  1662. * <em>Note:</em>This implementation should not call
  1663. * {@link Escalator#recalculateElementSizes()} - it is done by the
  1664. * discretion of the caller of this method.
  1665. */
  1666. protected abstract void reapplyDefaultRowHeights();
  1667. protected void reapplyRowHeight(final TableRowElement tr,
  1668. final double heightPx) {
  1669. assert heightPx >= 0 : "Height must not be negative";
  1670. Element cellElem = tr.getFirstChildElement();
  1671. while (cellElem != null) {
  1672. cellElem.getStyle().setHeight(heightPx, Unit.PX);
  1673. cellElem = cellElem.getNextSiblingElement();
  1674. }
  1675. /*
  1676. * no need to apply height to tr-element, it'll be resized
  1677. * implicitly.
  1678. */
  1679. }
  1680. protected void setRowPosition(final TableRowElement tr, final int x,
  1681. final double y) {
  1682. positions.set(tr, x, y);
  1683. }
  1684. /**
  1685. * Returns <em>the assigned</em> top position for the given element.
  1686. * <p>
  1687. * <em>Note:</em> This method does not calculate what a row's top
  1688. * position should be. It just returns an assigned value, correct or
  1689. * not.
  1690. *
  1691. * @param tr
  1692. * the table row element to measure
  1693. * @return the current top position for {@code tr}
  1694. * @see BodyRowContainerImpl#getRowTop(int)
  1695. */
  1696. protected double getRowTop(final TableRowElement tr) {
  1697. return positions.getTop(tr);
  1698. }
  1699. protected void removeRowPosition(TableRowElement tr) {
  1700. positions.remove(tr);
  1701. }
  1702. public void autodetectRowHeightLater() {
  1703. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  1704. @Override
  1705. public void execute() {
  1706. if (defaultRowHeightShouldBeAutodetected && isAttached()) {
  1707. autodetectRowHeightNow();
  1708. defaultRowHeightShouldBeAutodetected = false;
  1709. }
  1710. }
  1711. });
  1712. }
  1713. private void fireRowHeightChangedEventFinally() {
  1714. if (!rowHeightChangedEventFired) {
  1715. rowHeightChangedEventFired = true;
  1716. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  1717. @Override
  1718. public void execute() {
  1719. fireEvent(new RowHeightChangedEvent());
  1720. rowHeightChangedEventFired = false;
  1721. }
  1722. });
  1723. }
  1724. }
  1725. public void autodetectRowHeightNow() {
  1726. if (!isAttached()) {
  1727. // Run again when attached
  1728. defaultRowHeightShouldBeAutodetected = true;
  1729. return;
  1730. }
  1731. final double oldRowHeight = defaultRowHeight;
  1732. final Element detectionTr = DOM.createTR();
  1733. detectionTr.setClassName(getStylePrimaryName() + "-row");
  1734. final Element cellElem = DOM.createElement(getCellElementTagName());
  1735. cellElem.setClassName(getStylePrimaryName() + "-cell");
  1736. cellElem.setInnerText("Ij");
  1737. detectionTr.appendChild(cellElem);
  1738. root.appendChild(detectionTr);
  1739. double boundingHeight = WidgetUtil
  1740. .getRequiredHeightBoundingClientRectDouble(cellElem);
  1741. defaultRowHeight = Math.max(1.0d, boundingHeight);
  1742. root.removeChild(detectionTr);
  1743. if (root.hasChildNodes()) {
  1744. reapplyDefaultRowHeights();
  1745. applyHeightByRows();
  1746. }
  1747. if (oldRowHeight != defaultRowHeight) {
  1748. fireRowHeightChangedEventFinally();
  1749. }
  1750. }
  1751. @Override
  1752. public Cell getCell(final Element element) {
  1753. if (element == null) {
  1754. throw new IllegalArgumentException("Element cannot be null");
  1755. }
  1756. /*
  1757. * Ensure that element is not root nor the direct descendant of root
  1758. * (a row) and ensure the element is inside the dom hierarchy of the
  1759. * root element. If not, return.
  1760. */
  1761. if (root == element || element.getParentElement() == root
  1762. || !root.isOrHasChild(element)) {
  1763. return null;
  1764. }
  1765. /*
  1766. * Ensure element is the cell element by iterating up the DOM
  1767. * hierarchy until reaching cell element.
  1768. */
  1769. Element cellElementCandidate = element;
  1770. while (cellElementCandidate.getParentElement()
  1771. .getParentElement() != root) {
  1772. cellElementCandidate = cellElementCandidate.getParentElement();
  1773. }
  1774. final TableCellElement cellElement = TableCellElement
  1775. .as(cellElementCandidate);
  1776. // Find dom column
  1777. int domColumnIndex = -1;
  1778. for (Element e = cellElement; e != null; e = e
  1779. .getPreviousSiblingElement()) {
  1780. domColumnIndex++;
  1781. }
  1782. // Find dom row
  1783. int domRowIndex = -1;
  1784. for (Element e = cellElement.getParentElement(); e != null; e = e
  1785. .getPreviousSiblingElement()) {
  1786. domRowIndex++;
  1787. }
  1788. return new Cell(domRowIndex, domColumnIndex, cellElement);
  1789. }
  1790. double measureCellWidth(TableCellElement cell, boolean withContent) {
  1791. /*
  1792. * To get the actual width of the contents, we need to get the cell
  1793. * content without any hardcoded height or width.
  1794. *
  1795. * But we don't want to modify the existing column, because that
  1796. * might trigger some unnecessary listeners and whatnot. So,
  1797. * instead, we make a deep clone of that cell, but without any
  1798. * explicit dimensions, and measure that instead.
  1799. */
  1800. TableCellElement cellClone = TableCellElement
  1801. .as((Element) cell.cloneNode(withContent));
  1802. cellClone.getStyle().clearHeight();
  1803. cellClone.getStyle().clearWidth();
  1804. cell.getParentElement().insertBefore(cellClone, cell);
  1805. double requiredWidth = WidgetUtil
  1806. .getRequiredWidthBoundingClientRectDouble(cellClone);
  1807. if (BrowserInfo.get().isIE()) {
  1808. /*
  1809. * IE browsers have some issues with subpixels. Occasionally
  1810. * content is overflown even if not necessary. Increase the
  1811. * counted required size by 0.01 just to be on the safe side.
  1812. */
  1813. requiredWidth += 0.01;
  1814. }
  1815. cellClone.removeFromParent();
  1816. return requiredWidth;
  1817. }
  1818. /**
  1819. * Gets the minimum width needed to display the cell properly.
  1820. *
  1821. * @param colIndex
  1822. * index of column to measure
  1823. * @param withContent
  1824. * <code>true</code> if content is taken into account,
  1825. * <code>false</code> if not
  1826. * @return cell width needed for displaying correctly
  1827. */
  1828. double measureMinCellWidth(int colIndex, boolean withContent) {
  1829. assert isAttached() : "Can't measure max width of cell, since Escalator is not attached to the DOM.";
  1830. double minCellWidth = -1;
  1831. NodeList<TableRowElement> rows = root.getRows();
  1832. for (int row = 0; row < rows.getLength(); row++) {
  1833. TableCellElement cell = rows.getItem(row).getCells()
  1834. .getItem(colIndex);
  1835. if (cell != null && !cellIsPartOfSpan(cell)) {
  1836. double cellWidth = measureCellWidth(cell, withContent);
  1837. minCellWidth = Math.max(minCellWidth, cellWidth);
  1838. }
  1839. }
  1840. return minCellWidth;
  1841. }
  1842. private boolean cellIsPartOfSpan(TableCellElement cell) {
  1843. boolean cellHasColspan = cell.getColSpan() > 1;
  1844. boolean cellIsHidden = Display.NONE.getCssName()
  1845. .equals(cell.getStyle().getDisplay());
  1846. return cellHasColspan || cellIsHidden;
  1847. }
  1848. void refreshColumns(int index, int numberOfColumns) {
  1849. if (getRowCount() > 0) {
  1850. Range rowRange = Range.withLength(0, getRowCount());
  1851. Range colRange = Range.withLength(index, numberOfColumns);
  1852. refreshCells(rowRange, colRange);
  1853. }
  1854. }
  1855. /**
  1856. * The height of this table section.
  1857. * <p>
  1858. * Note that {@link Escalator#getBody() the body} will calculate its
  1859. * height, while the others will return a precomputed value.
  1860. *
  1861. * @since 7.5.0
  1862. *
  1863. * @return the height of this table section
  1864. */
  1865. protected abstract double getHeightOfSection();
  1866. /**
  1867. * Gets the logical row index for the given table row element.
  1868. *
  1869. * @param tr
  1870. * the table row element inside this container
  1871. * @return the logical index of the given element
  1872. */
  1873. public int getLogicalRowIndex(final TableRowElement tr) {
  1874. return tr.getSectionRowIndex();
  1875. };
  1876. }
  1877. private abstract class AbstractStaticRowContainer
  1878. extends AbstractRowContainer {
  1879. /** The height of the combined rows in the DOM. Never negative. */
  1880. private double heightOfSection = 0;
  1881. public AbstractStaticRowContainer(
  1882. final TableSectionElement headElement) {
  1883. super(headElement);
  1884. }
  1885. @Override
  1886. public int getDomRowCount() {
  1887. return root.getChildCount();
  1888. }
  1889. @Override
  1890. protected void paintRemoveRows(final int index,
  1891. final int numberOfRows) {
  1892. for (int i = index; i < index + numberOfRows; i++) {
  1893. final TableRowElement tr = root.getRows().getItem(index);
  1894. paintRemoveRow(tr, index);
  1895. }
  1896. recalculateSectionHeight();
  1897. }
  1898. @Override
  1899. protected TableRowElement getTrByVisualIndex(final int index)
  1900. throws IndexOutOfBoundsException {
  1901. if (index >= 0 && index < root.getChildCount()) {
  1902. return root.getRows().getItem(index);
  1903. } else {
  1904. throw new IndexOutOfBoundsException(
  1905. "No such visual index: " + index);
  1906. }
  1907. }
  1908. @Override
  1909. public void insertRows(int index, int numberOfRows) {
  1910. super.insertRows(index, numberOfRows);
  1911. recalculateElementSizes();
  1912. applyHeightByRows();
  1913. }
  1914. @Override
  1915. public void removeRows(int index, int numberOfRows) {
  1916. /*
  1917. * While the rows in a static section are removed, the scrollbar is
  1918. * temporarily shrunk and then re-expanded. This leads to the fact
  1919. * that the scroll position is scooted up a bit. This means that we
  1920. * need to reset the position here.
  1921. *
  1922. * If Escalator, at some point, gets a JIT evaluation functionality,
  1923. * this re-setting is a strong candidate for removal.
  1924. */
  1925. double oldScrollPos = verticalScrollbar.getScrollPos();
  1926. super.removeRows(index, numberOfRows);
  1927. recalculateElementSizes();
  1928. applyHeightByRows();
  1929. verticalScrollbar.setScrollPos(oldScrollPos);
  1930. }
  1931. @Override
  1932. protected void reapplyDefaultRowHeights() {
  1933. if (root.getChildCount() == 0) {
  1934. return;
  1935. }
  1936. Profiler.enter(
  1937. "Escalator.AbstractStaticRowContainer.reapplyDefaultRowHeights");
  1938. Element tr = root.getRows().getItem(0);
  1939. while (tr != null) {
  1940. reapplyRowHeight(TableRowElement.as(tr), getDefaultRowHeight());
  1941. tr = tr.getNextSiblingElement();
  1942. }
  1943. /*
  1944. * Because all rows are immediately displayed in the static row
  1945. * containers, the section's overall height has most probably
  1946. * changed.
  1947. */
  1948. recalculateSectionHeight();
  1949. Profiler.leave(
  1950. "Escalator.AbstractStaticRowContainer.reapplyDefaultRowHeights");
  1951. }
  1952. @Override
  1953. protected void recalculateSectionHeight() {
  1954. Profiler.enter(
  1955. "Escalator.AbstractStaticRowContainer.recalculateSectionHeight");
  1956. double newHeight = calculateTotalRowHeight();
  1957. if (newHeight != heightOfSection) {
  1958. heightOfSection = newHeight;
  1959. sectionHeightCalculated();
  1960. /*
  1961. * We need to update the scrollbar dimension at this point. If
  1962. * we are scrolled too far down and the static section shrinks,
  1963. * the body will try to render rows that don't exist during
  1964. * body.verifyEscalatorCount. This is because the logical row
  1965. * indices are calculated from the scrollbar position.
  1966. */
  1967. verticalScrollbar.setOffsetSize(
  1968. heightOfEscalator - header.getHeightOfSection()
  1969. - footer.getHeightOfSection());
  1970. body.verifyEscalatorCount();
  1971. body.spacerContainer.updateSpacerDecosVisibility();
  1972. }
  1973. Profiler.leave(
  1974. "Escalator.AbstractStaticRowContainer.recalculateSectionHeight");
  1975. }
  1976. /**
  1977. * Informs the row container that the height of its respective table
  1978. * section has changed.
  1979. * <p>
  1980. * These calculations might affect some layouting logic, such as the
  1981. * body is being offset by the footer, the footer needs to be readjusted
  1982. * according to its height, and so on.
  1983. * <p>
  1984. * A table section is either header, body or footer.
  1985. */
  1986. protected abstract void sectionHeightCalculated();
  1987. @Override
  1988. protected void refreshCells(Range logicalRowRange, Range colRange) {
  1989. assertArgumentsAreValidAndWithinRange(logicalRowRange.getStart(),
  1990. logicalRowRange.length());
  1991. if (!isAttached()) {
  1992. return;
  1993. }
  1994. Profiler.enter("Escalator.AbstractStaticRowContainer.refreshCells");
  1995. if (hasColumnAndRowData()) {
  1996. for (int row = logicalRowRange.getStart(); row < logicalRowRange
  1997. .getEnd(); row++) {
  1998. final TableRowElement tr = getTrByVisualIndex(row);
  1999. refreshRow(tr, row, colRange);
  2000. }
  2001. }
  2002. Profiler.leave("Escalator.AbstractStaticRowContainer.refreshCells");
  2003. }
  2004. @Override
  2005. protected void paintInsertRows(int visualIndex, int numberOfRows) {
  2006. paintInsertStaticRows(visualIndex, numberOfRows);
  2007. }
  2008. @Override
  2009. protected boolean rowCanBeFrozen(TableRowElement tr) {
  2010. assert root.isOrHasChild(
  2011. tr) : "Row does not belong to this table section";
  2012. return true;
  2013. }
  2014. @Override
  2015. protected double getHeightOfSection() {
  2016. return Math.max(0, heightOfSection);
  2017. }
  2018. }
  2019. private class HeaderRowContainer extends AbstractStaticRowContainer {
  2020. public HeaderRowContainer(final TableSectionElement headElement) {
  2021. super(headElement);
  2022. }
  2023. @Override
  2024. protected void sectionHeightCalculated() {
  2025. double heightOfSection = getHeightOfSection();
  2026. bodyElem.getStyle().setMarginTop(heightOfSection, Unit.PX);
  2027. spacerDecoContainer.getStyle().setMarginTop(heightOfSection,
  2028. Unit.PX);
  2029. verticalScrollbar.getElement().getStyle().setTop(heightOfSection,
  2030. Unit.PX);
  2031. headerDeco.getStyle().setHeight(heightOfSection, Unit.PX);
  2032. }
  2033. @Override
  2034. protected String getCellElementTagName() {
  2035. return "th";
  2036. }
  2037. @Override
  2038. public void setStylePrimaryName(String primaryStyleName) {
  2039. super.setStylePrimaryName(primaryStyleName);
  2040. UIObject.setStylePrimaryName(root, primaryStyleName + "-header");
  2041. }
  2042. }
  2043. private class FooterRowContainer extends AbstractStaticRowContainer {
  2044. public FooterRowContainer(final TableSectionElement footElement) {
  2045. super(footElement);
  2046. }
  2047. @Override
  2048. public void setStylePrimaryName(String primaryStyleName) {
  2049. super.setStylePrimaryName(primaryStyleName);
  2050. UIObject.setStylePrimaryName(root, primaryStyleName + "-footer");
  2051. }
  2052. @Override
  2053. protected String getCellElementTagName() {
  2054. return "td";
  2055. }
  2056. @Override
  2057. protected void sectionHeightCalculated() {
  2058. double headerHeight = header.getHeightOfSection();
  2059. double footerHeight = footer.getHeightOfSection();
  2060. int vscrollHeight = (int) Math
  2061. .floor(heightOfEscalator - headerHeight - footerHeight);
  2062. final boolean horizontalScrollbarNeeded = columnConfiguration
  2063. .calculateRowWidth() > widthOfEscalator;
  2064. if (horizontalScrollbarNeeded) {
  2065. vscrollHeight -= horizontalScrollbar.getScrollbarThickness();
  2066. }
  2067. footerDeco.getStyle().setHeight(footer.getHeightOfSection(),
  2068. Unit.PX);
  2069. verticalScrollbar.setOffsetSize(vscrollHeight);
  2070. }
  2071. }
  2072. private class BodyRowContainerImpl extends AbstractRowContainer
  2073. implements BodyRowContainer {
  2074. /*
  2075. * TODO [[optimize]]: check whether a native JsArray might be faster
  2076. * than LinkedList
  2077. */
  2078. /**
  2079. * The order in which row elements are rendered visually in the browser,
  2080. * with the help of CSS tricks. Usually has nothing to do with the DOM
  2081. * order.
  2082. *
  2083. * @see #sortDomElements()
  2084. */
  2085. private final LinkedList<TableRowElement> visualRowOrder = new LinkedList<TableRowElement>();
  2086. /**
  2087. * The logical index of the topmost row.
  2088. *
  2089. * @deprecated Use the accessors {@link #setTopRowLogicalIndex(int)},
  2090. * {@link #updateTopRowLogicalIndex(int)} and
  2091. * {@link #getTopRowLogicalIndex()} instead
  2092. */
  2093. @Deprecated
  2094. private int topRowLogicalIndex = 0;
  2095. private void setTopRowLogicalIndex(int topRowLogicalIndex) {
  2096. if (LogConfiguration.loggingIsEnabled(Level.INFO)) {
  2097. Logger.getLogger("Escalator.BodyRowContainer")
  2098. .fine("topRowLogicalIndex: " + this.topRowLogicalIndex
  2099. + " -> " + topRowLogicalIndex);
  2100. }
  2101. assert topRowLogicalIndex >= 0 : "topRowLogicalIndex became negative (top left cell contents: "
  2102. + visualRowOrder.getFirst().getCells().getItem(0)
  2103. .getInnerText()
  2104. + ") ";
  2105. /*
  2106. * if there's a smart way of evaluating and asserting the max index,
  2107. * this would be a nice place to put it. I haven't found out an
  2108. * effective and generic solution.
  2109. */
  2110. this.topRowLogicalIndex = topRowLogicalIndex;
  2111. }
  2112. public int getTopRowLogicalIndex() {
  2113. return topRowLogicalIndex;
  2114. }
  2115. private void updateTopRowLogicalIndex(int diff) {
  2116. setTopRowLogicalIndex(topRowLogicalIndex + diff);
  2117. }
  2118. private class DeferredDomSorter {
  2119. private static final int SORT_DELAY_MILLIS = 50;
  2120. // as it happens, 3 frames = 50ms @ 60fps.
  2121. private static final int REQUIRED_FRAMES_PASSED = 3;
  2122. private final AnimationCallback frameCounter = new AnimationCallback() {
  2123. @Override
  2124. public void execute(double timestamp) {
  2125. framesPassed++;
  2126. boolean domWasSorted = sortIfConditionsMet();
  2127. if (!domWasSorted) {
  2128. animationHandle = AnimationScheduler.get()
  2129. .requestAnimationFrame(this);
  2130. } else {
  2131. waiting = false;
  2132. }
  2133. }
  2134. };
  2135. private int framesPassed;
  2136. private double startTime;
  2137. private AnimationHandle animationHandle;
  2138. /** <code>true</code> if a sort is scheduled */
  2139. public boolean waiting = false;
  2140. public void reschedule() {
  2141. waiting = true;
  2142. resetConditions();
  2143. animationHandle = AnimationScheduler.get()
  2144. .requestAnimationFrame(frameCounter);
  2145. }
  2146. private boolean sortIfConditionsMet() {
  2147. boolean enoughFramesHavePassed = framesPassed >= REQUIRED_FRAMES_PASSED;
  2148. boolean enoughTimeHasPassed = (Duration.currentTimeMillis()
  2149. - startTime) >= SORT_DELAY_MILLIS;
  2150. boolean notTouchActivity = !scroller.touchHandlerBundle.touching;
  2151. boolean conditionsMet = enoughFramesHavePassed
  2152. && enoughTimeHasPassed && notTouchActivity;
  2153. if (conditionsMet) {
  2154. resetConditions();
  2155. sortDomElements();
  2156. }
  2157. return conditionsMet;
  2158. }
  2159. private void resetConditions() {
  2160. if (animationHandle != null) {
  2161. animationHandle.cancel();
  2162. animationHandle = null;
  2163. }
  2164. startTime = Duration.currentTimeMillis();
  2165. framesPassed = 0;
  2166. }
  2167. }
  2168. private DeferredDomSorter domSorter = new DeferredDomSorter();
  2169. private final SpacerContainer spacerContainer = new SpacerContainer();
  2170. public BodyRowContainerImpl(final TableSectionElement bodyElement) {
  2171. super(bodyElement);
  2172. }
  2173. @Override
  2174. public void insertRows(int index, int numberOfRows) {
  2175. super.insertRows(index, numberOfRows);
  2176. if (heightMode == HeightMode.UNDEFINED) {
  2177. heightByRows = getRowCount();
  2178. }
  2179. }
  2180. @Override
  2181. public void removeRows(int index, int numberOfRows) {
  2182. super.removeRows(index, numberOfRows);
  2183. if (heightMode == HeightMode.UNDEFINED) {
  2184. heightByRows = getRowCount();
  2185. }
  2186. }
  2187. @Override
  2188. public void setStylePrimaryName(String primaryStyleName) {
  2189. super.setStylePrimaryName(primaryStyleName);
  2190. UIObject.setStylePrimaryName(root, primaryStyleName + "-body");
  2191. spacerContainer.setStylePrimaryName(primaryStyleName);
  2192. }
  2193. public void updateEscalatorRowsOnScroll() {
  2194. if (visualRowOrder.isEmpty()) {
  2195. return;
  2196. }
  2197. boolean rowsWereMoved = false;
  2198. final double topElementPosition;
  2199. final double nextRowBottomOffset;
  2200. SpacerContainer.SpacerImpl topSpacer = spacerContainer
  2201. .getSpacer(getTopRowLogicalIndex() - 1);
  2202. if (topSpacer != null) {
  2203. topElementPosition = topSpacer.getTop();
  2204. nextRowBottomOffset = topSpacer.getHeight()
  2205. + getDefaultRowHeight();
  2206. } else {
  2207. topElementPosition = getRowTop(visualRowOrder.getFirst());
  2208. nextRowBottomOffset = getDefaultRowHeight();
  2209. }
  2210. // TODO [[mpixscroll]]
  2211. final double scrollTop = tBodyScrollTop;
  2212. final double viewportOffset = topElementPosition - scrollTop;
  2213. /*
  2214. * TODO [[optimize]] this if-else can most probably be refactored
  2215. * into a neater block of code
  2216. */
  2217. if (viewportOffset > 0) {
  2218. // there's empty room on top
  2219. double rowPx = getRowHeightsSumBetweenPx(scrollTop,
  2220. topElementPosition);
  2221. int originalRowsToMove = (int) Math
  2222. .ceil(rowPx / getDefaultRowHeight());
  2223. int rowsToMove = Math.min(originalRowsToMove,
  2224. visualRowOrder.size());
  2225. final int end = visualRowOrder.size();
  2226. final int start = end - rowsToMove;
  2227. final int logicalRowIndex = getLogicalRowIndex(scrollTop);
  2228. moveAndUpdateEscalatorRows(Range.between(start, end), 0,
  2229. logicalRowIndex);
  2230. setTopRowLogicalIndex(logicalRowIndex);
  2231. rowsWereMoved = true;
  2232. } else if (viewportOffset + nextRowBottomOffset <= 0) {
  2233. /*
  2234. * the viewport has been scrolled more than the topmost visual
  2235. * row.
  2236. */
  2237. double rowPx = getRowHeightsSumBetweenPx(topElementPosition,
  2238. scrollTop);
  2239. int originalRowsToMove = (int) (rowPx / getDefaultRowHeight());
  2240. int rowsToMove = Math.min(originalRowsToMove,
  2241. visualRowOrder.size());
  2242. int logicalRowIndex;
  2243. if (rowsToMove < visualRowOrder.size()) {
  2244. /*
  2245. * We scroll so little that we can just keep adding the rows
  2246. * below the current escalator
  2247. */
  2248. logicalRowIndex = getLogicalRowIndex(
  2249. visualRowOrder.getLast()) + 1;
  2250. } else {
  2251. /*
  2252. * Since we're moving all escalator rows, we need to
  2253. * calculate the first logical row index from the scroll
  2254. * position.
  2255. */
  2256. logicalRowIndex = getLogicalRowIndex(scrollTop);
  2257. }
  2258. /*
  2259. * Since we're moving the viewport downwards, the visual index
  2260. * is always at the bottom. Note: Due to how
  2261. * moveAndUpdateEscalatorRows works, this will work out even if
  2262. * we move all the rows, and try to place them "at the end".
  2263. */
  2264. final int targetVisualIndex = visualRowOrder.size();
  2265. // make sure that we don't move rows over the data boundary
  2266. boolean aRowWasLeftBehind = false;
  2267. if (logicalRowIndex + rowsToMove > getRowCount()) {
  2268. /*
  2269. * TODO [[spacer]]: with constant row heights, there's
  2270. * always exactly one row that will be moved beyond the data
  2271. * source, when viewport is scrolled to the end. This,
  2272. * however, isn't guaranteed anymore once row heights start
  2273. * varying.
  2274. */
  2275. rowsToMove--;
  2276. aRowWasLeftBehind = true;
  2277. }
  2278. /*
  2279. * Make sure we don't scroll beyond the row content. This can
  2280. * happen if we have spacers for the last rows.
  2281. */
  2282. rowsToMove = Math.max(0,
  2283. Math.min(rowsToMove, getRowCount() - logicalRowIndex));
  2284. moveAndUpdateEscalatorRows(Range.between(0, rowsToMove),
  2285. targetVisualIndex, logicalRowIndex);
  2286. if (aRowWasLeftBehind) {
  2287. /*
  2288. * To keep visualRowOrder as a spatially contiguous block of
  2289. * rows, let's make sure that the one row we didn't move
  2290. * visually still stays with the pack.
  2291. */
  2292. final Range strayRow = Range.withOnly(0);
  2293. /*
  2294. * We cannot trust getLogicalRowIndex, because it hasn't yet
  2295. * been updated. But since we're leaving rows behind, it
  2296. * means we've scrolled to the bottom. So, instead, we
  2297. * simply count backwards from the end.
  2298. */
  2299. final int topLogicalIndex = getRowCount()
  2300. - visualRowOrder.size();
  2301. moveAndUpdateEscalatorRows(strayRow, 0, topLogicalIndex);
  2302. }
  2303. final int naiveNewLogicalIndex = getTopRowLogicalIndex()
  2304. + originalRowsToMove;
  2305. final int maxLogicalIndex = getRowCount()
  2306. - visualRowOrder.size();
  2307. setTopRowLogicalIndex(
  2308. Math.min(naiveNewLogicalIndex, maxLogicalIndex));
  2309. rowsWereMoved = true;
  2310. }
  2311. if (rowsWereMoved) {
  2312. fireRowVisibilityChangeEvent();
  2313. domSorter.reschedule();
  2314. }
  2315. }
  2316. private double getRowHeightsSumBetweenPx(double y1, double y2) {
  2317. assert y1 < y2 : "y1 must be smaller than y2";
  2318. double viewportPx = y2 - y1;
  2319. double spacerPx = spacerContainer.getSpacerHeightsSumBetweenPx(y1,
  2320. SpacerInclusionStrategy.PARTIAL, y2,
  2321. SpacerInclusionStrategy.PARTIAL);
  2322. return viewportPx - spacerPx;
  2323. }
  2324. private int getLogicalRowIndex(final double px) {
  2325. double rowPx = px - spacerContainer.getSpacerHeightsSumUntilPx(px);
  2326. return (int) (rowPx / getDefaultRowHeight());
  2327. }
  2328. @Override
  2329. protected void paintInsertRows(final int index,
  2330. final int numberOfRows) {
  2331. if (numberOfRows == 0) {
  2332. return;
  2333. }
  2334. spacerContainer.shiftSpacersByRows(index, numberOfRows);
  2335. /*
  2336. * TODO: this method should probably only add physical rows, and not
  2337. * populate them - let everything be populated as appropriate by the
  2338. * logic that follows.
  2339. *
  2340. * This also would lead to the fact that paintInsertRows wouldn't
  2341. * need to return anything.
  2342. */
  2343. final List<TableRowElement> addedRows = fillAndPopulateEscalatorRowsIfNeeded(
  2344. index, numberOfRows);
  2345. /*
  2346. * insertRows will always change the number of rows - update the
  2347. * scrollbar sizes.
  2348. */
  2349. scroller.recalculateScrollbarsForVirtualViewport();
  2350. final boolean addedRowsAboveCurrentViewport = index
  2351. * getDefaultRowHeight() < getScrollTop();
  2352. final boolean addedRowsBelowCurrentViewport = index
  2353. * getDefaultRowHeight() > getScrollTop()
  2354. + getHeightOfSection();
  2355. if (addedRowsAboveCurrentViewport) {
  2356. /*
  2357. * We need to tweak the virtual viewport (scroll handle
  2358. * positions, table "scroll position" and row locations), but
  2359. * without re-evaluating any rows.
  2360. */
  2361. final double yDelta = numberOfRows * getDefaultRowHeight();
  2362. moveViewportAndContent(yDelta);
  2363. updateTopRowLogicalIndex(numberOfRows);
  2364. } else if (addedRowsBelowCurrentViewport) {
  2365. // NOOP, we already recalculated scrollbars.
  2366. } else {
  2367. // some rows were added inside the current viewport
  2368. final int unupdatedLogicalStart = index + addedRows.size();
  2369. final int visualOffset = getLogicalRowIndex(
  2370. visualRowOrder.getFirst());
  2371. /*
  2372. * At this point, we have added new escalator rows, if so
  2373. * needed.
  2374. *
  2375. * If more rows were added than the new escalator rows can
  2376. * account for, we need to start to spin the escalator to update
  2377. * the remaining rows as well.
  2378. */
  2379. final int rowsStillNeeded = numberOfRows - addedRows.size();
  2380. if (rowsStillNeeded > 0) {
  2381. final Range unupdatedVisual = convertToVisual(
  2382. Range.withLength(unupdatedLogicalStart,
  2383. rowsStillNeeded));
  2384. final int end = getDomRowCount();
  2385. final int start = end - unupdatedVisual.length();
  2386. final int visualTargetIndex = unupdatedLogicalStart
  2387. - visualOffset;
  2388. moveAndUpdateEscalatorRows(Range.between(start, end),
  2389. visualTargetIndex, unupdatedLogicalStart);
  2390. // move the surrounding rows to their correct places.
  2391. double rowTop = (unupdatedLogicalStart + (end - start))
  2392. * getDefaultRowHeight();
  2393. // TODO: Get rid of this try/catch block by fixing the
  2394. // underlying issue. The reason for this erroneous behavior
  2395. // might be that Escalator actually works 'by mistake', and
  2396. // the order of operations is, in fact, wrong.
  2397. try {
  2398. final ListIterator<TableRowElement> i = visualRowOrder
  2399. .listIterator(
  2400. visualTargetIndex + (end - start));
  2401. int logicalRowIndexCursor = unupdatedLogicalStart;
  2402. while (i.hasNext()) {
  2403. rowTop += spacerContainer
  2404. .getSpacerHeight(logicalRowIndexCursor++);
  2405. final TableRowElement tr = i.next();
  2406. setRowPosition(tr, 0, rowTop);
  2407. rowTop += getDefaultRowHeight();
  2408. }
  2409. } catch (Exception e) {
  2410. Logger logger = getLogger();
  2411. logger.warning(
  2412. "Ignored out-of-bounds row element access");
  2413. logger.warning("Escalator state: start=" + start
  2414. + ", end=" + end + ", visualTargetIndex="
  2415. + visualTargetIndex + ", visualRowOrder.size()="
  2416. + visualRowOrder.size());
  2417. logger.warning(e.toString());
  2418. }
  2419. }
  2420. fireRowVisibilityChangeEvent();
  2421. sortDomElements();
  2422. }
  2423. }
  2424. /**
  2425. * Move escalator rows around, and make sure everything gets
  2426. * appropriately repositioned and repainted.
  2427. *
  2428. * @param visualSourceRange
  2429. * the range of rows to move to a new place
  2430. * @param visualTargetIndex
  2431. * the visual index where the rows will be placed to
  2432. * @param logicalTargetIndex
  2433. * the logical index to be assigned to the first moved row
  2434. */
  2435. private void moveAndUpdateEscalatorRows(final Range visualSourceRange,
  2436. final int visualTargetIndex, final int logicalTargetIndex)
  2437. throws IllegalArgumentException {
  2438. if (visualSourceRange.isEmpty()) {
  2439. return;
  2440. }
  2441. assert visualSourceRange.getStart() >= 0 : "Visual source start "
  2442. + "must be 0 or greater (was "
  2443. + visualSourceRange.getStart() + ")";
  2444. assert logicalTargetIndex >= 0 : "Logical target must be 0 or "
  2445. + "greater (was " + logicalTargetIndex + ")";
  2446. assert visualTargetIndex >= 0 : "Visual target must be 0 or greater (was "
  2447. + visualTargetIndex + ")";
  2448. assert visualTargetIndex <= getDomRowCount() : "Visual target "
  2449. + "must not be greater than the number of escalator rows (was "
  2450. + visualTargetIndex + ", escalator rows " + getDomRowCount()
  2451. + ")";
  2452. assert logicalTargetIndex
  2453. + visualSourceRange.length() <= getRowCount() : "Logical "
  2454. + "target leads to rows outside of the data range ("
  2455. + Range.withLength(logicalTargetIndex,
  2456. visualSourceRange.length())
  2457. + " goes beyond "
  2458. + Range.withLength(0, getRowCount()) + ")";
  2459. /*
  2460. * Since we move a range into another range, the indices might move
  2461. * about. Having 10 rows, if we move 0..1 to index 10 (to the end of
  2462. * the collection), the target range will end up being 8..9, instead
  2463. * of 10..11.
  2464. *
  2465. * This applies only if we move elements forward in the collection,
  2466. * not backward.
  2467. */
  2468. final int adjustedVisualTargetIndex;
  2469. if (visualSourceRange.getStart() < visualTargetIndex) {
  2470. adjustedVisualTargetIndex = visualTargetIndex
  2471. - visualSourceRange.length();
  2472. } else {
  2473. adjustedVisualTargetIndex = visualTargetIndex;
  2474. }
  2475. if (visualSourceRange.getStart() != adjustedVisualTargetIndex) {
  2476. /*
  2477. * Reorder the rows to their correct places within
  2478. * visualRowOrder (unless rows are moved back to their original
  2479. * places)
  2480. */
  2481. /*
  2482. * TODO [[optimize]]: move whichever set is smaller: the ones
  2483. * explicitly moved, or the others. So, with 10 escalator rows,
  2484. * if we are asked to move idx[0..8] to the end of the list,
  2485. * it's faster to just move idx[9] to the beginning.
  2486. */
  2487. final List<TableRowElement> removedRows = new ArrayList<TableRowElement>(
  2488. visualSourceRange.length());
  2489. for (int i = 0; i < visualSourceRange.length(); i++) {
  2490. final TableRowElement tr = visualRowOrder
  2491. .remove(visualSourceRange.getStart());
  2492. removedRows.add(tr);
  2493. }
  2494. visualRowOrder.addAll(adjustedVisualTargetIndex, removedRows);
  2495. }
  2496. { // Refresh the contents of the affected rows
  2497. final ListIterator<TableRowElement> iter = visualRowOrder
  2498. .listIterator(adjustedVisualTargetIndex);
  2499. for (int logicalIndex = logicalTargetIndex; logicalIndex < logicalTargetIndex
  2500. + visualSourceRange.length(); logicalIndex++) {
  2501. final TableRowElement tr = iter.next();
  2502. refreshRow(tr, logicalIndex);
  2503. }
  2504. }
  2505. { // Reposition the rows that were moved
  2506. double newRowTop = getRowTop(logicalTargetIndex);
  2507. final ListIterator<TableRowElement> iter = visualRowOrder
  2508. .listIterator(adjustedVisualTargetIndex);
  2509. for (int i = 0; i < visualSourceRange.length(); i++) {
  2510. final TableRowElement tr = iter.next();
  2511. setRowPosition(tr, 0, newRowTop);
  2512. newRowTop += getDefaultRowHeight();
  2513. newRowTop += spacerContainer
  2514. .getSpacerHeight(logicalTargetIndex + i);
  2515. }
  2516. }
  2517. }
  2518. /**
  2519. * Adjust the scroll position and move the contained rows.
  2520. * <p>
  2521. * The difference between using this method and simply scrolling is that
  2522. * this method "takes the rows and spacers with it" and renders them
  2523. * appropriately. The viewport may be scrolled any arbitrary amount, and
  2524. * the contents are moved appropriately, but always snapped into a
  2525. * plausible place.
  2526. * <p>
  2527. * <dl>
  2528. * <dt>Example 1</dt>
  2529. * <dd>An Escalator with default row height 20px. Adjusting the scroll
  2530. * position with 7.5px will move the viewport 7.5px down, but leave the
  2531. * row where it is.</dd>
  2532. * <dt>Example 2</dt>
  2533. * <dd>An Escalator with default row height 20px. Adjusting the scroll
  2534. * position with 27.5px will move the viewport 27.5px down, and place
  2535. * the row at 20px.</dd>
  2536. * </dl>
  2537. *
  2538. * @param yDelta
  2539. * the delta of pixels by which to move the viewport and
  2540. * content. A positive value moves everything downwards,
  2541. * while a negative value moves everything upwards
  2542. */
  2543. public void moveViewportAndContent(final double yDelta) {
  2544. if (yDelta == 0) {
  2545. return;
  2546. }
  2547. double newTop = tBodyScrollTop + yDelta;
  2548. verticalScrollbar.setScrollPos(newTop);
  2549. final double defaultRowHeight = getDefaultRowHeight();
  2550. double rowPxDelta = yDelta - (yDelta % defaultRowHeight);
  2551. int rowIndexDelta = (int) (yDelta / defaultRowHeight);
  2552. if (!WidgetUtil.pixelValuesEqual(rowPxDelta, 0)) {
  2553. Collection<SpacerContainer.SpacerImpl> spacers = spacerContainer
  2554. .getSpacersAfterPx(tBodyScrollTop,
  2555. SpacerInclusionStrategy.PARTIAL);
  2556. for (SpacerContainer.SpacerImpl spacer : spacers) {
  2557. spacer.setPositionDiff(0, rowPxDelta);
  2558. spacer.setRowIndex(spacer.getRow() + rowIndexDelta);
  2559. }
  2560. for (TableRowElement tr : visualRowOrder) {
  2561. setRowPosition(tr, 0, getRowTop(tr) + rowPxDelta);
  2562. }
  2563. }
  2564. setBodyScrollPosition(tBodyScrollLeft, newTop);
  2565. }
  2566. /**
  2567. * Adds new physical escalator rows to the DOM at the given index if
  2568. * there's still a need for more escalator rows.
  2569. * <p>
  2570. * If Escalator already is at (or beyond) max capacity, this method does
  2571. * nothing to the DOM.
  2572. *
  2573. * @param index
  2574. * the index at which to add new escalator rows.
  2575. * <em>Note:</em>It is assumed that the index is both the
  2576. * visual index and the logical index.
  2577. * @param numberOfRows
  2578. * the number of rows to add at <code>index</code>
  2579. * @return a list of the added rows
  2580. */
  2581. private List<TableRowElement> fillAndPopulateEscalatorRowsIfNeeded(
  2582. final int index, final int numberOfRows) {
  2583. final int escalatorRowsStillFit = getMaxVisibleRowCount()
  2584. - getDomRowCount();
  2585. final int escalatorRowsNeeded = Math.min(numberOfRows,
  2586. escalatorRowsStillFit);
  2587. if (escalatorRowsNeeded > 0) {
  2588. final List<TableRowElement> addedRows = paintInsertStaticRows(
  2589. index, escalatorRowsNeeded);
  2590. visualRowOrder.addAll(index, addedRows);
  2591. double y = index * getDefaultRowHeight()
  2592. + spacerContainer.getSpacerHeightsSumUntilIndex(index);
  2593. for (int i = index; i < visualRowOrder.size(); i++) {
  2594. final TableRowElement tr;
  2595. if (i - index < addedRows.size()) {
  2596. tr = addedRows.get(i - index);
  2597. } else {
  2598. tr = visualRowOrder.get(i);
  2599. }
  2600. setRowPosition(tr, 0, y);
  2601. y += getDefaultRowHeight();
  2602. y += spacerContainer.getSpacerHeight(i);
  2603. }
  2604. return addedRows;
  2605. } else {
  2606. return Collections.emptyList();
  2607. }
  2608. }
  2609. private int getMaxVisibleRowCount() {
  2610. double heightOfSection = getHeightOfSection();
  2611. // By including the possibly shown scrollbar height, we get a
  2612. // consistent count and do not add/remove rows whenever a scrollbar
  2613. // is shown
  2614. heightOfSection += horizontalScrollbarDeco.getOffsetHeight();
  2615. double defaultRowHeight = getDefaultRowHeight();
  2616. final int maxVisibleRowCount = (int) Math
  2617. .ceil(heightOfSection / defaultRowHeight) + 1;
  2618. /*
  2619. * maxVisibleRowCount can become negative if the headers and footers
  2620. * start to overlap. This is a crazy situation, but Vaadin blinks
  2621. * the components a lot, so it's feasible.
  2622. */
  2623. return Math.max(0, maxVisibleRowCount);
  2624. }
  2625. @Override
  2626. protected void paintRemoveRows(final int index,
  2627. final int numberOfRows) {
  2628. if (numberOfRows == 0) {
  2629. return;
  2630. }
  2631. final Range viewportRange = getVisibleRowRange();
  2632. final Range removedRowsRange = Range.withLength(index,
  2633. numberOfRows);
  2634. /*
  2635. * Removing spacers as the very first step will correct the
  2636. * scrollbars and row offsets right away.
  2637. *
  2638. * TODO: actually, it kinda sounds like a Grid feature that a spacer
  2639. * would be associated with a particular row. Maybe it would be
  2640. * better to have a spacer separate from rows, and simply collapse
  2641. * them if they happen to end up on top of each other. This would
  2642. * probably make supporting the -1 row pretty easy, too.
  2643. */
  2644. spacerContainer.paintRemoveSpacers(removedRowsRange);
  2645. final Range[] partitions = removedRowsRange
  2646. .partitionWith(viewportRange);
  2647. final Range removedAbove = partitions[0];
  2648. final Range removedLogicalInside = partitions[1];
  2649. final Range removedVisualInside = convertToVisual(
  2650. removedLogicalInside);
  2651. /*
  2652. * TODO: extract the following if-block to a separate method. I'll
  2653. * leave this be inlined for now, to make linediff-based code
  2654. * reviewing easier. Probably will be moved in the following patch
  2655. * set.
  2656. */
  2657. /*
  2658. * Adjust scroll position in one of two scenarios:
  2659. *
  2660. * 1) Rows were removed above. Then we just need to adjust the
  2661. * scrollbar by the height of the removed rows.
  2662. *
  2663. * 2) There are no logical rows above, and at least the first (if
  2664. * not more) visual row is removed. Then we need to snap the scroll
  2665. * position to the first visible row (i.e. reset scroll position to
  2666. * absolute 0)
  2667. *
  2668. * The logic is optimized in such a way that the
  2669. * moveViewportAndContent is called only once, to avoid extra
  2670. * reflows, and thus the code might seem a bit obscure.
  2671. */
  2672. final boolean firstVisualRowIsRemoved = !removedVisualInside
  2673. .isEmpty() && removedVisualInside.getStart() == 0;
  2674. if (!removedAbove.isEmpty() || firstVisualRowIsRemoved) {
  2675. final double yDelta = removedAbove.length()
  2676. * getDefaultRowHeight();
  2677. final double firstLogicalRowHeight = getDefaultRowHeight();
  2678. final boolean removalScrollsToShowFirstLogicalRow = verticalScrollbar
  2679. .getScrollPos() - yDelta < firstLogicalRowHeight;
  2680. if (removedVisualInside.isEmpty()
  2681. && (!removalScrollsToShowFirstLogicalRow
  2682. || !firstVisualRowIsRemoved)) {
  2683. /*
  2684. * rows were removed from above the viewport, so all we need
  2685. * to do is to adjust the scroll position to account for the
  2686. * removed rows
  2687. */
  2688. moveViewportAndContent(-yDelta);
  2689. } else if (removalScrollsToShowFirstLogicalRow) {
  2690. /*
  2691. * It seems like we've removed all rows from above, and also
  2692. * into the current viewport. This means we'll need to even
  2693. * out the scroll position to exactly 0 (i.e. adjust by the
  2694. * current negative scrolltop, presto!), so that it isn't
  2695. * aligned funnily
  2696. */
  2697. moveViewportAndContent(-verticalScrollbar.getScrollPos());
  2698. }
  2699. }
  2700. // ranges evaluated, let's do things.
  2701. if (!removedVisualInside.isEmpty()) {
  2702. int escalatorRowCount = body.getDomRowCount();
  2703. /*
  2704. * remember: the rows have already been subtracted from the row
  2705. * count at this point
  2706. */
  2707. int rowsLeft = getRowCount();
  2708. if (rowsLeft < escalatorRowCount) {
  2709. int escalatorRowsToRemove = escalatorRowCount - rowsLeft;
  2710. for (int i = 0; i < escalatorRowsToRemove; i++) {
  2711. final TableRowElement tr = visualRowOrder
  2712. .remove(removedVisualInside.getStart());
  2713. paintRemoveRow(tr, index);
  2714. removeRowPosition(tr);
  2715. }
  2716. escalatorRowCount -= escalatorRowsToRemove;
  2717. /*
  2718. * Because we're removing escalator rows, we don't have
  2719. * anything to scroll by. Let's make sure the viewport is
  2720. * scrolled to top, to render any rows possibly left above.
  2721. */
  2722. body.setBodyScrollPosition(tBodyScrollLeft, 0);
  2723. /*
  2724. * We might have removed some rows from the middle, so let's
  2725. * make sure we're not left with any holes. Also remember:
  2726. * visualIndex == logicalIndex applies now.
  2727. */
  2728. final int dirtyRowsStart = removedLogicalInside.getStart();
  2729. double y = getRowTop(dirtyRowsStart);
  2730. for (int i = dirtyRowsStart; i < escalatorRowCount; i++) {
  2731. final TableRowElement tr = visualRowOrder.get(i);
  2732. setRowPosition(tr, 0, y);
  2733. y += getDefaultRowHeight();
  2734. y += spacerContainer.getSpacerHeight(i);
  2735. }
  2736. /*
  2737. * this is how many rows appeared into the viewport from
  2738. * below
  2739. */
  2740. final int rowsToUpdateDataOn = numberOfRows
  2741. - escalatorRowsToRemove;
  2742. final int start = Math.max(0,
  2743. escalatorRowCount - rowsToUpdateDataOn);
  2744. final int end = escalatorRowCount;
  2745. for (int i = start; i < end; i++) {
  2746. final TableRowElement tr = visualRowOrder.get(i);
  2747. refreshRow(tr, i);
  2748. }
  2749. } else {
  2750. // No escalator rows need to be removed.
  2751. /*
  2752. * Two things (or a combination thereof) can happen:
  2753. *
  2754. * 1) We're scrolled to the bottom, the last rows are
  2755. * removed. SOLUTION: moveAndUpdateEscalatorRows the
  2756. * bottommost rows, and place them at the top to be
  2757. * refreshed.
  2758. *
  2759. * 2) We're scrolled somewhere in the middle, arbitrary rows
  2760. * are removed. SOLUTION: moveAndUpdateEscalatorRows the
  2761. * removed rows, and place them at the bottom to be
  2762. * refreshed.
  2763. *
  2764. * Since a combination can also happen, we need to handle
  2765. * this in a smart way, all while avoiding
  2766. * double-refreshing.
  2767. */
  2768. final double contentBottom = getRowCount()
  2769. * getDefaultRowHeight();
  2770. final double viewportBottom = tBodyScrollTop
  2771. + getHeightOfSection();
  2772. if (viewportBottom <= contentBottom) {
  2773. /*
  2774. * We're in the middle of the row container, everything
  2775. * is added to the bottom
  2776. */
  2777. paintRemoveRowsAtMiddle(removedLogicalInside,
  2778. removedVisualInside, 0);
  2779. } else if (removedVisualInside.contains(0)
  2780. && numberOfRows >= visualRowOrder.size()) {
  2781. /*
  2782. * We're removing so many rows that the viewport is
  2783. * pushed up more than a screenful. This means we can
  2784. * simply scroll up and everything will work without a
  2785. * sweat.
  2786. */
  2787. double left = horizontalScrollbar.getScrollPos();
  2788. double top = contentBottom
  2789. - visualRowOrder.size() * getDefaultRowHeight();
  2790. setBodyScrollPosition(left, top);
  2791. Range allEscalatorRows = Range.withLength(0,
  2792. visualRowOrder.size());
  2793. int logicalTargetIndex = getRowCount()
  2794. - allEscalatorRows.length();
  2795. moveAndUpdateEscalatorRows(allEscalatorRows, 0,
  2796. logicalTargetIndex);
  2797. /*
  2798. * moveAndUpdateEscalatorRows recalculates the rows, but
  2799. * logical top row index bookkeeping is handled in this
  2800. * method.
  2801. *
  2802. * TODO: Redesign how to keep it easy to track this.
  2803. */
  2804. updateTopRowLogicalIndex(
  2805. -removedLogicalInside.length());
  2806. /*
  2807. * Scrolling the body to the correct location will be
  2808. * fixed automatically. Because the amount of rows is
  2809. * decreased, the viewport is pushed up as the scrollbar
  2810. * shrinks. So no need to do anything there.
  2811. *
  2812. * TODO [[optimize]]: This might lead to a double body
  2813. * refresh. Needs investigation.
  2814. */
  2815. } else if (contentBottom
  2816. + (numberOfRows * getDefaultRowHeight())
  2817. - viewportBottom < getDefaultRowHeight()) {
  2818. /*
  2819. * We're at the end of the row container, everything is
  2820. * added to the top.
  2821. */
  2822. /*
  2823. * FIXME [[spacer]]: above if-clause is coded to only
  2824. * work with default row heights - will not work with
  2825. * variable row heights
  2826. */
  2827. paintRemoveRowsAtBottom(removedLogicalInside,
  2828. removedVisualInside);
  2829. updateTopRowLogicalIndex(
  2830. -removedLogicalInside.length());
  2831. } else {
  2832. /*
  2833. * We're in a combination, where we need to both scroll
  2834. * up AND show new rows at the bottom.
  2835. *
  2836. * Example: Scrolled down to show the second to last
  2837. * row. Remove two. Viewport scrolls up, revealing the
  2838. * row above row. The last element collapses up and into
  2839. * view.
  2840. *
  2841. * Reminder: this use case handles only the case when
  2842. * there are enough escalator rows to still render a
  2843. * full view. I.e. all escalator rows will _always_ be
  2844. * populated
  2845. */
  2846. /*-
  2847. * 1 1 |1| <- newly rendered
  2848. * |2| |2| |2|
  2849. * |3| ==> |*| ==> |5| <- newly rendered
  2850. * |4| |*|
  2851. * 5 5
  2852. *
  2853. * 1 1 |1| <- newly rendered
  2854. * |2| |*| |4|
  2855. * |3| ==> |*| ==> |5| <- newly rendered
  2856. * |4| |4|
  2857. * 5 5
  2858. */
  2859. /*
  2860. * STEP 1:
  2861. *
  2862. * reorganize deprecated escalator rows to bottom, but
  2863. * don't re-render anything yet
  2864. */
  2865. /*-
  2866. * 1 1 1
  2867. * |2| |*| |4|
  2868. * |3| ==> |*| ==> |*|
  2869. * |4| |4| |*|
  2870. * 5 5 5
  2871. */
  2872. double newTop = getRowTop(visualRowOrder
  2873. .get(removedVisualInside.getStart()));
  2874. for (int i = 0; i < removedVisualInside.length(); i++) {
  2875. final TableRowElement tr = visualRowOrder
  2876. .remove(removedVisualInside.getStart());
  2877. visualRowOrder.addLast(tr);
  2878. }
  2879. for (int i = removedVisualInside
  2880. .getStart(); i < escalatorRowCount; i++) {
  2881. final TableRowElement tr = visualRowOrder.get(i);
  2882. setRowPosition(tr, 0, (int) newTop);
  2883. newTop += getDefaultRowHeight();
  2884. newTop += spacerContainer.getSpacerHeight(
  2885. i + removedLogicalInside.getStart());
  2886. }
  2887. /*
  2888. * STEP 2:
  2889. *
  2890. * manually scroll
  2891. */
  2892. /*-
  2893. * 1 |1| <-- newly rendered (by scrolling)
  2894. * |4| |4|
  2895. * |*| ==> |*|
  2896. * |*|
  2897. * 5 5
  2898. */
  2899. final double newScrollTop = contentBottom
  2900. - getHeightOfSection();
  2901. setScrollTop(newScrollTop);
  2902. /*
  2903. * Manually call the scroll handler, so we get immediate
  2904. * effects in the escalator.
  2905. */
  2906. scroller.onScroll();
  2907. /*
  2908. * Move the bottommost (n+1:th) escalator row to top,
  2909. * because scrolling up doesn't handle that for us
  2910. * automatically
  2911. */
  2912. moveAndUpdateEscalatorRows(
  2913. Range.withOnly(escalatorRowCount - 1), 0,
  2914. getLogicalRowIndex(visualRowOrder.getFirst())
  2915. - 1);
  2916. updateTopRowLogicalIndex(-1);
  2917. /*
  2918. * STEP 3:
  2919. *
  2920. * update remaining escalator rows
  2921. */
  2922. /*-
  2923. * |1| |1|
  2924. * |4| ==> |4|
  2925. * |*| |5| <-- newly rendered
  2926. *
  2927. * 5
  2928. */
  2929. final int rowsScrolled = (int) (Math
  2930. .ceil((viewportBottom - contentBottom)
  2931. / getDefaultRowHeight()));
  2932. final int start = escalatorRowCount
  2933. - (removedVisualInside.length() - rowsScrolled);
  2934. final Range visualRefreshRange = Range.between(start,
  2935. escalatorRowCount);
  2936. final int logicalTargetIndex = getLogicalRowIndex(
  2937. visualRowOrder.getFirst()) + start;
  2938. // in-place move simply re-renders the rows.
  2939. moveAndUpdateEscalatorRows(visualRefreshRange, start,
  2940. logicalTargetIndex);
  2941. }
  2942. }
  2943. fireRowVisibilityChangeEvent();
  2944. sortDomElements();
  2945. }
  2946. updateTopRowLogicalIndex(-removedAbove.length());
  2947. /*
  2948. * this needs to be done after the escalator has been shrunk down,
  2949. * or it won't work correctly (due to setScrollTop invocation)
  2950. */
  2951. scroller.recalculateScrollbarsForVirtualViewport();
  2952. }
  2953. private void paintRemoveRowsAtMiddle(final Range removedLogicalInside,
  2954. final Range removedVisualInside, final int logicalOffset) {
  2955. /*-
  2956. * : : :
  2957. * |2| |2| |2|
  2958. * |3| ==> |*| ==> |4|
  2959. * |4| |4| |6| <- newly rendered
  2960. * : : :
  2961. */
  2962. final int escalatorRowCount = visualRowOrder.size();
  2963. final int logicalTargetIndex = getLogicalRowIndex(
  2964. visualRowOrder.getLast())
  2965. - (removedVisualInside.length() - 1) + logicalOffset;
  2966. moveAndUpdateEscalatorRows(removedVisualInside, escalatorRowCount,
  2967. logicalTargetIndex);
  2968. // move the surrounding rows to their correct places.
  2969. final ListIterator<TableRowElement> iterator = visualRowOrder
  2970. .listIterator(removedVisualInside.getStart());
  2971. double rowTop = getRowTop(
  2972. removedLogicalInside.getStart() + logicalOffset);
  2973. for (int i = removedVisualInside.getStart(); i < escalatorRowCount
  2974. - removedVisualInside.length(); i++) {
  2975. final TableRowElement tr = iterator.next();
  2976. setRowPosition(tr, 0, rowTop);
  2977. rowTop += getDefaultRowHeight();
  2978. rowTop += spacerContainer
  2979. .getSpacerHeight(i + removedLogicalInside.getStart());
  2980. }
  2981. }
  2982. private void paintRemoveRowsAtBottom(final Range removedLogicalInside,
  2983. final Range removedVisualInside) {
  2984. /*-
  2985. * :
  2986. * : : |4| <- newly rendered
  2987. * |5| |5| |5|
  2988. * |6| ==> |*| ==> |7|
  2989. * |7| |7|
  2990. */
  2991. final int logicalTargetIndex = getLogicalRowIndex(
  2992. visualRowOrder.getFirst()) - removedVisualInside.length();
  2993. moveAndUpdateEscalatorRows(removedVisualInside, 0,
  2994. logicalTargetIndex);
  2995. // move the surrounding rows to their correct places.
  2996. int firstUpdatedIndex = removedVisualInside.getEnd();
  2997. final ListIterator<TableRowElement> iterator = visualRowOrder
  2998. .listIterator(firstUpdatedIndex);
  2999. double rowTop = getRowTop(removedLogicalInside.getStart());
  3000. int i = 0;
  3001. while (iterator.hasNext()) {
  3002. final TableRowElement tr = iterator.next();
  3003. setRowPosition(tr, 0, rowTop);
  3004. rowTop += getDefaultRowHeight();
  3005. rowTop += spacerContainer
  3006. .getSpacerHeight(firstUpdatedIndex + i++);
  3007. }
  3008. }
  3009. @Override
  3010. public int getLogicalRowIndex(final TableRowElement tr) {
  3011. assert tr
  3012. .getParentNode() == root : "The given element isn't a row element in the body";
  3013. int internalIndex = visualRowOrder.indexOf(tr);
  3014. return getTopRowLogicalIndex() + internalIndex;
  3015. }
  3016. @Override
  3017. protected void recalculateSectionHeight() {
  3018. // NOOP for body, since it doesn't make any sense.
  3019. }
  3020. /**
  3021. * Adjusts the row index and number to be relevant for the current
  3022. * virtual viewport.
  3023. * <p>
  3024. * It converts a logical range of rows index to the matching visual
  3025. * range, truncating the resulting range with the viewport.
  3026. * <p>
  3027. * <ul>
  3028. * <li>Escalator contains logical rows 0..100
  3029. * <li>Current viewport showing logical rows 20..29
  3030. * <li>convertToVisual([20..29]) &rarr; [0..9]
  3031. * <li>convertToVisual([15..24]) &rarr; [0..4]
  3032. * <li>convertToVisual([25..29]) &rarr; [5..9]
  3033. * <li>convertToVisual([26..39]) &rarr; [6..9]
  3034. * <li>convertToVisual([0..5]) &rarr; [0..-1] <em>(empty)</em>
  3035. * <li>convertToVisual([35..1]) &rarr; [0..-1] <em>(empty)</em>
  3036. * <li>convertToVisual([0..100]) &rarr; [0..9]
  3037. * </ul>
  3038. *
  3039. * @return a logical range converted to a visual range, truncated to the
  3040. * current viewport. The first visual row has the index 0.
  3041. */
  3042. private Range convertToVisual(final Range logicalRange) {
  3043. if (logicalRange.isEmpty()) {
  3044. return logicalRange;
  3045. } else if (visualRowOrder.isEmpty()) {
  3046. // empty range
  3047. return Range.withLength(0, 0);
  3048. }
  3049. /*
  3050. * TODO [[spacer]]: these assumptions will be totally broken with
  3051. * spacers.
  3052. */
  3053. final int maxVisibleRowCount = getMaxVisibleRowCount();
  3054. final int currentTopRowIndex = getLogicalRowIndex(
  3055. visualRowOrder.getFirst());
  3056. final Range[] partitions = logicalRange.partitionWith(
  3057. Range.withLength(currentTopRowIndex, maxVisibleRowCount));
  3058. final Range insideRange = partitions[1];
  3059. return insideRange.offsetBy(-currentTopRowIndex);
  3060. }
  3061. @Override
  3062. protected String getCellElementTagName() {
  3063. return "td";
  3064. }
  3065. @Override
  3066. protected double getHeightOfSection() {
  3067. final int tableHeight = tableWrapper.getOffsetHeight();
  3068. final double footerHeight = footer.getHeightOfSection();
  3069. final double headerHeight = header.getHeightOfSection();
  3070. double heightOfSection = tableHeight - footerHeight - headerHeight;
  3071. return Math.max(0, heightOfSection);
  3072. }
  3073. @Override
  3074. protected void refreshCells(Range logicalRowRange, Range colRange) {
  3075. Profiler.enter("Escalator.BodyRowContainer.refreshRows");
  3076. final Range visualRange = convertToVisual(logicalRowRange);
  3077. if (!visualRange.isEmpty()) {
  3078. final int firstLogicalRowIndex = getLogicalRowIndex(
  3079. visualRowOrder.getFirst());
  3080. for (int rowNumber = visualRange
  3081. .getStart(); rowNumber < visualRange
  3082. .getEnd(); rowNumber++) {
  3083. refreshRow(visualRowOrder.get(rowNumber),
  3084. firstLogicalRowIndex + rowNumber, colRange);
  3085. }
  3086. }
  3087. Profiler.leave("Escalator.BodyRowContainer.refreshRows");
  3088. }
  3089. @Override
  3090. protected TableRowElement getTrByVisualIndex(final int index)
  3091. throws IndexOutOfBoundsException {
  3092. if (index >= 0 && index < visualRowOrder.size()) {
  3093. return visualRowOrder.get(index);
  3094. } else {
  3095. throw new IndexOutOfBoundsException(
  3096. "No such visual index: " + index);
  3097. }
  3098. }
  3099. @Override
  3100. public TableRowElement getRowElement(int index) {
  3101. if (index < 0 || index >= getRowCount()) {
  3102. throw new IndexOutOfBoundsException(
  3103. "No such logical index: " + index);
  3104. }
  3105. int visualIndex = index
  3106. - getLogicalRowIndex(visualRowOrder.getFirst());
  3107. if (visualIndex >= 0 && visualIndex < visualRowOrder.size()) {
  3108. return super.getRowElement(visualIndex);
  3109. } else {
  3110. throw new IllegalStateException("Row with logical index "
  3111. + index + " is currently not available in the DOM");
  3112. }
  3113. }
  3114. private void setBodyScrollPosition(final double scrollLeft,
  3115. final double scrollTop) {
  3116. tBodyScrollLeft = scrollLeft;
  3117. tBodyScrollTop = scrollTop;
  3118. position.set(bodyElem, -tBodyScrollLeft, -tBodyScrollTop);
  3119. position.set(spacerDecoContainer, 0, -tBodyScrollTop);
  3120. }
  3121. /**
  3122. * Make sure that there is a correct amount of escalator rows: Add more
  3123. * if needed, or remove any superfluous ones.
  3124. * <p>
  3125. * This method should be called when e.g. the height of the Escalator
  3126. * changes.
  3127. * <p>
  3128. * <em>Note:</em> This method will make sure that the escalator rows are
  3129. * placed in the proper places. By default new rows are added below, but
  3130. * if the content is scrolled down, the rows are populated on top
  3131. * instead.
  3132. */
  3133. public void verifyEscalatorCount() {
  3134. /*
  3135. * This method indeed has a smell very similar to paintRemoveRows
  3136. * and paintInsertRows.
  3137. *
  3138. * Unfortunately, those the code can't trivially be shared, since
  3139. * there are some slight differences in the respective
  3140. * responsibilities. The "paint" methods fake the addition and
  3141. * removal of rows, and make sure to either push existing data out
  3142. * of view, or draw new data into view. Only in some special cases
  3143. * will the DOM element count change.
  3144. *
  3145. * This method, however, has the explicit responsibility to verify
  3146. * that when "something" happens, we still have the correct amount
  3147. * of escalator rows in the DOM, and if not, we make sure to modify
  3148. * that count. Only in some special cases do we need to take into
  3149. * account other things than simply modifying the DOM element count.
  3150. */
  3151. Profiler.enter("Escalator.BodyRowContainer.verifyEscalatorCount");
  3152. if (!isAttached()) {
  3153. return;
  3154. }
  3155. final int maxVisibleRowCount = getMaxVisibleRowCount();
  3156. final int neededEscalatorRows = Math.min(maxVisibleRowCount,
  3157. body.getRowCount());
  3158. final int neededEscalatorRowsDiff = neededEscalatorRows
  3159. - visualRowOrder.size();
  3160. if (neededEscalatorRowsDiff > 0) {
  3161. // needs more
  3162. /*
  3163. * This is a workaround for the issue where we might be scrolled
  3164. * to the bottom, and the widget expands beyond the content
  3165. * range
  3166. */
  3167. final int index = visualRowOrder.size();
  3168. final int nextLastLogicalIndex;
  3169. if (!visualRowOrder.isEmpty()) {
  3170. nextLastLogicalIndex = getLogicalRowIndex(
  3171. visualRowOrder.getLast()) + 1;
  3172. } else {
  3173. nextLastLogicalIndex = 0;
  3174. }
  3175. final boolean contentWillFit = nextLastLogicalIndex < getRowCount()
  3176. - neededEscalatorRowsDiff;
  3177. if (contentWillFit) {
  3178. final List<TableRowElement> addedRows = fillAndPopulateEscalatorRowsIfNeeded(
  3179. index, neededEscalatorRowsDiff);
  3180. /*
  3181. * Since fillAndPopulateEscalatorRowsIfNeeded operates on
  3182. * the assumption that index == visual index == logical
  3183. * index, we thank for the added escalator rows, but since
  3184. * they're painted in the wrong CSS position, we need to
  3185. * move them to their actual locations.
  3186. *
  3187. * Note: this is the second (see body.paintInsertRows)
  3188. * occasion where fillAndPopulateEscalatorRowsIfNeeded would
  3189. * behave "more correctly" if it only would add escalator
  3190. * rows to the DOM and appropriate bookkeping, and not
  3191. * actually populate them :/
  3192. */
  3193. moveAndUpdateEscalatorRows(
  3194. Range.withLength(index, addedRows.size()), index,
  3195. nextLastLogicalIndex);
  3196. } else {
  3197. /*
  3198. * TODO [[optimize]]
  3199. *
  3200. * We're scrolled so far down that all rows can't be simply
  3201. * appended at the end, since we might start displaying
  3202. * escalator rows that don't exist. To avoid the mess that
  3203. * is body.paintRemoveRows, this is a dirty hack that dumbs
  3204. * the problem down to a more basic and already-solved
  3205. * problem:
  3206. *
  3207. * 1) scroll all the way up 2) add the missing escalator
  3208. * rows 3) scroll back to the original position.
  3209. *
  3210. * Letting the browser scroll back to our original position
  3211. * will automatically solve any possible overflow problems,
  3212. * since the browser will not allow us to scroll beyond the
  3213. * actual content.
  3214. */
  3215. final double oldScrollTop = getScrollTop();
  3216. setScrollTop(0);
  3217. scroller.onScroll();
  3218. fillAndPopulateEscalatorRowsIfNeeded(index,
  3219. neededEscalatorRowsDiff);
  3220. setScrollTop(oldScrollTop);
  3221. scroller.onScroll();
  3222. }
  3223. } else if (neededEscalatorRowsDiff < 0) {
  3224. // needs less
  3225. final ListIterator<TableRowElement> iter = visualRowOrder
  3226. .listIterator(visualRowOrder.size());
  3227. for (int i = 0; i < -neededEscalatorRowsDiff; i++) {
  3228. final Element last = iter.previous();
  3229. last.removeFromParent();
  3230. iter.remove();
  3231. }
  3232. /*
  3233. * If we were scrolled to the bottom so that we didn't have an
  3234. * extra escalator row at the bottom, we'll probably end up with
  3235. * blank space at the bottom of the escalator, and one extra row
  3236. * above the header.
  3237. *
  3238. * Experimentation idea #1: calculate "scrollbottom" vs content
  3239. * bottom and remove one row from top, rest from bottom. This
  3240. * FAILED, since setHeight has already happened, thus we never
  3241. * will detect ourselves having been scrolled all the way to the
  3242. * bottom.
  3243. */
  3244. if (!visualRowOrder.isEmpty()) {
  3245. final double firstRowTop = getRowTop(
  3246. visualRowOrder.getFirst());
  3247. final double firstRowMinTop = tBodyScrollTop
  3248. - getDefaultRowHeight();
  3249. if (firstRowTop < firstRowMinTop) {
  3250. final int newLogicalIndex = getLogicalRowIndex(
  3251. visualRowOrder.getLast()) + 1;
  3252. moveAndUpdateEscalatorRows(Range.withOnly(0),
  3253. visualRowOrder.size(), newLogicalIndex);
  3254. }
  3255. }
  3256. }
  3257. if (neededEscalatorRowsDiff != 0) {
  3258. fireRowVisibilityChangeEvent();
  3259. }
  3260. Profiler.leave("Escalator.BodyRowContainer.verifyEscalatorCount");
  3261. }
  3262. @Override
  3263. protected void reapplyDefaultRowHeights() {
  3264. if (visualRowOrder.isEmpty()) {
  3265. return;
  3266. }
  3267. Profiler.enter(
  3268. "Escalator.BodyRowContainer.reapplyDefaultRowHeights");
  3269. /* step 1: resize and reposition rows */
  3270. for (int i = 0; i < visualRowOrder.size(); i++) {
  3271. TableRowElement tr = visualRowOrder.get(i);
  3272. reapplyRowHeight(tr, getDefaultRowHeight());
  3273. final int logicalIndex = getTopRowLogicalIndex() + i;
  3274. setRowPosition(tr, 0, logicalIndex * getDefaultRowHeight());
  3275. }
  3276. /*
  3277. * step 2: move scrollbar so that it corresponds to its previous
  3278. * place
  3279. */
  3280. /*
  3281. * This ratio needs to be calculated with the scrollsize (not max
  3282. * scroll position) in order to align the top row with the new
  3283. * scroll position.
  3284. */
  3285. double scrollRatio = verticalScrollbar.getScrollPos()
  3286. / verticalScrollbar.getScrollSize();
  3287. scroller.recalculateScrollbarsForVirtualViewport();
  3288. verticalScrollbar.setScrollPos((int) (getDefaultRowHeight()
  3289. * getRowCount() * scrollRatio));
  3290. setBodyScrollPosition(horizontalScrollbar.getScrollPos(),
  3291. verticalScrollbar.getScrollPos());
  3292. scroller.onScroll();
  3293. /*
  3294. * step 3: make sure we have the correct amount of escalator rows.
  3295. */
  3296. verifyEscalatorCount();
  3297. int logicalLogical = (int) (getRowTop(visualRowOrder.getFirst())
  3298. / getDefaultRowHeight());
  3299. setTopRowLogicalIndex(logicalLogical);
  3300. Profiler.leave(
  3301. "Escalator.BodyRowContainer.reapplyDefaultRowHeights");
  3302. }
  3303. /**
  3304. * Sorts the rows in the DOM to correspond to the visual order.
  3305. *
  3306. * @see #visualRowOrder
  3307. */
  3308. private void sortDomElements() {
  3309. final String profilingName = "Escalator.BodyRowContainer.sortDomElements";
  3310. Profiler.enter(profilingName);
  3311. /*
  3312. * Focus is lost from an element if that DOM element is (or any of
  3313. * its parents are) removed from the document. Therefore, we sort
  3314. * everything around that row instead.
  3315. */
  3316. final TableRowElement focusedRow = getRowWithFocus();
  3317. if (focusedRow != null) {
  3318. assert focusedRow
  3319. .getParentElement() == root : "Trying to sort around a row that doesn't exist in body";
  3320. assert visualRowOrder.contains(focusedRow)
  3321. || body.spacerContainer.isSpacer(
  3322. focusedRow) : "Trying to sort around a row that doesn't exist in visualRowOrder or is not a spacer.";
  3323. }
  3324. /*
  3325. * Two cases handled simultaneously:
  3326. *
  3327. * 1) No focus on rows. We iterate visualRowOrder backwards, and
  3328. * take the respective element in the DOM, and place it as the first
  3329. * child in the body element. Then we take the next-to-last from
  3330. * visualRowOrder, and put that first, pushing the previous row as
  3331. * the second child. And so on...
  3332. *
  3333. * 2) Focus on some row within Escalator body. Again, we iterate
  3334. * visualRowOrder backwards. This time, we use the focused row as a
  3335. * pivot: Instead of placing rows from the bottom of visualRowOrder
  3336. * and placing it first, we place it underneath the focused row.
  3337. * Once we hit the focused row, we don't move it (to not reset
  3338. * focus) but change sorting mode. After that, we place all rows as
  3339. * the first child.
  3340. */
  3341. List<TableRowElement> orderedBodyRows = new ArrayList<TableRowElement>(
  3342. visualRowOrder);
  3343. Map<Integer, SpacerContainer.SpacerImpl> spacers = body.spacerContainer
  3344. .getSpacers();
  3345. /*
  3346. * Start at -1 to include a spacer that is rendered above the
  3347. * viewport, but its parent row is still not shown
  3348. */
  3349. for (int i = -1; i < visualRowOrder.size(); i++) {
  3350. SpacerContainer.SpacerImpl spacer = spacers
  3351. .remove(Integer.valueOf(getTopRowLogicalIndex() + i));
  3352. if (spacer != null) {
  3353. orderedBodyRows.add(i + 1, spacer.getRootElement());
  3354. spacer.show();
  3355. }
  3356. }
  3357. /*
  3358. * At this point, invisible spacers aren't reordered, so their
  3359. * position in the DOM will remain undefined.
  3360. */
  3361. // If a spacer was not reordered, it means that it's out of view.
  3362. for (SpacerContainer.SpacerImpl unmovedSpacer : spacers.values()) {
  3363. unmovedSpacer.hide();
  3364. }
  3365. /*
  3366. * If we have a focused row, start in the mode where we put
  3367. * everything underneath that row. Otherwise, all rows are placed as
  3368. * first child.
  3369. */
  3370. boolean insertFirst = (focusedRow == null);
  3371. final ListIterator<TableRowElement> i = orderedBodyRows
  3372. .listIterator(orderedBodyRows.size());
  3373. while (i.hasPrevious()) {
  3374. TableRowElement tr = i.previous();
  3375. if (tr == focusedRow) {
  3376. insertFirst = true;
  3377. } else if (insertFirst) {
  3378. root.insertFirst(tr);
  3379. } else {
  3380. root.insertAfter(tr, focusedRow);
  3381. }
  3382. }
  3383. Profiler.leave(profilingName);
  3384. }
  3385. /**
  3386. * Get the {@literal <tbody>} row that contains (or has) focus.
  3387. *
  3388. * @return The {@literal <tbody>} row that contains a focused DOM
  3389. * element, or <code>null</code> if focus is outside of a body
  3390. * row.
  3391. */
  3392. private TableRowElement getRowWithFocus() {
  3393. TableRowElement rowContainingFocus = null;
  3394. final Element focusedElement = WidgetUtil.getFocusedElement();
  3395. if (focusedElement != null && root.isOrHasChild(focusedElement)) {
  3396. Element e = focusedElement;
  3397. while (e != null && e != root) {
  3398. /*
  3399. * You never know if there's several tables embedded in a
  3400. * cell... We'll take the deepest one.
  3401. */
  3402. if (TableRowElement.is(e)) {
  3403. rowContainingFocus = TableRowElement.as(e);
  3404. }
  3405. e = e.getParentElement();
  3406. }
  3407. }
  3408. return rowContainingFocus;
  3409. }
  3410. @Override
  3411. public Cell getCell(Element element) {
  3412. Cell cell = super.getCell(element);
  3413. if (cell == null) {
  3414. return null;
  3415. }
  3416. // Convert DOM coordinates to logical coordinates for rows
  3417. TableRowElement rowElement = (TableRowElement) cell.getElement()
  3418. .getParentElement();
  3419. return new Cell(getLogicalRowIndex(rowElement), cell.getColumn(),
  3420. cell.getElement());
  3421. }
  3422. @Override
  3423. public void setSpacer(int rowIndex, double height)
  3424. throws IllegalArgumentException {
  3425. spacerContainer.setSpacer(rowIndex, height);
  3426. }
  3427. @Override
  3428. public void setSpacerUpdater(SpacerUpdater spacerUpdater)
  3429. throws IllegalArgumentException {
  3430. spacerContainer.setSpacerUpdater(spacerUpdater);
  3431. }
  3432. @Override
  3433. public SpacerUpdater getSpacerUpdater() {
  3434. return spacerContainer.getSpacerUpdater();
  3435. }
  3436. /**
  3437. * <em>Calculates</em> the correct top position of a row at a logical
  3438. * index, regardless if there is one there or not.
  3439. * <p>
  3440. * A correct result requires that both {@link #getDefaultRowHeight()} is
  3441. * consistent, and the placement and height of all spacers above the
  3442. * given logical index are consistent.
  3443. *
  3444. * @param logicalIndex
  3445. * the logical index of the row for which to calculate the
  3446. * top position
  3447. * @return the position at which to place a row in {@code logicalIndex}
  3448. * @see #getRowTop(TableRowElement)
  3449. */
  3450. private double getRowTop(int logicalIndex) {
  3451. double top = spacerContainer
  3452. .getSpacerHeightsSumUntilIndex(logicalIndex);
  3453. return top + (logicalIndex * getDefaultRowHeight());
  3454. }
  3455. public void shiftRowPositions(int row, double diff) {
  3456. for (TableRowElement tr : getVisibleRowsAfter(row)) {
  3457. setRowPosition(tr, 0, getRowTop(tr) + diff);
  3458. }
  3459. }
  3460. private List<TableRowElement> getVisibleRowsAfter(int logicalRow) {
  3461. Range visibleRowLogicalRange = getVisibleRowRange();
  3462. boolean allRowsAreInView = logicalRow < visibleRowLogicalRange
  3463. .getStart();
  3464. boolean noRowsAreInView = logicalRow >= visibleRowLogicalRange
  3465. .getEnd() - 1;
  3466. if (allRowsAreInView) {
  3467. return Collections.unmodifiableList(visualRowOrder);
  3468. } else if (noRowsAreInView) {
  3469. return Collections.emptyList();
  3470. } else {
  3471. int fromIndex = (logicalRow - visibleRowLogicalRange.getStart())
  3472. + 1;
  3473. int toIndex = visibleRowLogicalRange.length();
  3474. List<TableRowElement> sublist = visualRowOrder
  3475. .subList(fromIndex, toIndex);
  3476. return Collections.unmodifiableList(sublist);
  3477. }
  3478. }
  3479. @Override
  3480. public int getDomRowCount() {
  3481. return root.getChildCount()
  3482. - spacerContainer.getSpacersInDom().size();
  3483. }
  3484. @Override
  3485. protected boolean rowCanBeFrozen(TableRowElement tr) {
  3486. return visualRowOrder.contains(tr);
  3487. }
  3488. void reapplySpacerWidths() {
  3489. spacerContainer.reapplySpacerWidths();
  3490. }
  3491. void scrollToSpacer(int spacerIndex, ScrollDestination destination,
  3492. int padding) {
  3493. spacerContainer.scrollToSpacer(spacerIndex, destination, padding);
  3494. }
  3495. }
  3496. private class ColumnConfigurationImpl implements ColumnConfiguration {
  3497. public class Column {
  3498. public static final double DEFAULT_COLUMN_WIDTH_PX = 100;
  3499. private double definedWidth = -1;
  3500. private double calculatedWidth = DEFAULT_COLUMN_WIDTH_PX;
  3501. private boolean measuringRequested = false;
  3502. public void setWidth(double px) {
  3503. definedWidth = px;
  3504. if (px < 0) {
  3505. if (isAttached()) {
  3506. calculateWidth();
  3507. } else {
  3508. /*
  3509. * the column's width is calculated at Escalator.onLoad
  3510. * via measureAndSetWidthIfNeeded!
  3511. */
  3512. measuringRequested = true;
  3513. }
  3514. } else {
  3515. calculatedWidth = px;
  3516. }
  3517. }
  3518. public double getDefinedWidth() {
  3519. return definedWidth;
  3520. }
  3521. /**
  3522. * Returns the actual width in the DOM.
  3523. *
  3524. * @return the width in pixels in the DOM. Returns -1 if the column
  3525. * needs measuring, but has not been yet measured
  3526. */
  3527. public double getCalculatedWidth() {
  3528. /*
  3529. * This might return an untrue value (e.g. during init/onload),
  3530. * since we haven't had a proper chance to actually calculate
  3531. * widths yet.
  3532. *
  3533. * This is fixed during Escalator.onLoad, by the call to
  3534. * "measureAndSetWidthIfNeeded", which fixes "everything".
  3535. */
  3536. if (!measuringRequested) {
  3537. return calculatedWidth;
  3538. } else {
  3539. return -1;
  3540. }
  3541. }
  3542. /**
  3543. * Checks if the column needs measuring, and then measures it.
  3544. * <p>
  3545. * Called by {@link Escalator#onLoad()}.
  3546. */
  3547. public boolean measureAndSetWidthIfNeeded() {
  3548. assert isAttached() : "Column.measureAndSetWidthIfNeeded() was called even though Escalator was not attached!";
  3549. if (measuringRequested) {
  3550. measuringRequested = false;
  3551. setWidth(definedWidth);
  3552. return true;
  3553. }
  3554. return false;
  3555. }
  3556. private void calculateWidth() {
  3557. calculatedWidth = getMaxCellWidth(columns.indexOf(this));
  3558. }
  3559. }
  3560. private final List<Column> columns = new ArrayList<Column>();
  3561. private int frozenColumns = 0;
  3562. /*
  3563. * TODO: this is a bit of a duplicate functionality with the
  3564. * Column.calculatedWidth caching. Probably should use one or the other,
  3565. * not both
  3566. */
  3567. /**
  3568. * A cached array of all the calculated column widths.
  3569. *
  3570. * @see #getCalculatedColumnWidths()
  3571. */
  3572. private double[] widthsArray = null;
  3573. /**
  3574. * {@inheritDoc}
  3575. * <p>
  3576. * <em>Implementation detail:</em> This method does no DOM modifications
  3577. * (i.e. is very cheap to call) if there are no rows in the DOM when
  3578. * this method is called.
  3579. *
  3580. * @see #hasSomethingInDom()
  3581. */
  3582. @Override
  3583. public void removeColumns(final int index, final int numberOfColumns) {
  3584. // Validate
  3585. assertArgumentsAreValidAndWithinRange(index, numberOfColumns);
  3586. // Move the horizontal scrollbar to the left, if removed columns are
  3587. // to the left of the viewport
  3588. removeColumnsAdjustScrollbar(index, numberOfColumns);
  3589. // Remove from DOM
  3590. header.paintRemoveColumns(index, numberOfColumns);
  3591. body.paintRemoveColumns(index, numberOfColumns);
  3592. footer.paintRemoveColumns(index, numberOfColumns);
  3593. // Remove from bookkeeping
  3594. flyweightRow.removeCells(index, numberOfColumns);
  3595. columns.subList(index, index + numberOfColumns).clear();
  3596. // Adjust frozen columns
  3597. if (index < getFrozenColumnCount()) {
  3598. if (index + numberOfColumns < frozenColumns) {
  3599. /*
  3600. * Last removed column was frozen, meaning that all removed
  3601. * columns were frozen. Just decrement the number of frozen
  3602. * columns accordingly.
  3603. */
  3604. frozenColumns -= numberOfColumns;
  3605. } else {
  3606. /*
  3607. * If last removed column was not frozen, we have removed
  3608. * columns beyond the frozen range, so all remaining frozen
  3609. * columns are to the left of the removed columns.
  3610. */
  3611. frozenColumns = index;
  3612. }
  3613. }
  3614. scroller.recalculateScrollbarsForVirtualViewport();
  3615. body.verifyEscalatorCount();
  3616. if (getColumnConfiguration().getColumnCount() > 0) {
  3617. reapplyRowWidths(header);
  3618. reapplyRowWidths(body);
  3619. reapplyRowWidths(footer);
  3620. }
  3621. /*
  3622. * Colspans make any kind of automatic clever content re-rendering
  3623. * impossible: As soon as anything has colspans, removing one might
  3624. * reveal further colspans, modifying the DOM structure once again,
  3625. * ending in a cascade of updates. Because we don't know how the
  3626. * data is updated.
  3627. *
  3628. * So, instead, we don't do anything. The client code is responsible
  3629. * for re-rendering the content (if so desired). Everything Just
  3630. * Works (TM) if colspans aren't used.
  3631. */
  3632. }
  3633. private void reapplyRowWidths(AbstractRowContainer container) {
  3634. if (container.getRowCount() > 0) {
  3635. container.reapplyRowWidths();
  3636. }
  3637. }
  3638. private void removeColumnsAdjustScrollbar(int index,
  3639. int numberOfColumns) {
  3640. if (horizontalScrollbar.getOffsetSize() >= horizontalScrollbar
  3641. .getScrollSize()) {
  3642. return;
  3643. }
  3644. double leftPosOfFirstColumnToRemove = getCalculatedColumnsWidth(
  3645. Range.between(0, index));
  3646. double widthOfColumnsToRemove = getCalculatedColumnsWidth(
  3647. Range.withLength(index, numberOfColumns));
  3648. double scrollLeft = horizontalScrollbar.getScrollPos();
  3649. if (scrollLeft <= leftPosOfFirstColumnToRemove) {
  3650. /*
  3651. * viewport is scrolled to the left of the first removed column,
  3652. * so there's no need to adjust anything
  3653. */
  3654. return;
  3655. }
  3656. double adjustedScrollLeft = Math.max(leftPosOfFirstColumnToRemove,
  3657. scrollLeft - widthOfColumnsToRemove);
  3658. horizontalScrollbar.setScrollPos(adjustedScrollLeft);
  3659. }
  3660. /**
  3661. * Calculate the width of a row, as the sum of columns' widths.
  3662. *
  3663. * @return the width of a row, in pixels
  3664. */
  3665. public double calculateRowWidth() {
  3666. return getCalculatedColumnsWidth(
  3667. Range.between(0, getColumnCount()));
  3668. }
  3669. private void assertArgumentsAreValidAndWithinRange(final int index,
  3670. final int numberOfColumns) {
  3671. if (numberOfColumns < 1) {
  3672. throw new IllegalArgumentException(
  3673. "Number of columns can't be less than 1 (was "
  3674. + numberOfColumns + ")");
  3675. }
  3676. if (index < 0 || index + numberOfColumns > getColumnCount()) {
  3677. throw new IndexOutOfBoundsException("The given "
  3678. + "column range (" + index + ".."
  3679. + (index + numberOfColumns)
  3680. + ") was outside of the current "
  3681. + "number of columns (" + getColumnCount() + ")");
  3682. }
  3683. }
  3684. /**
  3685. * {@inheritDoc}
  3686. * <p>
  3687. * <em>Implementation detail:</em> This method does no DOM modifications
  3688. * (i.e. is very cheap to call) if there is no data for rows when this
  3689. * method is called.
  3690. *
  3691. * @see #hasColumnAndRowData()
  3692. */
  3693. @Override
  3694. public void insertColumns(final int index, final int numberOfColumns) {
  3695. // Validate
  3696. if (index < 0 || index > getColumnCount()) {
  3697. throw new IndexOutOfBoundsException("The given index(" + index
  3698. + ") was outside of the current number of columns (0.."
  3699. + getColumnCount() + ")");
  3700. }
  3701. if (numberOfColumns < 1) {
  3702. throw new IllegalArgumentException(
  3703. "Number of columns must be 1 or greater (was "
  3704. + numberOfColumns);
  3705. }
  3706. // Add to bookkeeping
  3707. flyweightRow.addCells(index, numberOfColumns);
  3708. for (int i = 0; i < numberOfColumns; i++) {
  3709. columns.add(index, new Column());
  3710. }
  3711. // Adjust frozen columns
  3712. boolean frozen = index < frozenColumns;
  3713. if (frozen) {
  3714. frozenColumns += numberOfColumns;
  3715. }
  3716. // Add to DOM
  3717. header.paintInsertColumns(index, numberOfColumns, frozen);
  3718. body.paintInsertColumns(index, numberOfColumns, frozen);
  3719. footer.paintInsertColumns(index, numberOfColumns, frozen);
  3720. // this needs to be before the scrollbar adjustment.
  3721. boolean scrollbarWasNeeded = horizontalScrollbar
  3722. .getOffsetSize() < horizontalScrollbar.getScrollSize();
  3723. scroller.recalculateScrollbarsForVirtualViewport();
  3724. boolean scrollbarIsNowNeeded = horizontalScrollbar
  3725. .getOffsetSize() < horizontalScrollbar.getScrollSize();
  3726. if (!scrollbarWasNeeded && scrollbarIsNowNeeded) {
  3727. // This might as a side effect move rows around (when scrolled
  3728. // all the way down) and require the DOM to be up to date, i.e.
  3729. // the column to be added
  3730. body.verifyEscalatorCount();
  3731. }
  3732. // fix initial width
  3733. if (header.getRowCount() > 0 || body.getRowCount() > 0
  3734. || footer.getRowCount() > 0) {
  3735. Map<Integer, Double> colWidths = new HashMap<Integer, Double>();
  3736. Double width = Double.valueOf(Column.DEFAULT_COLUMN_WIDTH_PX);
  3737. for (int i = index; i < index + numberOfColumns; i++) {
  3738. Integer col = Integer.valueOf(i);
  3739. colWidths.put(col, width);
  3740. }
  3741. getColumnConfiguration().setColumnWidths(colWidths);
  3742. }
  3743. // Adjust scrollbar
  3744. double pixelsToInsertedColumn = columnConfiguration
  3745. .getCalculatedColumnsWidth(Range.withLength(0, index));
  3746. final boolean columnsWereAddedToTheLeftOfViewport = scroller.lastScrollLeft > pixelsToInsertedColumn;
  3747. if (columnsWereAddedToTheLeftOfViewport) {
  3748. double insertedColumnsWidth = columnConfiguration
  3749. .getCalculatedColumnsWidth(
  3750. Range.withLength(index, numberOfColumns));
  3751. horizontalScrollbar.setScrollPos(
  3752. scroller.lastScrollLeft + insertedColumnsWidth);
  3753. }
  3754. /*
  3755. * Colspans make any kind of automatic clever content re-rendering
  3756. * impossible: As soon as anything has colspans, adding one might
  3757. * affect surrounding colspans, modifying the DOM structure once
  3758. * again, ending in a cascade of updates. Because we don't know how
  3759. * the data is updated.
  3760. *
  3761. * So, instead, we don't do anything. The client code is responsible
  3762. * for re-rendering the content (if so desired). Everything Just
  3763. * Works (TM) if colspans aren't used.
  3764. */
  3765. }
  3766. @Override
  3767. public int getColumnCount() {
  3768. return columns.size();
  3769. }
  3770. @Override
  3771. public void setFrozenColumnCount(int count)
  3772. throws IllegalArgumentException {
  3773. if (count < 0 || count > getColumnCount()) {
  3774. throw new IllegalArgumentException(
  3775. "count must be between 0 and the current number of columns ("
  3776. + getColumnCount() + ")");
  3777. }
  3778. int oldCount = frozenColumns;
  3779. if (count == oldCount) {
  3780. return;
  3781. }
  3782. frozenColumns = count;
  3783. if (hasSomethingInDom()) {
  3784. // Are we freezing or unfreezing?
  3785. boolean frozen = count > oldCount;
  3786. int firstAffectedCol;
  3787. int firstUnaffectedCol;
  3788. if (frozen) {
  3789. firstAffectedCol = oldCount;
  3790. firstUnaffectedCol = count;
  3791. } else {
  3792. firstAffectedCol = count;
  3793. firstUnaffectedCol = oldCount;
  3794. }
  3795. if (oldCount > 0) {
  3796. header.setColumnLastFrozen(oldCount - 1, false);
  3797. body.setColumnLastFrozen(oldCount - 1, false);
  3798. footer.setColumnLastFrozen(oldCount - 1, false);
  3799. }
  3800. if (count > 0) {
  3801. header.setColumnLastFrozen(count - 1, true);
  3802. body.setColumnLastFrozen(count - 1, true);
  3803. footer.setColumnLastFrozen(count - 1, true);
  3804. }
  3805. for (int col = firstAffectedCol; col < firstUnaffectedCol; col++) {
  3806. header.setColumnFrozen(col, frozen);
  3807. body.setColumnFrozen(col, frozen);
  3808. footer.setColumnFrozen(col, frozen);
  3809. }
  3810. }
  3811. scroller.recalculateScrollbarsForVirtualViewport();
  3812. }
  3813. @Override
  3814. public int getFrozenColumnCount() {
  3815. return frozenColumns;
  3816. }
  3817. @Override
  3818. public void setColumnWidth(int index, double px)
  3819. throws IllegalArgumentException {
  3820. setColumnWidths(Collections.singletonMap(Integer.valueOf(index),
  3821. Double.valueOf(px)));
  3822. }
  3823. @Override
  3824. public void setColumnWidths(Map<Integer, Double> indexWidthMap)
  3825. throws IllegalArgumentException {
  3826. if (indexWidthMap == null) {
  3827. throw new IllegalArgumentException("indexWidthMap was null");
  3828. }
  3829. if (indexWidthMap.isEmpty()) {
  3830. return;
  3831. }
  3832. for (Entry<Integer, Double> entry : indexWidthMap.entrySet()) {
  3833. int index = entry.getKey().intValue();
  3834. double width = entry.getValue().doubleValue();
  3835. checkValidColumnIndex(index);
  3836. // Not all browsers will accept any fractional size..
  3837. width = WidgetUtil.roundSizeDown(width);
  3838. columns.get(index).setWidth(width);
  3839. }
  3840. widthsArray = null;
  3841. header.reapplyColumnWidths();
  3842. body.reapplyColumnWidths();
  3843. footer.reapplyColumnWidths();
  3844. recalculateElementSizes();
  3845. }
  3846. private void checkValidColumnIndex(int index)
  3847. throws IllegalArgumentException {
  3848. if (!Range.withLength(0, getColumnCount()).contains(index)) {
  3849. throw new IllegalArgumentException("The given column index ("
  3850. + index + ") does not exist");
  3851. }
  3852. }
  3853. @Override
  3854. public double getColumnWidth(int index)
  3855. throws IllegalArgumentException {
  3856. checkValidColumnIndex(index);
  3857. return columns.get(index).getDefinedWidth();
  3858. }
  3859. @Override
  3860. public double getColumnWidthActual(int index) {
  3861. return columns.get(index).getCalculatedWidth();
  3862. }
  3863. private double getMaxCellWidth(int colIndex)
  3864. throws IllegalArgumentException {
  3865. double headerWidth = header.measureMinCellWidth(colIndex, true);
  3866. double bodyWidth = body.measureMinCellWidth(colIndex, true);
  3867. double footerWidth = footer.measureMinCellWidth(colIndex, true);
  3868. double maxWidth = Math.max(headerWidth,
  3869. Math.max(bodyWidth, footerWidth));
  3870. assert maxWidth >= 0 : "Got a negative max width for a column, which should be impossible.";
  3871. return maxWidth;
  3872. }
  3873. private double getMinCellWidth(int colIndex)
  3874. throws IllegalArgumentException {
  3875. double headerWidth = header.measureMinCellWidth(colIndex, false);
  3876. double bodyWidth = body.measureMinCellWidth(colIndex, false);
  3877. double footerWidth = footer.measureMinCellWidth(colIndex, false);
  3878. double minWidth = Math.max(headerWidth,
  3879. Math.max(bodyWidth, footerWidth));
  3880. assert minWidth >= 0 : "Got a negative max width for a column, which should be impossible.";
  3881. return minWidth;
  3882. }
  3883. /**
  3884. * Calculates the width of the columns in a given range.
  3885. *
  3886. * @param columns
  3887. * the columns to calculate
  3888. * @return the total width of the columns in the given
  3889. * <code>columns</code>
  3890. */
  3891. double getCalculatedColumnsWidth(final Range columns) {
  3892. /*
  3893. * This is an assert instead of an exception, since this is an
  3894. * internal method.
  3895. */
  3896. assert columns
  3897. .isSubsetOf(Range.between(0, getColumnCount())) : "Range "
  3898. + "was outside of current column range (i.e.: "
  3899. + Range.between(0, getColumnCount())
  3900. + ", but was given :" + columns;
  3901. double sum = 0;
  3902. for (int i = columns.getStart(); i < columns.getEnd(); i++) {
  3903. double columnWidthActual = getColumnWidthActual(i);
  3904. sum += columnWidthActual;
  3905. }
  3906. return sum;
  3907. }
  3908. double[] getCalculatedColumnWidths() {
  3909. if (widthsArray == null || widthsArray.length != getColumnCount()) {
  3910. widthsArray = new double[getColumnCount()];
  3911. for (int i = 0; i < columns.size(); i++) {
  3912. widthsArray[i] = columns.get(i).getCalculatedWidth();
  3913. }
  3914. }
  3915. return widthsArray;
  3916. }
  3917. @Override
  3918. public void refreshColumns(int index, int numberOfColumns)
  3919. throws IndexOutOfBoundsException, IllegalArgumentException {
  3920. if (numberOfColumns < 1) {
  3921. throw new IllegalArgumentException(
  3922. "Number of columns must be 1 or greater (was "
  3923. + numberOfColumns + ")");
  3924. }
  3925. if (index < 0 || index + numberOfColumns > getColumnCount()) {
  3926. throw new IndexOutOfBoundsException("The given "
  3927. + "column range (" + index + ".."
  3928. + (index + numberOfColumns)
  3929. + ") was outside of the current number of columns ("
  3930. + getColumnCount() + ")");
  3931. }
  3932. header.refreshColumns(index, numberOfColumns);
  3933. body.refreshColumns(index, numberOfColumns);
  3934. footer.refreshColumns(index, numberOfColumns);
  3935. }
  3936. }
  3937. /**
  3938. * A decision on how to measure a spacer when it is partially within a
  3939. * designated range.
  3940. * <p>
  3941. * The meaning of each value may differ depending on the context it is being
  3942. * used in. Check that particular method's JavaDoc.
  3943. */
  3944. private enum SpacerInclusionStrategy {
  3945. /** A representation of "the entire spacer". */
  3946. COMPLETE,
  3947. /** A representation of "a partial spacer". */
  3948. PARTIAL,
  3949. /** A representation of "no spacer at all". */
  3950. NONE
  3951. }
  3952. private class SpacerContainer {
  3953. /** This is used mainly for testing purposes */
  3954. private static final String SPACER_LOGICAL_ROW_PROPERTY = "vLogicalRow";
  3955. private final class SpacerImpl implements Spacer {
  3956. private TableCellElement spacerElement;
  3957. private TableRowElement root;
  3958. private DivElement deco;
  3959. private int rowIndex;
  3960. private double height = -1;
  3961. private boolean domHasBeenSetup = false;
  3962. private double decoHeight;
  3963. private double defaultCellBorderBottomSize = -1;
  3964. public SpacerImpl(int rowIndex) {
  3965. this.rowIndex = rowIndex;
  3966. root = TableRowElement.as(DOM.createTR());
  3967. spacerElement = TableCellElement.as(DOM.createTD());
  3968. root.appendChild(spacerElement);
  3969. root.setPropertyInt(SPACER_LOGICAL_ROW_PROPERTY, rowIndex);
  3970. deco = DivElement.as(DOM.createDiv());
  3971. }
  3972. public void setPositionDiff(double x, double y) {
  3973. setPosition(getLeft() + x, getTop() + y);
  3974. }
  3975. public void setupDom(double height) {
  3976. assert !domHasBeenSetup : "DOM can't be set up twice.";
  3977. assert RootPanel.get().getElement().isOrHasChild(
  3978. root) : "Root element should've been attached to the DOM by now.";
  3979. domHasBeenSetup = true;
  3980. getRootElement().getStyle().setWidth(getInnerWidth(), Unit.PX);
  3981. setHeight(height);
  3982. spacerElement
  3983. .setColSpan(getColumnConfiguration().getColumnCount());
  3984. setStylePrimaryName(getStylePrimaryName());
  3985. }
  3986. public TableRowElement getRootElement() {
  3987. return root;
  3988. }
  3989. @Override
  3990. public Element getDecoElement() {
  3991. return deco;
  3992. }
  3993. public void setPosition(double x, double y) {
  3994. positions.set(getRootElement(), x, y);
  3995. positions.set(getDecoElement(), 0,
  3996. y - getSpacerDecoTopOffset());
  3997. }
  3998. private double getSpacerDecoTopOffset() {
  3999. return getBody().getDefaultRowHeight();
  4000. }
  4001. public void setStylePrimaryName(String style) {
  4002. UIObject.setStylePrimaryName(root, style + "-spacer");
  4003. UIObject.setStylePrimaryName(deco, style + "-spacer-deco");
  4004. }
  4005. public void setHeight(double height) {
  4006. assert height >= 0 : "Height must be more >= 0 (was " + height
  4007. + ")";
  4008. final double heightDiff = height - Math.max(0, this.height);
  4009. final double oldHeight = this.height;
  4010. this.height = height;
  4011. // since the spacer might be rendered on top of the previous
  4012. // rows border (done with css), need to increase height the
  4013. // amount of the border thickness
  4014. if (defaultCellBorderBottomSize < 0) {
  4015. defaultCellBorderBottomSize = WidgetUtil
  4016. .getBorderBottomThickness(body
  4017. .getRowElement(
  4018. getVisibleRowRange().getStart())
  4019. .getFirstChildElement());
  4020. }
  4021. root.getStyle().setHeight(height + defaultCellBorderBottomSize,
  4022. Unit.PX);
  4023. // move the visible spacers getRow row onwards.
  4024. shiftSpacerPositionsAfterRow(getRow(), heightDiff);
  4025. /*
  4026. * If we're growing, we'll adjust the scroll size first, then
  4027. * adjust scrolling. If we're shrinking, we do it after the
  4028. * second if-clause.
  4029. */
  4030. boolean spacerIsGrowing = heightDiff > 0;
  4031. if (spacerIsGrowing) {
  4032. verticalScrollbar.setScrollSize(
  4033. verticalScrollbar.getScrollSize() + heightDiff);
  4034. }
  4035. /*
  4036. * Don't modify the scrollbars if we're expanding the -1 spacer
  4037. * while we're scrolled to the top.
  4038. */
  4039. boolean minusOneSpacerException = spacerIsGrowing
  4040. && getRow() == -1 && body.getTopRowLogicalIndex() == 0;
  4041. boolean viewportNeedsScrolling = getRow() < body
  4042. .getTopRowLogicalIndex() && !minusOneSpacerException;
  4043. if (viewportNeedsScrolling) {
  4044. /*
  4045. * We can't use adjustScrollPos here, probably because of a
  4046. * bookkeeping-related race condition.
  4047. *
  4048. * This particular situation is easier, however, since we
  4049. * know exactly how many pixels we need to move (heightDiff)
  4050. * and all elements below the spacer always need to move
  4051. * that pixel amount.
  4052. */
  4053. for (TableRowElement row : body.visualRowOrder) {
  4054. body.setRowPosition(row, 0,
  4055. body.getRowTop(row) + heightDiff);
  4056. }
  4057. double top = getTop();
  4058. double bottom = top + oldHeight;
  4059. double scrollTop = verticalScrollbar.getScrollPos();
  4060. boolean viewportTopIsAtMidSpacer = top < scrollTop
  4061. && scrollTop < bottom;
  4062. final double moveDiff;
  4063. if (viewportTopIsAtMidSpacer && !spacerIsGrowing) {
  4064. /*
  4065. * If the scroll top is in the middle of the modified
  4066. * spacer, we want to scroll the viewport up as usual,
  4067. * but we don't want to scroll past the top of it.
  4068. *
  4069. * Math.max ensures this (remember: the result is going
  4070. * to be negative).
  4071. */
  4072. moveDiff = Math.max(heightDiff, top - scrollTop);
  4073. } else {
  4074. moveDiff = heightDiff;
  4075. }
  4076. body.setBodyScrollPosition(tBodyScrollLeft,
  4077. tBodyScrollTop + moveDiff);
  4078. verticalScrollbar.setScrollPosByDelta(moveDiff);
  4079. } else {
  4080. body.shiftRowPositions(getRow(), heightDiff);
  4081. }
  4082. if (!spacerIsGrowing) {
  4083. verticalScrollbar.setScrollSize(
  4084. verticalScrollbar.getScrollSize() + heightDiff);
  4085. }
  4086. updateDecoratorGeometry(height);
  4087. }
  4088. /** Resizes and places the decorator. */
  4089. private void updateDecoratorGeometry(double detailsHeight) {
  4090. Style style = deco.getStyle();
  4091. decoHeight = detailsHeight + getBody().getDefaultRowHeight();
  4092. style.setHeight(decoHeight, Unit.PX);
  4093. }
  4094. @Override
  4095. public Element getElement() {
  4096. return spacerElement;
  4097. }
  4098. @Override
  4099. public int getRow() {
  4100. return rowIndex;
  4101. }
  4102. public double getHeight() {
  4103. assert height >= 0 : "Height was not previously set by setHeight.";
  4104. return height;
  4105. }
  4106. public double getTop() {
  4107. return positions.getTop(getRootElement());
  4108. }
  4109. public double getLeft() {
  4110. return positions.getLeft(getRootElement());
  4111. }
  4112. /**
  4113. * Sets a new row index for this spacer. Also updates the bookeeping
  4114. * at {@link SpacerContainer#rowIndexToSpacer}.
  4115. */
  4116. @SuppressWarnings("boxing")
  4117. public void setRowIndex(int rowIndex) {
  4118. SpacerImpl spacer = rowIndexToSpacer.remove(this.rowIndex);
  4119. assert this == spacer : "trying to move an unexpected spacer.";
  4120. this.rowIndex = rowIndex;
  4121. root.setPropertyInt(SPACER_LOGICAL_ROW_PROPERTY, rowIndex);
  4122. rowIndexToSpacer.put(this.rowIndex, this);
  4123. }
  4124. /**
  4125. * Updates the spacer's visibility parameters, based on whether it
  4126. * is being currently visible or not.
  4127. */
  4128. public void updateVisibility() {
  4129. if (isInViewport()) {
  4130. show();
  4131. } else {
  4132. hide();
  4133. }
  4134. }
  4135. private boolean isInViewport() {
  4136. int top = (int) Math.ceil(getTop());
  4137. int height = (int) Math.floor(getHeight());
  4138. Range location = Range.withLength(top, height);
  4139. return getViewportPixels().intersects(location);
  4140. }
  4141. public void show() {
  4142. getRootElement().getStyle().clearDisplay();
  4143. getDecoElement().getStyle().clearDisplay();
  4144. }
  4145. public void hide() {
  4146. getRootElement().getStyle().setDisplay(Display.NONE);
  4147. getDecoElement().getStyle().setDisplay(Display.NONE);
  4148. }
  4149. /**
  4150. * Crop the decorator element so that it doesn't overlap the header
  4151. * and footer sections.
  4152. *
  4153. * @param bodyTop
  4154. * the top cordinate of the escalator body
  4155. * @param bodyBottom
  4156. * the bottom cordinate of the escalator body
  4157. * @param decoWidth
  4158. * width of the deco
  4159. */
  4160. private void updateDecoClip(final double bodyTop,
  4161. final double bodyBottom, final double decoWidth) {
  4162. final int top = deco.getAbsoluteTop();
  4163. final int bottom = deco.getAbsoluteBottom();
  4164. /*
  4165. * FIXME
  4166. *
  4167. * Height and its use is a workaround for the issue where
  4168. * coordinates of the deco are not calculated yet. This will
  4169. * prevent a deco from being displayed when it's added to DOM
  4170. */
  4171. final int height = bottom - top;
  4172. if (top < bodyTop || bottom > bodyBottom) {
  4173. final double topClip = Math.max(0.0D, bodyTop - top);
  4174. final double bottomClip = height
  4175. - Math.max(0.0D, bottom - bodyBottom);
  4176. // TODO [optimize] not sure how GWT compiles this
  4177. final String clip = new StringBuilder("rect(")
  4178. .append(topClip).append("px,").append(decoWidth)
  4179. .append("px,").append(bottomClip).append("px,0)")
  4180. .toString();
  4181. deco.getStyle().setProperty("clip", clip);
  4182. } else {
  4183. deco.getStyle().setProperty("clip", "auto");
  4184. }
  4185. }
  4186. }
  4187. private final TreeMap<Integer, SpacerImpl> rowIndexToSpacer = new TreeMap<Integer, SpacerImpl>();
  4188. private SpacerUpdater spacerUpdater = SpacerUpdater.NULL;
  4189. private final ScrollHandler spacerScroller = new ScrollHandler() {
  4190. private double prevScrollX = 0;
  4191. @Override
  4192. public void onScroll(ScrollEvent event) {
  4193. if (WidgetUtil.pixelValuesEqual(getScrollLeft(), prevScrollX)) {
  4194. return;
  4195. }
  4196. prevScrollX = getScrollLeft();
  4197. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4198. spacer.setPosition(prevScrollX, spacer.getTop());
  4199. }
  4200. }
  4201. };
  4202. private HandlerRegistration spacerScrollerRegistration;
  4203. /** Width of the spacers' decos. Calculated once then cached. */
  4204. private double spacerDecoWidth = 0.0D;
  4205. public void setSpacer(int rowIndex, double height)
  4206. throws IllegalArgumentException {
  4207. if (rowIndex < -1 || rowIndex >= getBody().getRowCount()) {
  4208. throw new IllegalArgumentException("invalid row index: "
  4209. + rowIndex + ", while the body only has "
  4210. + getBody().getRowCount() + " rows.");
  4211. }
  4212. if (height >= 0) {
  4213. if (!spacerExists(rowIndex)) {
  4214. insertNewSpacer(rowIndex, height);
  4215. } else {
  4216. updateExistingSpacer(rowIndex, height);
  4217. }
  4218. } else if (spacerExists(rowIndex)) {
  4219. removeSpacer(rowIndex);
  4220. }
  4221. updateSpacerDecosVisibility();
  4222. }
  4223. /** Checks if a given element is a spacer element */
  4224. public boolean isSpacer(Element row) {
  4225. /*
  4226. * If this needs optimization, we could do a more heuristic check
  4227. * based on stylenames and stuff, instead of iterating through the
  4228. * map.
  4229. */
  4230. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4231. if (spacer.getRootElement().equals(row)) {
  4232. return true;
  4233. }
  4234. }
  4235. return false;
  4236. }
  4237. @SuppressWarnings("boxing")
  4238. void scrollToSpacer(int spacerIndex, ScrollDestination destination,
  4239. int padding) {
  4240. assert !destination.equals(ScrollDestination.MIDDLE)
  4241. || padding != 0 : "destination/padding check should be done before this method";
  4242. if (!rowIndexToSpacer.containsKey(spacerIndex)) {
  4243. throw new IllegalArgumentException(
  4244. "No spacer open at index " + spacerIndex);
  4245. }
  4246. SpacerImpl spacer = rowIndexToSpacer.get(spacerIndex);
  4247. double targetStartPx = spacer.getTop();
  4248. double targetEndPx = targetStartPx + spacer.getHeight();
  4249. Range viewportPixels = getViewportPixels();
  4250. double viewportStartPx = viewportPixels.getStart();
  4251. double viewportEndPx = viewportPixels.getEnd();
  4252. double scrollTop = getScrollPos(destination, targetStartPx,
  4253. targetEndPx, viewportStartPx, viewportEndPx, padding);
  4254. setScrollTop(scrollTop);
  4255. }
  4256. public void reapplySpacerWidths() {
  4257. // FIXME #16266 , spacers get couple pixels too much because borders
  4258. final double width = getInnerWidth() - spacerDecoWidth;
  4259. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4260. spacer.getRootElement().getStyle().setWidth(width, Unit.PX);
  4261. }
  4262. }
  4263. public void paintRemoveSpacers(Range removedRowsRange) {
  4264. removeSpacers(removedRowsRange);
  4265. shiftSpacersByRows(removedRowsRange.getStart(),
  4266. -removedRowsRange.length());
  4267. }
  4268. @SuppressWarnings("boxing")
  4269. public void removeSpacers(Range removedRange) {
  4270. Map<Integer, SpacerImpl> removedSpacers = rowIndexToSpacer.subMap(
  4271. removedRange.getStart(), true, removedRange.getEnd(),
  4272. false);
  4273. if (removedSpacers.isEmpty()) {
  4274. return;
  4275. }
  4276. for (SpacerImpl spacer : removedSpacers.values()) {
  4277. /*
  4278. * [[optimization]] TODO: Each invocation of the setHeight
  4279. * method has a cascading effect in the DOM. if this proves to
  4280. * be slow, the DOM offset could be updated as a batch.
  4281. */
  4282. destroySpacerContent(spacer);
  4283. spacer.setHeight(0); // resets row offsets
  4284. spacer.getRootElement().removeFromParent();
  4285. spacer.getDecoElement().removeFromParent();
  4286. }
  4287. removedSpacers.clear();
  4288. if (rowIndexToSpacer.isEmpty()) {
  4289. assert spacerScrollerRegistration != null : "Spacer scroller registration was null";
  4290. spacerScrollerRegistration.removeHandler();
  4291. spacerScrollerRegistration = null;
  4292. }
  4293. }
  4294. public Map<Integer, SpacerImpl> getSpacers() {
  4295. return new HashMap<Integer, SpacerImpl>(rowIndexToSpacer);
  4296. }
  4297. /**
  4298. * Calculates the sum of all spacers.
  4299. *
  4300. * @return sum of all spacers, or 0 if no spacers present
  4301. */
  4302. public double getSpacerHeightsSum() {
  4303. return getHeights(rowIndexToSpacer.values());
  4304. }
  4305. /**
  4306. * Calculates the sum of all spacers from one row index onwards.
  4307. *
  4308. * @param logicalRowIndex
  4309. * the spacer to include as the first calculated spacer
  4310. * @return the sum of all spacers from {@code logicalRowIndex} and
  4311. * onwards, or 0 if no suitable spacers were found
  4312. */
  4313. @SuppressWarnings("boxing")
  4314. public Collection<SpacerImpl> getSpacersForRowAndAfter(
  4315. int logicalRowIndex) {
  4316. return new ArrayList<SpacerImpl>(
  4317. rowIndexToSpacer.tailMap(logicalRowIndex, true).values());
  4318. }
  4319. /**
  4320. * Get all spacers from one pixel point onwards.
  4321. * <p>
  4322. *
  4323. * In this method, the {@link SpacerInclusionStrategy} has the following
  4324. * meaning when a spacer lies in the middle of either pixel argument:
  4325. * <dl>
  4326. * <dt>{@link SpacerInclusionStrategy#COMPLETE COMPLETE}
  4327. * <dd>include the spacer
  4328. * <dt>{@link SpacerInclusionStrategy#PARTIAL PARTIAL}
  4329. * <dd>include the spacer
  4330. * <dt>{@link SpacerInclusionStrategy#NONE NONE}
  4331. * <dd>ignore the spacer
  4332. * </dl>
  4333. *
  4334. * @param px
  4335. * the pixel point after which to return all spacers
  4336. * @param strategy
  4337. * the inclusion strategy regarding the {@code px}
  4338. * @return a collection of the spacers that exist after {@code px}
  4339. */
  4340. public Collection<SpacerImpl> getSpacersAfterPx(final double px,
  4341. final SpacerInclusionStrategy strategy) {
  4342. List<SpacerImpl> spacers = new ArrayList<SpacerImpl>(
  4343. rowIndexToSpacer.values());
  4344. for (int i = 0; i < spacers.size(); i++) {
  4345. SpacerImpl spacer = spacers.get(i);
  4346. double top = spacer.getTop();
  4347. double bottom = top + spacer.getHeight();
  4348. if (top > px) {
  4349. return spacers.subList(i, spacers.size());
  4350. } else if (bottom > px) {
  4351. if (strategy == SpacerInclusionStrategy.NONE) {
  4352. return spacers.subList(i + 1, spacers.size());
  4353. } else {
  4354. return spacers.subList(i, spacers.size());
  4355. }
  4356. }
  4357. }
  4358. return Collections.emptySet();
  4359. }
  4360. /**
  4361. * Gets the spacers currently rendered in the DOM.
  4362. *
  4363. * @return an unmodifiable (but live) collection of the spacers
  4364. * currently in the DOM
  4365. */
  4366. public Collection<SpacerImpl> getSpacersInDom() {
  4367. return Collections
  4368. .unmodifiableCollection(rowIndexToSpacer.values());
  4369. }
  4370. /**
  4371. * Gets the amount of pixels occupied by spacers between two pixel
  4372. * points.
  4373. * <p>
  4374. * In this method, the {@link SpacerInclusionStrategy} has the following
  4375. * meaning when a spacer lies in the middle of either pixel argument:
  4376. * <dl>
  4377. * <dt>{@link SpacerInclusionStrategy#COMPLETE COMPLETE}
  4378. * <dd>take the entire spacer into account
  4379. * <dt>{@link SpacerInclusionStrategy#PARTIAL PARTIAL}
  4380. * <dd>take only the visible area into account
  4381. * <dt>{@link SpacerInclusionStrategy#NONE NONE}
  4382. * <dd>ignore that spacer
  4383. * </dl>
  4384. *
  4385. * @param rangeTop
  4386. * the top pixel point
  4387. * @param topInclusion
  4388. * the inclusion strategy regarding {@code rangeTop}.
  4389. * @param rangeBottom
  4390. * the bottom pixel point
  4391. * @param bottomInclusion
  4392. * the inclusion strategy regarding {@code rangeBottom}.
  4393. * @return the pixels occupied by spacers between {@code rangeTop} and
  4394. * {@code rangeBottom}
  4395. */
  4396. public double getSpacerHeightsSumBetweenPx(double rangeTop,
  4397. SpacerInclusionStrategy topInclusion, double rangeBottom,
  4398. SpacerInclusionStrategy bottomInclusion) {
  4399. assert rangeTop <= rangeBottom : "rangeTop must be less than rangeBottom";
  4400. double heights = 0;
  4401. /*
  4402. * TODO [[optimize]]: this might be somewhat inefficient (due to
  4403. * iterator-based scanning, instead of using the treemap's search
  4404. * functionalities). But it should be easy to write, read, verify
  4405. * and maintain.
  4406. */
  4407. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4408. double top = spacer.getTop();
  4409. double height = spacer.getHeight();
  4410. double bottom = top + height;
  4411. /*
  4412. * If we happen to implement a DoubleRange (in addition to the
  4413. * int-based Range) at some point, the following logic should
  4414. * probably be converted into using the
  4415. * Range.partitionWith-equivalent.
  4416. */
  4417. boolean topIsAboveRange = top < rangeTop;
  4418. boolean topIsInRange = rangeTop <= top && top <= rangeBottom;
  4419. boolean topIsBelowRange = rangeBottom < top;
  4420. boolean bottomIsAboveRange = bottom < rangeTop;
  4421. boolean bottomIsInRange = rangeTop <= bottom
  4422. && bottom <= rangeBottom;
  4423. boolean bottomIsBelowRange = rangeBottom < bottom;
  4424. assert topIsAboveRange ^ topIsBelowRange
  4425. ^ topIsInRange : "Bad top logic";
  4426. assert bottomIsAboveRange ^ bottomIsBelowRange
  4427. ^ bottomIsInRange : "Bad bottom logic";
  4428. if (bottomIsAboveRange) {
  4429. continue;
  4430. } else if (topIsBelowRange) {
  4431. return heights;
  4432. } else if (topIsAboveRange && bottomIsInRange) {
  4433. switch (topInclusion) {
  4434. case PARTIAL:
  4435. heights += bottom - rangeTop;
  4436. break;
  4437. case COMPLETE:
  4438. heights += height;
  4439. break;
  4440. default:
  4441. break;
  4442. }
  4443. } else if (topIsAboveRange && bottomIsBelowRange) {
  4444. /*
  4445. * Here we arbitrarily decide that the top inclusion will
  4446. * have the honor of overriding the bottom inclusion if
  4447. * happens to be a conflict of interests.
  4448. */
  4449. switch (topInclusion) {
  4450. case NONE:
  4451. return 0;
  4452. case COMPLETE:
  4453. return height;
  4454. case PARTIAL:
  4455. return rangeBottom - rangeTop;
  4456. default:
  4457. throw new IllegalArgumentException(
  4458. "Unexpected inclusion state :" + topInclusion);
  4459. }
  4460. } else if (topIsInRange && bottomIsInRange) {
  4461. heights += height;
  4462. } else if (topIsInRange && bottomIsBelowRange) {
  4463. switch (bottomInclusion) {
  4464. case PARTIAL:
  4465. heights += rangeBottom - top;
  4466. break;
  4467. case COMPLETE:
  4468. heights += height;
  4469. break;
  4470. default:
  4471. break;
  4472. }
  4473. return heights;
  4474. } else {
  4475. assert false : "Unnaccounted-for situation";
  4476. }
  4477. }
  4478. return heights;
  4479. }
  4480. /**
  4481. * Gets the amount of pixels occupied by spacers from the top until a
  4482. * certain spot from the top of the body.
  4483. *
  4484. * @param px
  4485. * pixels counted from the top
  4486. * @return the pixels occupied by spacers up until {@code px}
  4487. */
  4488. public double getSpacerHeightsSumUntilPx(double px) {
  4489. return getSpacerHeightsSumBetweenPx(0,
  4490. SpacerInclusionStrategy.PARTIAL, px,
  4491. SpacerInclusionStrategy.PARTIAL);
  4492. }
  4493. /**
  4494. * Gets the amount of pixels occupied by spacers until a logical row
  4495. * index.
  4496. *
  4497. * @param logicalIndex
  4498. * a logical row index
  4499. * @return the pixels occupied by spacers up until {@code logicalIndex}
  4500. */
  4501. @SuppressWarnings("boxing")
  4502. public double getSpacerHeightsSumUntilIndex(int logicalIndex) {
  4503. return getHeights(
  4504. rowIndexToSpacer.headMap(logicalIndex, false).values());
  4505. }
  4506. private double getHeights(Collection<SpacerImpl> spacers) {
  4507. double heights = 0;
  4508. for (SpacerImpl spacer : spacers) {
  4509. heights += spacer.getHeight();
  4510. }
  4511. return heights;
  4512. }
  4513. /**
  4514. * Gets the height of the spacer for a row index.
  4515. *
  4516. * @param rowIndex
  4517. * the index of the row where the spacer should be
  4518. * @return the height of the spacer at index {@code rowIndex}, or 0 if
  4519. * there is no spacer there
  4520. */
  4521. public double getSpacerHeight(int rowIndex) {
  4522. SpacerImpl spacer = getSpacer(rowIndex);
  4523. if (spacer != null) {
  4524. return spacer.getHeight();
  4525. } else {
  4526. return 0;
  4527. }
  4528. }
  4529. private boolean spacerExists(int rowIndex) {
  4530. return rowIndexToSpacer.containsKey(Integer.valueOf(rowIndex));
  4531. }
  4532. @SuppressWarnings("boxing")
  4533. private void insertNewSpacer(int rowIndex, double height) {
  4534. if (spacerScrollerRegistration == null) {
  4535. spacerScrollerRegistration = addScrollHandler(spacerScroller);
  4536. }
  4537. final SpacerImpl spacer = new SpacerImpl(rowIndex);
  4538. rowIndexToSpacer.put(rowIndex, spacer);
  4539. // set the position before adding it to DOM
  4540. positions.set(spacer.getRootElement(), getScrollLeft(),
  4541. calculateSpacerTop(rowIndex));
  4542. TableRowElement spacerRoot = spacer.getRootElement();
  4543. spacerRoot.getStyle()
  4544. .setWidth(columnConfiguration.calculateRowWidth(), Unit.PX);
  4545. body.getElement().appendChild(spacerRoot);
  4546. spacer.setupDom(height);
  4547. // set the deco position, requires that spacer is in the DOM
  4548. positions.set(spacer.getDecoElement(), 0,
  4549. spacer.getTop() - spacer.getSpacerDecoTopOffset());
  4550. spacerDecoContainer.appendChild(spacer.getDecoElement());
  4551. if (spacerDecoContainer.getParentElement() == null) {
  4552. getElement().appendChild(spacerDecoContainer);
  4553. // calculate the spacer deco width, it won't change
  4554. spacerDecoWidth = WidgetUtil
  4555. .getRequiredWidthBoundingClientRectDouble(
  4556. spacer.getDecoElement());
  4557. }
  4558. initSpacerContent(spacer);
  4559. body.sortDomElements();
  4560. }
  4561. private void updateExistingSpacer(int rowIndex, double newHeight) {
  4562. getSpacer(rowIndex).setHeight(newHeight);
  4563. }
  4564. public SpacerImpl getSpacer(int rowIndex) {
  4565. return rowIndexToSpacer.get(Integer.valueOf(rowIndex));
  4566. }
  4567. private void removeSpacer(int rowIndex) {
  4568. removeSpacers(Range.withOnly(rowIndex));
  4569. }
  4570. public void setStylePrimaryName(String style) {
  4571. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4572. spacer.setStylePrimaryName(style);
  4573. }
  4574. }
  4575. public void setSpacerUpdater(SpacerUpdater spacerUpdater)
  4576. throws IllegalArgumentException {
  4577. if (spacerUpdater == null) {
  4578. throw new IllegalArgumentException(
  4579. "spacer updater cannot be null");
  4580. }
  4581. destroySpacerContent(rowIndexToSpacer.values());
  4582. this.spacerUpdater = spacerUpdater;
  4583. initSpacerContent(rowIndexToSpacer.values());
  4584. }
  4585. public SpacerUpdater getSpacerUpdater() {
  4586. return spacerUpdater;
  4587. }
  4588. private void destroySpacerContent(Iterable<SpacerImpl> spacers) {
  4589. for (SpacerImpl spacer : spacers) {
  4590. destroySpacerContent(spacer);
  4591. }
  4592. }
  4593. private void destroySpacerContent(SpacerImpl spacer) {
  4594. assert getElement().isOrHasChild(spacer
  4595. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before detaching";
  4596. assert getElement().isOrHasChild(spacer
  4597. .getElement()) : "Spacer element somehow got detached from Escalator before detaching";
  4598. spacerUpdater.destroy(spacer);
  4599. assert getElement().isOrHasChild(spacer
  4600. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before detaching";
  4601. assert getElement().isOrHasChild(spacer
  4602. .getElement()) : "Spacer element somehow got detached from Escalator before detaching";
  4603. }
  4604. private void initSpacerContent(Iterable<SpacerImpl> spacers) {
  4605. for (SpacerImpl spacer : spacers) {
  4606. initSpacerContent(spacer);
  4607. }
  4608. }
  4609. private void initSpacerContent(SpacerImpl spacer) {
  4610. assert getElement().isOrHasChild(spacer
  4611. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before attaching";
  4612. assert getElement().isOrHasChild(spacer
  4613. .getElement()) : "Spacer element somehow got detached from Escalator before attaching";
  4614. spacerUpdater.init(spacer);
  4615. assert getElement().isOrHasChild(spacer
  4616. .getRootElement()) : "Spacer's root element somehow got detached from Escalator during attaching";
  4617. assert getElement().isOrHasChild(spacer
  4618. .getElement()) : "Spacer element somehow got detached from Escalator during attaching";
  4619. spacer.updateVisibility();
  4620. }
  4621. public String getSubPartName(Element subElement) {
  4622. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  4623. if (spacer.getRootElement().isOrHasChild(subElement)) {
  4624. return "spacer[" + spacer.getRow() + "]";
  4625. }
  4626. }
  4627. return null;
  4628. }
  4629. public Element getSubPartElement(int index) {
  4630. SpacerImpl spacer = rowIndexToSpacer.get(Integer.valueOf(index));
  4631. if (spacer != null) {
  4632. return spacer.getElement();
  4633. } else {
  4634. return null;
  4635. }
  4636. }
  4637. private double calculateSpacerTop(int logicalIndex) {
  4638. return body.getRowTop(logicalIndex) + body.getDefaultRowHeight();
  4639. }
  4640. @SuppressWarnings("boxing")
  4641. private void shiftSpacerPositionsAfterRow(int changedRowIndex,
  4642. double diffPx) {
  4643. for (SpacerImpl spacer : rowIndexToSpacer
  4644. .tailMap(changedRowIndex, false).values()) {
  4645. spacer.setPositionDiff(0, diffPx);
  4646. }
  4647. }
  4648. /**
  4649. * Shifts spacers at and after a specific row by an amount of rows.
  4650. * <p>
  4651. * This moves both their associated row index and also their visual
  4652. * placement.
  4653. * <p>
  4654. * <em>Note:</em> This method does not check for the validity of any
  4655. * arguments.
  4656. *
  4657. * @param index
  4658. * the index of first row to move
  4659. * @param numberOfRows
  4660. * the number of rows to shift the spacers with. A positive
  4661. * value is downwards, a negative value is upwards.
  4662. */
  4663. public void shiftSpacersByRows(int index, int numberOfRows) {
  4664. final double pxDiff = numberOfRows * body.getDefaultRowHeight();
  4665. for (SpacerContainer.SpacerImpl spacer : getSpacersForRowAndAfter(
  4666. index)) {
  4667. spacer.setPositionDiff(0, pxDiff);
  4668. spacer.setRowIndex(spacer.getRow() + numberOfRows);
  4669. }
  4670. }
  4671. private void updateSpacerDecosVisibility() {
  4672. final Range visibleRowRange = getVisibleRowRange();
  4673. Collection<SpacerImpl> visibleSpacers = rowIndexToSpacer
  4674. .subMap(visibleRowRange.getStart() - 1,
  4675. visibleRowRange.getEnd() + 1)
  4676. .values();
  4677. if (!visibleSpacers.isEmpty()) {
  4678. final double top = tableWrapper.getAbsoluteTop()
  4679. + header.getHeightOfSection();
  4680. final double bottom = tableWrapper.getAbsoluteBottom()
  4681. - footer.getHeightOfSection();
  4682. for (SpacerImpl spacer : visibleSpacers) {
  4683. spacer.updateDecoClip(top, bottom, spacerDecoWidth);
  4684. }
  4685. }
  4686. }
  4687. }
  4688. private class ElementPositionBookkeeper {
  4689. /**
  4690. * A map containing cached values of an element's current top position.
  4691. */
  4692. private final Map<Element, Double> elementTopPositionMap = new HashMap<Element, Double>();
  4693. private final Map<Element, Double> elementLeftPositionMap = new HashMap<Element, Double>();
  4694. public void set(final Element e, final double x, final double y) {
  4695. assert e != null : "Element was null";
  4696. position.set(e, x, y);
  4697. elementTopPositionMap.put(e, Double.valueOf(y));
  4698. elementLeftPositionMap.put(e, Double.valueOf(x));
  4699. }
  4700. public double getTop(final Element e) {
  4701. Double top = elementTopPositionMap.get(e);
  4702. if (top == null) {
  4703. throw new IllegalArgumentException("Element " + e
  4704. + " was not found in the position bookkeeping");
  4705. }
  4706. return top.doubleValue();
  4707. }
  4708. public double getLeft(final Element e) {
  4709. Double left = elementLeftPositionMap.get(e);
  4710. if (left == null) {
  4711. throw new IllegalArgumentException("Element " + e
  4712. + " was not found in the position bookkeeping");
  4713. }
  4714. return left.doubleValue();
  4715. }
  4716. public void remove(Element e) {
  4717. elementTopPositionMap.remove(e);
  4718. elementLeftPositionMap.remove(e);
  4719. }
  4720. }
  4721. /**
  4722. * Utility class for parsing and storing SubPart request string attributes
  4723. * for Grid and Escalator.
  4724. *
  4725. * @since 7.5.0
  4726. */
  4727. public static class SubPartArguments {
  4728. private String type;
  4729. private int[] indices;
  4730. private SubPartArguments(String type, int[] indices) {
  4731. /*
  4732. * The constructor is private so that no third party would by
  4733. * mistake start using this parsing scheme, since it's not official
  4734. * by TestBench (yet?).
  4735. */
  4736. this.type = type;
  4737. this.indices = indices;
  4738. }
  4739. public String getType() {
  4740. return type;
  4741. }
  4742. public int getIndicesLength() {
  4743. return indices.length;
  4744. }
  4745. public int getIndex(int i) {
  4746. return indices[i];
  4747. }
  4748. public int[] getIndices() {
  4749. return Arrays.copyOf(indices, indices.length);
  4750. }
  4751. static SubPartArguments create(String subPart) {
  4752. String[] splitArgs = subPart.split("\\[");
  4753. String type = splitArgs[0];
  4754. int[] indices = new int[splitArgs.length - 1];
  4755. for (int i = 0; i < indices.length; ++i) {
  4756. String tmp = splitArgs[i + 1];
  4757. indices[i] = Integer
  4758. .parseInt(tmp.substring(0, tmp.indexOf("]", 1)));
  4759. }
  4760. return new SubPartArguments(type, indices);
  4761. }
  4762. }
  4763. // abs(atan(y/x))*(180/PI) = n deg, x = 1, solve y
  4764. /**
  4765. * The solution to
  4766. * <code>|tan<sup>-1</sup>(<i>x</i>)|&times;(180/&pi;)&nbsp;=&nbsp;30</code>
  4767. * .
  4768. * <p>
  4769. * This constant is placed in the Escalator class, instead of an inner
  4770. * class, since even mathematical expressions aren't allowed in non-static
  4771. * inner classes for constants.
  4772. */
  4773. private static final double RATIO_OF_30_DEGREES = 1 / Math.sqrt(3);
  4774. /**
  4775. * The solution to
  4776. * <code>|tan<sup>-1</sup>(<i>x</i>)|&times;(180/&pi;)&nbsp;=&nbsp;40</code>
  4777. * .
  4778. * <p>
  4779. * This constant is placed in the Escalator class, instead of an inner
  4780. * class, since even mathematical expressions aren't allowed in non-static
  4781. * inner classes for constants.
  4782. */
  4783. private static final double RATIO_OF_40_DEGREES = Math.tan(2 * Math.PI / 9);
  4784. private static final String DEFAULT_WIDTH = "500.0px";
  4785. private static final String DEFAULT_HEIGHT = "400.0px";
  4786. private FlyweightRow flyweightRow = new FlyweightRow();
  4787. /** The {@code <thead/>} tag. */
  4788. private final TableSectionElement headElem = TableSectionElement
  4789. .as(DOM.createTHead());
  4790. /** The {@code <tbody/>} tag. */
  4791. private final TableSectionElement bodyElem = TableSectionElement
  4792. .as(DOM.createTBody());
  4793. /** The {@code <tfoot/>} tag. */
  4794. private final TableSectionElement footElem = TableSectionElement
  4795. .as(DOM.createTFoot());
  4796. /**
  4797. * TODO: investigate whether this field is now unnecessary, as
  4798. * {@link ScrollbarBundle} now caches its values.
  4799. *
  4800. * @deprecated maybe...
  4801. */
  4802. @Deprecated
  4803. private double tBodyScrollTop = 0;
  4804. /**
  4805. * TODO: investigate whether this field is now unnecessary, as
  4806. * {@link ScrollbarBundle} now caches its values.
  4807. *
  4808. * @deprecated maybe...
  4809. */
  4810. @Deprecated
  4811. private double tBodyScrollLeft = 0;
  4812. private final VerticalScrollbarBundle verticalScrollbar = new VerticalScrollbarBundle();
  4813. private final HorizontalScrollbarBundle horizontalScrollbar = new HorizontalScrollbarBundle();
  4814. private final HeaderRowContainer header = new HeaderRowContainer(headElem);
  4815. private final BodyRowContainerImpl body = new BodyRowContainerImpl(
  4816. bodyElem);
  4817. private final FooterRowContainer footer = new FooterRowContainer(footElem);
  4818. /**
  4819. * Flag for keeping track of {@link RowHeightChangedEvent}s
  4820. */
  4821. private boolean rowHeightChangedEventFired = false;
  4822. private final Scroller scroller = new Scroller();
  4823. private final ColumnConfigurationImpl columnConfiguration = new ColumnConfigurationImpl();
  4824. private final DivElement tableWrapper;
  4825. private final DivElement horizontalScrollbarDeco = DivElement
  4826. .as(DOM.createDiv());
  4827. private final DivElement headerDeco = DivElement.as(DOM.createDiv());
  4828. private final DivElement footerDeco = DivElement.as(DOM.createDiv());
  4829. private final DivElement spacerDecoContainer = DivElement
  4830. .as(DOM.createDiv());
  4831. private PositionFunction position;
  4832. /** The cached width of the escalator, in pixels. */
  4833. private double widthOfEscalator = 0;
  4834. /** The cached height of the escalator, in pixels. */
  4835. private double heightOfEscalator = 0;
  4836. /** The height of Escalator in terms of body rows. */
  4837. private double heightByRows = 10.0d;
  4838. /** The height of Escalator, as defined by {@link #setHeight(String)} */
  4839. private String heightByCss = "";
  4840. private HeightMode heightMode = HeightMode.CSS;
  4841. private boolean layoutIsScheduled = false;
  4842. private ScheduledCommand layoutCommand = new ScheduledCommand() {
  4843. @Override
  4844. public void execute() {
  4845. recalculateElementSizes();
  4846. layoutIsScheduled = false;
  4847. }
  4848. };
  4849. private final ElementPositionBookkeeper positions = new ElementPositionBookkeeper();
  4850. /**
  4851. * Creates a new Escalator widget instance.
  4852. */
  4853. public Escalator() {
  4854. detectAndApplyPositionFunction();
  4855. getLogger().info("Using " + position.getClass().getSimpleName()
  4856. + " for position");
  4857. final Element root = DOM.createDiv();
  4858. setElement(root);
  4859. setupScrollbars(root);
  4860. tableWrapper = DivElement.as(DOM.createDiv());
  4861. root.appendChild(tableWrapper);
  4862. final Element table = DOM.createTable();
  4863. tableWrapper.appendChild(table);
  4864. table.appendChild(headElem);
  4865. table.appendChild(bodyElem);
  4866. table.appendChild(footElem);
  4867. Style hCornerStyle = headerDeco.getStyle();
  4868. hCornerStyle.setWidth(verticalScrollbar.getScrollbarThickness(),
  4869. Unit.PX);
  4870. hCornerStyle.setDisplay(Display.NONE);
  4871. root.appendChild(headerDeco);
  4872. Style fCornerStyle = footerDeco.getStyle();
  4873. fCornerStyle.setWidth(verticalScrollbar.getScrollbarThickness(),
  4874. Unit.PX);
  4875. fCornerStyle.setDisplay(Display.NONE);
  4876. root.appendChild(footerDeco);
  4877. Style hWrapperStyle = horizontalScrollbarDeco.getStyle();
  4878. hWrapperStyle.setDisplay(Display.NONE);
  4879. hWrapperStyle.setHeight(horizontalScrollbar.getScrollbarThickness(),
  4880. Unit.PX);
  4881. root.appendChild(horizontalScrollbarDeco);
  4882. setStylePrimaryName("v-escalator");
  4883. spacerDecoContainer.setAttribute("aria-hidden", "true");
  4884. // init default dimensions
  4885. setHeight(null);
  4886. setWidth(null);
  4887. publishJSHelpers(root);
  4888. }
  4889. private int getBodyRowCount() {
  4890. return getBody().getRowCount();
  4891. }
  4892. private native void publishJSHelpers(Element root)
  4893. /*-{
  4894. var self = this;
  4895. root.getBodyRowCount = $entry(function () {
  4896. return self.@Escalator::getBodyRowCount()();
  4897. });
  4898. }-*/;
  4899. private void setupScrollbars(final Element root) {
  4900. ScrollHandler scrollHandler = new ScrollHandler() {
  4901. @Override
  4902. public void onScroll(ScrollEvent event) {
  4903. scroller.onScroll();
  4904. fireEvent(new ScrollEvent());
  4905. }
  4906. };
  4907. int scrollbarThickness = WidgetUtil.getNativeScrollbarSize();
  4908. if (BrowserInfo.get().isIE()) {
  4909. /*
  4910. * IE refuses to scroll properly if the DIV isn't at least one pixel
  4911. * larger than the scrollbar controls themselves.
  4912. */
  4913. scrollbarThickness += 1;
  4914. }
  4915. root.appendChild(verticalScrollbar.getElement());
  4916. verticalScrollbar.addScrollHandler(scrollHandler);
  4917. verticalScrollbar.setScrollbarThickness(scrollbarThickness);
  4918. root.appendChild(horizontalScrollbar.getElement());
  4919. horizontalScrollbar.addScrollHandler(scrollHandler);
  4920. horizontalScrollbar.setScrollbarThickness(scrollbarThickness);
  4921. horizontalScrollbar
  4922. .addVisibilityHandler(new ScrollbarBundle.VisibilityHandler() {
  4923. private boolean queued = false;
  4924. @Override
  4925. public void visibilityChanged(
  4926. ScrollbarBundle.VisibilityChangeEvent event) {
  4927. if (queued) {
  4928. return;
  4929. }
  4930. queued = true;
  4931. /*
  4932. * We either lost or gained a scrollbar. In any case, we
  4933. * need to change the height, if it's defined by rows.
  4934. */
  4935. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  4936. @Override
  4937. public void execute() {
  4938. applyHeightByRows();
  4939. queued = false;
  4940. }
  4941. });
  4942. }
  4943. });
  4944. /*
  4945. * Because of all the IE hacks we've done above, we now have scrollbars
  4946. * hiding underneath a lot of DOM elements.
  4947. *
  4948. * This leads to problems with OSX (and many touch-only devices) when
  4949. * scrollbars are only shown when scrolling, as the scrollbar elements
  4950. * are hidden underneath everything. We trust that the scrollbars behave
  4951. * properly in these situations and simply pop them out with a bit of
  4952. * z-indexing.
  4953. */
  4954. if (WidgetUtil.getNativeScrollbarSize() == 0) {
  4955. verticalScrollbar.getElement().getStyle().setZIndex(90);
  4956. horizontalScrollbar.getElement().getStyle().setZIndex(90);
  4957. }
  4958. }
  4959. @Override
  4960. protected void onLoad() {
  4961. super.onLoad();
  4962. header.autodetectRowHeightLater();
  4963. body.autodetectRowHeightLater();
  4964. footer.autodetectRowHeightLater();
  4965. header.paintInsertRows(0, header.getRowCount());
  4966. footer.paintInsertRows(0, footer.getRowCount());
  4967. // recalculateElementSizes();
  4968. Scheduler.get().scheduleDeferred(new Command() {
  4969. @Override
  4970. public void execute() {
  4971. /*
  4972. * Not a faintest idea why we have to defer this call, but
  4973. * unless it is deferred, the size of the escalator will be 0x0
  4974. * after it is first detached and then reattached to the DOM.
  4975. * This only applies to a bare Escalator; inside a Grid
  4976. * everything works fine either way.
  4977. *
  4978. * The three autodetectRowHeightLater calls above seem obvious
  4979. * suspects at first. However, they don't seem to have anything
  4980. * to do with the issue, as they are no-ops in the
  4981. * detach-reattach case.
  4982. */
  4983. recalculateElementSizes();
  4984. }
  4985. });
  4986. /*
  4987. * Note: There's no need to explicitly insert rows into the body.
  4988. *
  4989. * recalculateElementSizes will recalculate the height of the body. This
  4990. * has the side-effect that as the body's size grows bigger (i.e. from 0
  4991. * to its actual height), more escalator rows are populated. Those
  4992. * escalator rows are then immediately rendered. This, in effect, is the
  4993. * same thing as inserting those rows.
  4994. *
  4995. * In fact, having an extra paintInsertRows here would lead to duplicate
  4996. * rows.
  4997. */
  4998. boolean columnsChanged = false;
  4999. for (ColumnConfigurationImpl.Column column : columnConfiguration.columns) {
  5000. boolean columnChanged = column.measureAndSetWidthIfNeeded();
  5001. if (columnChanged) {
  5002. columnsChanged = true;
  5003. }
  5004. }
  5005. if (columnsChanged) {
  5006. header.reapplyColumnWidths();
  5007. body.reapplyColumnWidths();
  5008. footer.reapplyColumnWidths();
  5009. }
  5010. verticalScrollbar.onLoad();
  5011. horizontalScrollbar.onLoad();
  5012. scroller.attachScrollListener(verticalScrollbar.getElement());
  5013. scroller.attachScrollListener(horizontalScrollbar.getElement());
  5014. scroller.attachMousewheelListener(getElement());
  5015. if (isCurrentBrowserIE11OrEdge()) {
  5016. // Touch listeners doesn't work for IE11 and Edge (#18737)
  5017. scroller.attachPointerEventListeners(getElement());
  5018. } else {
  5019. scroller.attachTouchListeners(getElement());
  5020. }
  5021. }
  5022. @Override
  5023. protected void onUnload() {
  5024. scroller.detachScrollListener(verticalScrollbar.getElement());
  5025. scroller.detachScrollListener(horizontalScrollbar.getElement());
  5026. scroller.detachMousewheelListener(getElement());
  5027. if (isCurrentBrowserIE11OrEdge()) {
  5028. // Touch listeners doesn't work for IE11 and Edge (#18737)
  5029. scroller.detachPointerEventListeners(getElement());
  5030. } else {
  5031. scroller.detachTouchListeners(getElement());
  5032. }
  5033. /*
  5034. * We can call paintRemoveRows here, because static ranges are simple to
  5035. * remove.
  5036. */
  5037. header.paintRemoveRows(0, header.getRowCount());
  5038. footer.paintRemoveRows(0, footer.getRowCount());
  5039. /*
  5040. * We can't call body.paintRemoveRows since it relies on rowCount to be
  5041. * updated correctly. Since it isn't, we'll simply and brutally rip out
  5042. * the DOM elements (in an elegant way, of course).
  5043. */
  5044. int rowsToRemove = body.getDomRowCount();
  5045. for (int i = 0; i < rowsToRemove; i++) {
  5046. int index = rowsToRemove - i - 1;
  5047. TableRowElement tr = bodyElem.getRows().getItem(index);
  5048. body.paintRemoveRow(tr, index);
  5049. positions.remove(tr);
  5050. }
  5051. body.visualRowOrder.clear();
  5052. body.setTopRowLogicalIndex(0);
  5053. super.onUnload();
  5054. }
  5055. private void detectAndApplyPositionFunction() {
  5056. /*
  5057. * firefox has a bug in its translate operation, showing white space
  5058. * when adjusting the scrollbar in BodyRowContainer.paintInsertRows
  5059. */
  5060. if (Window.Navigator.getUserAgent().contains("Firefox")) {
  5061. position = new AbsolutePosition();
  5062. return;
  5063. }
  5064. final Style docStyle = Document.get().getBody().getStyle();
  5065. if (hasProperty(docStyle, "transform")) {
  5066. if (hasProperty(docStyle, "transformStyle")) {
  5067. position = new Translate3DPosition();
  5068. } else {
  5069. position = new TranslatePosition();
  5070. }
  5071. } else if (hasProperty(docStyle, "webkitTransform")) {
  5072. position = new WebkitTranslate3DPosition();
  5073. } else {
  5074. position = new AbsolutePosition();
  5075. }
  5076. }
  5077. private Logger getLogger() {
  5078. return Logger.getLogger(getClass().getName());
  5079. }
  5080. private static native boolean hasProperty(Style style, String name)
  5081. /*-{
  5082. return style[name] !== undefined;
  5083. }-*/;
  5084. /**
  5085. * Check whether there are both columns and any row data (for either
  5086. * headers, body or footer).
  5087. *
  5088. * @return <code>true</code> if header, body or footer has rows and there
  5089. * are columns
  5090. */
  5091. private boolean hasColumnAndRowData() {
  5092. return (header.getRowCount() > 0 || body.getRowCount() > 0
  5093. || footer.getRowCount() > 0)
  5094. && columnConfiguration.getColumnCount() > 0;
  5095. }
  5096. /**
  5097. * Check whether there are any cells in the DOM.
  5098. *
  5099. * @return <code>true</code> if header, body or footer has any child
  5100. * elements
  5101. */
  5102. private boolean hasSomethingInDom() {
  5103. return headElem.hasChildNodes() || bodyElem.hasChildNodes()
  5104. || footElem.hasChildNodes();
  5105. }
  5106. /**
  5107. * Returns the row container for the header in this Escalator.
  5108. *
  5109. * @return the header. Never <code>null</code>
  5110. */
  5111. public RowContainer getHeader() {
  5112. return header;
  5113. }
  5114. /**
  5115. * Returns the row container for the body in this Escalator.
  5116. *
  5117. * @return the body. Never <code>null</code>
  5118. */
  5119. public BodyRowContainer getBody() {
  5120. return body;
  5121. }
  5122. /**
  5123. * Returns the row container for the footer in this Escalator.
  5124. *
  5125. * @return the footer. Never <code>null</code>
  5126. */
  5127. public RowContainer getFooter() {
  5128. return footer;
  5129. }
  5130. /**
  5131. * Returns the configuration object for the columns in this Escalator.
  5132. *
  5133. * @return the configuration object for the columns in this Escalator. Never
  5134. * <code>null</code>
  5135. */
  5136. public ColumnConfiguration getColumnConfiguration() {
  5137. return columnConfiguration;
  5138. }
  5139. @Override
  5140. public void setWidth(final String width) {
  5141. if (width != null && !width.isEmpty()) {
  5142. super.setWidth(width);
  5143. } else {
  5144. super.setWidth(DEFAULT_WIDTH);
  5145. }
  5146. recalculateElementSizes();
  5147. }
  5148. /**
  5149. * {@inheritDoc}
  5150. * <p>
  5151. * If Escalator is currently not in {@link HeightMode#CSS}, the given value
  5152. * is remembered, and applied once the mode is applied.
  5153. *
  5154. * @see #setHeightMode(HeightMode)
  5155. */
  5156. @Override
  5157. public void setHeight(String height) {
  5158. /*
  5159. * TODO remove method once RequiresResize and the Vaadin layoutmanager
  5160. * listening mechanisms are implemented
  5161. */
  5162. if (height != null && !height.isEmpty()) {
  5163. heightByCss = height;
  5164. } else {
  5165. if (getHeightMode() == HeightMode.UNDEFINED) {
  5166. heightByRows = body.getRowCount();
  5167. applyHeightByRows();
  5168. return;
  5169. } else {
  5170. heightByCss = DEFAULT_HEIGHT;
  5171. }
  5172. }
  5173. if (getHeightMode() == HeightMode.CSS) {
  5174. setHeightInternal(height);
  5175. }
  5176. }
  5177. private void setHeightInternal(final String height) {
  5178. final int escalatorRowsBefore = body.visualRowOrder.size();
  5179. if (height != null && !height.isEmpty()) {
  5180. super.setHeight(height);
  5181. } else {
  5182. if (getHeightMode() == HeightMode.UNDEFINED) {
  5183. int newHeightByRows = body.getRowCount();
  5184. if (heightByRows != newHeightByRows) {
  5185. heightByRows = newHeightByRows;
  5186. applyHeightByRows();
  5187. }
  5188. return;
  5189. } else {
  5190. super.setHeight(DEFAULT_HEIGHT);
  5191. }
  5192. }
  5193. recalculateElementSizes();
  5194. if (escalatorRowsBefore != body.visualRowOrder.size()) {
  5195. fireRowVisibilityChangeEvent();
  5196. }
  5197. }
  5198. /**
  5199. * Returns the vertical scroll offset. Note that this is not necessarily the
  5200. * same as the {@code scrollTop} attribute in the DOM.
  5201. *
  5202. * @return the logical vertical scroll offset
  5203. */
  5204. public double getScrollTop() {
  5205. return verticalScrollbar.getScrollPos();
  5206. }
  5207. /**
  5208. * Sets the vertical scroll offset. Note that this will not necessarily
  5209. * become the same as the {@code scrollTop} attribute in the DOM.
  5210. *
  5211. * @param scrollTop
  5212. * the number of pixels to scroll vertically
  5213. */
  5214. public void setScrollTop(final double scrollTop) {
  5215. verticalScrollbar.setScrollPos(scrollTop);
  5216. }
  5217. /**
  5218. * Returns the logical horizontal scroll offset. Note that this is not
  5219. * necessarily the same as the {@code scrollLeft} attribute in the DOM.
  5220. *
  5221. * @return the logical horizontal scroll offset
  5222. */
  5223. public double getScrollLeft() {
  5224. return horizontalScrollbar.getScrollPos();
  5225. }
  5226. /**
  5227. * Sets the logical horizontal scroll offset. Note that will not necessarily
  5228. * become the same as the {@code scrollLeft} attribute in the DOM.
  5229. *
  5230. * @param scrollLeft
  5231. * the number of pixels to scroll horizontally
  5232. */
  5233. public void setScrollLeft(final double scrollLeft) {
  5234. horizontalScrollbar.setScrollPos(scrollLeft);
  5235. }
  5236. /**
  5237. * Returns the scroll width for the escalator. Note that this is not
  5238. * necessary the same as {@code Element.scrollWidth} in the DOM.
  5239. *
  5240. * @since 7.5.0
  5241. * @return the scroll width in pixels
  5242. */
  5243. public double getScrollWidth() {
  5244. return horizontalScrollbar.getScrollSize();
  5245. }
  5246. /**
  5247. * Returns the scroll height for the escalator. Note that this is not
  5248. * necessary the same as {@code Element.scrollHeight} in the DOM.
  5249. *
  5250. * @since 7.5.0
  5251. * @return the scroll height in pixels
  5252. */
  5253. public double getScrollHeight() {
  5254. return verticalScrollbar.getScrollSize();
  5255. }
  5256. /**
  5257. * Scrolls the body horizontally so that the column at the given index is
  5258. * visible and there is at least {@code padding} pixels in the direction of
  5259. * the given scroll destination.
  5260. *
  5261. * @param columnIndex
  5262. * the index of the column to scroll to
  5263. * @param destination
  5264. * where the column should be aligned visually after scrolling
  5265. * @param padding
  5266. * the number pixels to place between the scrolled-to column and
  5267. * the viewport edge.
  5268. * @throws IndexOutOfBoundsException
  5269. * if {@code columnIndex} is not a valid index for an existing
  5270. * column
  5271. * @throws IllegalArgumentException
  5272. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  5273. * and padding is nonzero; or if the indicated column is frozen;
  5274. * or if {@code destination == null}
  5275. */
  5276. public void scrollToColumn(final int columnIndex,
  5277. final ScrollDestination destination, final int padding)
  5278. throws IndexOutOfBoundsException, IllegalArgumentException {
  5279. validateScrollDestination(destination, padding);
  5280. verifyValidColumnIndex(columnIndex);
  5281. if (columnIndex < columnConfiguration.frozenColumns) {
  5282. throw new IllegalArgumentException(
  5283. "The given column index " + columnIndex + " is frozen.");
  5284. }
  5285. scroller.scrollToColumn(columnIndex, destination, padding);
  5286. }
  5287. private void verifyValidColumnIndex(final int columnIndex)
  5288. throws IndexOutOfBoundsException {
  5289. if (columnIndex < 0
  5290. || columnIndex >= columnConfiguration.getColumnCount()) {
  5291. throw new IndexOutOfBoundsException("The given column index "
  5292. + columnIndex + " does not exist.");
  5293. }
  5294. }
  5295. /**
  5296. * Scrolls the body vertically so that the row at the given index is visible
  5297. * and there is at least {@literal padding} pixels to the given scroll
  5298. * destination.
  5299. *
  5300. * @param rowIndex
  5301. * the index of the logical row to scroll to
  5302. * @param destination
  5303. * where the row should be aligned visually after scrolling
  5304. * @param padding
  5305. * the number pixels to place between the scrolled-to row and the
  5306. * viewport edge.
  5307. * @throws IndexOutOfBoundsException
  5308. * if {@code rowIndex} is not a valid index for an existing row
  5309. * @throws IllegalArgumentException
  5310. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  5311. * and padding is nonzero; or if {@code destination == null}
  5312. * @see #scrollToRowAndSpacer(int, ScrollDestination, int)
  5313. * @see #scrollToSpacer(int, ScrollDestination, int)
  5314. */
  5315. public void scrollToRow(final int rowIndex,
  5316. final ScrollDestination destination, final int padding)
  5317. throws IndexOutOfBoundsException, IllegalArgumentException {
  5318. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  5319. @Override
  5320. public void execute() {
  5321. validateScrollDestination(destination, padding);
  5322. verifyValidRowIndex(rowIndex);
  5323. scroller.scrollToRow(rowIndex, destination, padding);
  5324. }
  5325. });
  5326. }
  5327. private void verifyValidRowIndex(final int rowIndex) {
  5328. if (rowIndex < 0 || rowIndex >= body.getRowCount()) {
  5329. throw new IndexOutOfBoundsException(
  5330. "The given row index " + rowIndex + " does not exist.");
  5331. }
  5332. }
  5333. /**
  5334. * Scrolls the body vertically so that the spacer at the given row index is
  5335. * visible and there is at least {@literal padding} pixesl to the given
  5336. * scroll destination.
  5337. *
  5338. * @since 7.5.0
  5339. * @param spacerIndex
  5340. * the row index of the spacer to scroll to
  5341. * @param destination
  5342. * where the spacer should be aligned visually after scrolling
  5343. * @param padding
  5344. * the number of pixels to place between the scrolled-to spacer
  5345. * and the viewport edge
  5346. * @throws IllegalArgumentException
  5347. * if {@code spacerIndex} is not an opened spacer; or if
  5348. * {@code destination} is {@link ScrollDestination#MIDDLE} and
  5349. * padding is nonzero; or if {@code destination == null}
  5350. * @see #scrollToRow(int, ScrollDestination, int)
  5351. * @see #scrollToRowAndSpacer(int, ScrollDestination, int)
  5352. */
  5353. public void scrollToSpacer(final int spacerIndex,
  5354. ScrollDestination destination, final int padding)
  5355. throws IllegalArgumentException {
  5356. validateScrollDestination(destination, padding);
  5357. body.scrollToSpacer(spacerIndex, destination, padding);
  5358. }
  5359. /**
  5360. * Scrolls vertically to a row and the spacer below it.
  5361. * <p>
  5362. * If a spacer is not open at that index, this method behaves like
  5363. * {@link #scrollToRow(int, ScrollDestination, int)}
  5364. *
  5365. * @since 7.5.0
  5366. * @param rowIndex
  5367. * the index of the logical row to scroll to. -1 takes the
  5368. * topmost spacer into account as well.
  5369. * @param destination
  5370. * where the row should be aligned visually after scrolling
  5371. * @param padding
  5372. * the number pixels to place between the scrolled-to row and the
  5373. * viewport edge.
  5374. * @see #scrollToRow(int, ScrollDestination, int)
  5375. * @see #scrollToSpacer(int, ScrollDestination, int)
  5376. * @throws IllegalArgumentException
  5377. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  5378. * and {@code padding} is not zero; or if {@code rowIndex} is
  5379. * not a valid row index, or -1; or if
  5380. * {@code destination == null}; or if {@code rowIndex == -1} and
  5381. * there is no spacer open at that index.
  5382. */
  5383. public void scrollToRowAndSpacer(final int rowIndex,
  5384. final ScrollDestination destination, final int padding)
  5385. throws IllegalArgumentException {
  5386. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  5387. @Override
  5388. public void execute() {
  5389. validateScrollDestination(destination, padding);
  5390. if (rowIndex != -1) {
  5391. verifyValidRowIndex(rowIndex);
  5392. }
  5393. // row range
  5394. final Range rowRange;
  5395. if (rowIndex != -1) {
  5396. int rowTop = (int) Math.floor(body.getRowTop(rowIndex));
  5397. int rowHeight = (int) Math.ceil(body.getDefaultRowHeight());
  5398. rowRange = Range.withLength(rowTop, rowHeight);
  5399. } else {
  5400. rowRange = Range.withLength(0, 0);
  5401. }
  5402. // get spacer
  5403. final SpacerContainer.SpacerImpl spacer = body.spacerContainer
  5404. .getSpacer(rowIndex);
  5405. if (rowIndex == -1 && spacer == null) {
  5406. throw new IllegalArgumentException(
  5407. "Cannot scroll to row index "
  5408. + "-1, as there is no spacer open at that index.");
  5409. }
  5410. // make into target range
  5411. final Range targetRange;
  5412. if (spacer != null) {
  5413. final int spacerTop = (int) Math.floor(spacer.getTop());
  5414. final int spacerHeight = (int) Math
  5415. .ceil(spacer.getHeight());
  5416. Range spacerRange = Range.withLength(spacerTop,
  5417. spacerHeight);
  5418. targetRange = rowRange.combineWith(spacerRange);
  5419. } else {
  5420. targetRange = rowRange;
  5421. }
  5422. // get params
  5423. int targetStart = targetRange.getStart();
  5424. int targetEnd = targetRange.getEnd();
  5425. double viewportStart = getScrollTop();
  5426. double viewportEnd = viewportStart + body.getHeightOfSection();
  5427. double scrollPos = getScrollPos(destination, targetStart,
  5428. targetEnd, viewportStart, viewportEnd, padding);
  5429. setScrollTop(scrollPos);
  5430. }
  5431. });
  5432. }
  5433. private static void validateScrollDestination(
  5434. final ScrollDestination destination, final int padding) {
  5435. if (destination == null) {
  5436. throw new IllegalArgumentException("Destination cannot be null");
  5437. }
  5438. if (destination == ScrollDestination.MIDDLE && padding != 0) {
  5439. throw new IllegalArgumentException(
  5440. "You cannot have a padding with a MIDDLE destination");
  5441. }
  5442. }
  5443. /**
  5444. * Recalculates the dimensions for all elements that require manual
  5445. * calculations. Also updates the dimension caches.
  5446. * <p>
  5447. * <em>Note:</em> This method has the <strong>side-effect</strong>
  5448. * automatically makes sure that an appropriate amount of escalator rows are
  5449. * present. So, if the body area grows, more <strong>escalator rows might be
  5450. * inserted</strong>. Conversely, if the body area shrinks,
  5451. * <strong>escalator rows might be removed</strong>.
  5452. */
  5453. private void recalculateElementSizes() {
  5454. if (!isAttached()) {
  5455. return;
  5456. }
  5457. Profiler.enter("Escalator.recalculateElementSizes");
  5458. widthOfEscalator = Math.max(0, WidgetUtil
  5459. .getRequiredWidthBoundingClientRectDouble(getElement()));
  5460. heightOfEscalator = Math.max(0, WidgetUtil
  5461. .getRequiredHeightBoundingClientRectDouble(getElement()));
  5462. header.recalculateSectionHeight();
  5463. body.recalculateSectionHeight();
  5464. footer.recalculateSectionHeight();
  5465. scroller.recalculateScrollbarsForVirtualViewport();
  5466. body.verifyEscalatorCount();
  5467. body.reapplySpacerWidths();
  5468. Profiler.leave("Escalator.recalculateElementSizes");
  5469. }
  5470. /**
  5471. * Snap deltas of x and y to the major four axes (up, down, left, right)
  5472. * with a threshold of a number of degrees from those axes.
  5473. *
  5474. * @param deltaX
  5475. * the delta in the x axis
  5476. * @param deltaY
  5477. * the delta in the y axis
  5478. * @param thresholdRatio
  5479. * the threshold in ratio (0..1) between x and y for when to snap
  5480. * @return a two-element array: <code>[snappedX, snappedY]</code>
  5481. */
  5482. private static double[] snapDeltas(final double deltaX, final double deltaY,
  5483. final double thresholdRatio) {
  5484. final double[] array = new double[2];
  5485. if (deltaX != 0 && deltaY != 0) {
  5486. final double aDeltaX = Math.abs(deltaX);
  5487. final double aDeltaY = Math.abs(deltaY);
  5488. final double yRatio = aDeltaY / aDeltaX;
  5489. final double xRatio = aDeltaX / aDeltaY;
  5490. array[0] = (xRatio < thresholdRatio) ? 0 : deltaX;
  5491. array[1] = (yRatio < thresholdRatio) ? 0 : deltaY;
  5492. } else {
  5493. array[0] = deltaX;
  5494. array[1] = deltaY;
  5495. }
  5496. return array;
  5497. }
  5498. /**
  5499. * Adds an event handler that gets notified when the range of visible rows
  5500. * changes e.g. because of scrolling, row resizing or spacers
  5501. * appearing/disappearing.
  5502. *
  5503. * @param rowVisibilityChangeHandler
  5504. * the event handler
  5505. * @return a handler registration for the added handler
  5506. */
  5507. public HandlerRegistration addRowVisibilityChangeHandler(
  5508. RowVisibilityChangeHandler rowVisibilityChangeHandler) {
  5509. return addHandler(rowVisibilityChangeHandler,
  5510. RowVisibilityChangeEvent.TYPE);
  5511. }
  5512. private void fireRowVisibilityChangeEvent() {
  5513. if (!body.visualRowOrder.isEmpty()) {
  5514. int visibleRangeStart = body
  5515. .getLogicalRowIndex(body.visualRowOrder.getFirst());
  5516. int visibleRangeEnd = body
  5517. .getLogicalRowIndex(body.visualRowOrder.getLast()) + 1;
  5518. int visibleRowCount = visibleRangeEnd - visibleRangeStart;
  5519. fireEvent(new RowVisibilityChangeEvent(visibleRangeStart,
  5520. visibleRowCount));
  5521. } else {
  5522. fireEvent(new RowVisibilityChangeEvent(0, 0));
  5523. }
  5524. }
  5525. /**
  5526. * Gets the logical index range of currently visible rows.
  5527. *
  5528. * @return logical index range of visible rows
  5529. */
  5530. public Range getVisibleRowRange() {
  5531. if (!body.visualRowOrder.isEmpty()) {
  5532. return Range.withLength(body.getTopRowLogicalIndex(),
  5533. body.visualRowOrder.size());
  5534. } else {
  5535. return Range.withLength(0, 0);
  5536. }
  5537. }
  5538. /**
  5539. * Returns the widget from a cell node or <code>null</code> if there is no
  5540. * widget in the cell
  5541. *
  5542. * @param cellNode
  5543. * The cell node
  5544. */
  5545. static Widget getWidgetFromCell(Node cellNode) {
  5546. Node possibleWidgetNode = cellNode.getFirstChild();
  5547. if (possibleWidgetNode != null
  5548. && possibleWidgetNode.getNodeType() == Node.ELEMENT_NODE) {
  5549. @SuppressWarnings("deprecation")
  5550. com.google.gwt.user.client.Element castElement = (com.google.gwt.user.client.Element) possibleWidgetNode
  5551. .cast();
  5552. Widget w = WidgetUtil.findWidget(castElement, null);
  5553. // Ensure findWidget did not traverse past the cell element in the
  5554. // DOM hierarchy
  5555. if (cellNode.isOrHasChild(w.getElement())) {
  5556. return w;
  5557. }
  5558. }
  5559. return null;
  5560. }
  5561. @Override
  5562. public void setStylePrimaryName(String style) {
  5563. super.setStylePrimaryName(style);
  5564. verticalScrollbar.setStylePrimaryName(style);
  5565. horizontalScrollbar.setStylePrimaryName(style);
  5566. UIObject.setStylePrimaryName(tableWrapper, style + "-tablewrapper");
  5567. UIObject.setStylePrimaryName(headerDeco, style + "-header-deco");
  5568. UIObject.setStylePrimaryName(footerDeco, style + "-footer-deco");
  5569. UIObject.setStylePrimaryName(horizontalScrollbarDeco,
  5570. style + "-horizontal-scrollbar-deco");
  5571. UIObject.setStylePrimaryName(spacerDecoContainer,
  5572. style + "-spacer-deco-container");
  5573. header.setStylePrimaryName(style);
  5574. body.setStylePrimaryName(style);
  5575. footer.setStylePrimaryName(style);
  5576. }
  5577. /**
  5578. * Sets the number of rows that should be visible in Escalator's body, while
  5579. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  5580. * <p>
  5581. * If Escalator is currently not in {@link HeightMode#ROW}, the given value
  5582. * is remembered, and applied once the mode is applied.
  5583. *
  5584. * @param rows
  5585. * the number of rows that should be visible in Escalator's body
  5586. * @throws IllegalArgumentException
  5587. * if {@code rows} is &leq; 0, {@link Double#isInifinite(double)
  5588. * infinite} or {@link Double#isNaN(double) NaN}.
  5589. * @see #setHeightMode(HeightMode)
  5590. */
  5591. public void setHeightByRows(double rows) throws IllegalArgumentException {
  5592. if (rows <= 0) {
  5593. throw new IllegalArgumentException(
  5594. "The number of rows must be a positive number.");
  5595. } else if (Double.isInfinite(rows)) {
  5596. throw new IllegalArgumentException(
  5597. "The number of rows must be finite.");
  5598. } else if (Double.isNaN(rows)) {
  5599. throw new IllegalArgumentException("The number must not be NaN.");
  5600. }
  5601. heightByRows = rows;
  5602. applyHeightByRows();
  5603. }
  5604. /**
  5605. * Gets the amount of rows in Escalator's body that are shown, while
  5606. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  5607. * <p>
  5608. * By default, it is 10.
  5609. *
  5610. * @return the amount of rows that are being shown in Escalator's body
  5611. * @see #setHeightByRows(double)
  5612. */
  5613. public double getHeightByRows() {
  5614. return heightByRows;
  5615. }
  5616. /**
  5617. * Reapplies the row-based height of the Grid, if Grid currently should
  5618. * define its height that way.
  5619. */
  5620. private void applyHeightByRows() {
  5621. if (heightMode != HeightMode.ROW
  5622. && heightMode != HeightMode.UNDEFINED) {
  5623. return;
  5624. }
  5625. double headerHeight = header.getHeightOfSection();
  5626. double footerHeight = footer.getHeightOfSection();
  5627. double bodyHeight = body.getDefaultRowHeight() * heightByRows;
  5628. double scrollbar = horizontalScrollbar.showsScrollHandle()
  5629. ? horizontalScrollbar.getScrollbarThickness()
  5630. : 0;
  5631. double spacerHeight = 0; // ignored if HeightMode.ROW
  5632. if (heightMode == HeightMode.UNDEFINED) {
  5633. spacerHeight = body.spacerContainer.getSpacerHeightsSum();
  5634. }
  5635. double totalHeight = headerHeight + bodyHeight + spacerHeight
  5636. + scrollbar + footerHeight;
  5637. setHeightInternal(totalHeight + "px");
  5638. }
  5639. /**
  5640. * Defines the mode in which the Escalator widget's height is calculated.
  5641. * <p>
  5642. * If {@link HeightMode#CSS} is given, Escalator will respect the values
  5643. * given via {@link #setHeight(String)}, and behave as a traditional Widget.
  5644. * <p>
  5645. * If {@link HeightMode#ROW} is given, Escalator will make sure that the
  5646. * {@link #getBody() body} will display as many rows as
  5647. * {@link #getHeightByRows()} defines. <em>Note:</em> If headers/footers are
  5648. * inserted or removed, the widget will resize itself to still display the
  5649. * required amount of rows in its body. It also takes the horizontal
  5650. * scrollbar into account.
  5651. *
  5652. * @param heightMode
  5653. * the mode in to which Escalator should be set
  5654. */
  5655. public void setHeightMode(HeightMode heightMode) {
  5656. /*
  5657. * This method is a workaround for the fact that Vaadin re-applies
  5658. * widget dimensions (height/width) on each state change event. The
  5659. * original design was to have setHeight an setHeightByRow be equals,
  5660. * and whichever was called the latest was considered in effect.
  5661. *
  5662. * But, because of Vaadin always calling setHeight on the widget, this
  5663. * approach doesn't work.
  5664. */
  5665. if (heightMode != this.heightMode) {
  5666. this.heightMode = heightMode;
  5667. switch (this.heightMode) {
  5668. case CSS:
  5669. setHeight(heightByCss);
  5670. break;
  5671. case ROW:
  5672. setHeightByRows(heightByRows);
  5673. break;
  5674. case UNDEFINED:
  5675. setHeightByRows(body.getRowCount());
  5676. break;
  5677. default:
  5678. throw new IllegalStateException("Unimplemented feature "
  5679. + "- unknown HeightMode: " + this.heightMode);
  5680. }
  5681. }
  5682. }
  5683. /**
  5684. * Returns the current {@link HeightMode} the Escalator is in.
  5685. * <p>
  5686. * Defaults to {@link HeightMode#CSS}.
  5687. *
  5688. * @return the current HeightMode
  5689. */
  5690. public HeightMode getHeightMode() {
  5691. return heightMode;
  5692. }
  5693. /**
  5694. * Returns the {@link RowContainer} which contains the element.
  5695. *
  5696. * @param element
  5697. * the element to check for
  5698. * @return the container the element is in or <code>null</code> if element
  5699. * is not present in any container.
  5700. */
  5701. public RowContainer findRowContainer(Element element) {
  5702. if (getHeader().getElement() != element
  5703. && getHeader().getElement().isOrHasChild(element)) {
  5704. return getHeader();
  5705. } else if (getBody().getElement() != element
  5706. && getBody().getElement().isOrHasChild(element)) {
  5707. return getBody();
  5708. } else if (getFooter().getElement() != element
  5709. && getFooter().getElement().isOrHasChild(element)) {
  5710. return getFooter();
  5711. }
  5712. return null;
  5713. }
  5714. /**
  5715. * Sets whether a scroll direction is locked or not.
  5716. * <p>
  5717. * If a direction is locked, the escalator will refuse to scroll in that
  5718. * direction.
  5719. *
  5720. * @param direction
  5721. * the orientation of the scroll to set the lock status
  5722. * @param locked
  5723. * <code>true</code> to lock, <code>false</code> to unlock
  5724. */
  5725. public void setScrollLocked(ScrollbarBundle.Direction direction,
  5726. boolean locked) {
  5727. switch (direction) {
  5728. case HORIZONTAL:
  5729. horizontalScrollbar.setLocked(locked);
  5730. break;
  5731. case VERTICAL:
  5732. verticalScrollbar.setLocked(locked);
  5733. break;
  5734. default:
  5735. throw new UnsupportedOperationException(
  5736. "Unexpected value: " + direction);
  5737. }
  5738. }
  5739. /**
  5740. * Checks whether or not an direction is locked for scrolling.
  5741. *
  5742. * @param direction
  5743. * the direction of the scroll of which to check the lock status
  5744. * @return <code>true</code> if the direction is locked
  5745. */
  5746. public boolean isScrollLocked(ScrollbarBundle.Direction direction) {
  5747. switch (direction) {
  5748. case HORIZONTAL:
  5749. return horizontalScrollbar.isLocked();
  5750. case VERTICAL:
  5751. return verticalScrollbar.isLocked();
  5752. default:
  5753. throw new UnsupportedOperationException(
  5754. "Unexpected value: " + direction);
  5755. }
  5756. }
  5757. /**
  5758. * Adds a scroll handler to this escalator.
  5759. *
  5760. * @param handler
  5761. * the scroll handler to add
  5762. * @return a handler registration for the registered scroll handler
  5763. */
  5764. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  5765. return addHandler(handler, ScrollEvent.TYPE);
  5766. }
  5767. @Override
  5768. public boolean isWorkPending() {
  5769. return body.domSorter.waiting || verticalScrollbar.isWorkPending()
  5770. || horizontalScrollbar.isWorkPending() || layoutIsScheduled;
  5771. }
  5772. @Override
  5773. public void onResize() {
  5774. if (isAttached() && !layoutIsScheduled) {
  5775. layoutIsScheduled = true;
  5776. Scheduler.get().scheduleFinally(layoutCommand);
  5777. }
  5778. }
  5779. /**
  5780. * Gets the maximum number of body rows that can be visible on the screen at
  5781. * once.
  5782. *
  5783. * @return the maximum capacity
  5784. */
  5785. public int getMaxVisibleRowCount() {
  5786. return body.getMaxVisibleRowCount();
  5787. }
  5788. /**
  5789. * Gets the escalator's inner width. This is the entire width in pixels,
  5790. * without the vertical scrollbar.
  5791. *
  5792. * @return escalator's inner width
  5793. */
  5794. public double getInnerWidth() {
  5795. return WidgetUtil
  5796. .getRequiredWidthBoundingClientRectDouble(tableWrapper);
  5797. }
  5798. /**
  5799. * Resets all cached pixel sizes and reads new values from the DOM. This
  5800. * methods should be used e.g. when styles affecting the dimensions of
  5801. * elements in this escalator have been changed.
  5802. */
  5803. public void resetSizesFromDom() {
  5804. header.autodetectRowHeightNow();
  5805. body.autodetectRowHeightNow();
  5806. footer.autodetectRowHeightNow();
  5807. for (int i = 0; i < columnConfiguration.getColumnCount(); i++) {
  5808. columnConfiguration.setColumnWidth(i,
  5809. columnConfiguration.getColumnWidth(i));
  5810. }
  5811. }
  5812. private Range getViewportPixels() {
  5813. int from = (int) Math.floor(verticalScrollbar.getScrollPos());
  5814. int to = (int) body.getHeightOfSection();
  5815. return Range.withLength(from, to);
  5816. }
  5817. @Override
  5818. @SuppressWarnings("deprecation")
  5819. public com.google.gwt.user.client.Element getSubPartElement(
  5820. String subPart) {
  5821. SubPartArguments args = SubPartArguments.create(subPart);
  5822. Element tableStructureElement = getSubPartElementTableStructure(args);
  5823. if (tableStructureElement != null) {
  5824. return DOM.asOld(tableStructureElement);
  5825. }
  5826. Element spacerElement = getSubPartElementSpacer(args);
  5827. if (spacerElement != null) {
  5828. return DOM.asOld(spacerElement);
  5829. }
  5830. return null;
  5831. }
  5832. private Element getSubPartElementTableStructure(SubPartArguments args) {
  5833. String type = args.getType();
  5834. int[] indices = args.getIndices();
  5835. // Get correct RowContainer for type from Escalator
  5836. RowContainer container = null;
  5837. if (type.equalsIgnoreCase("header")) {
  5838. container = getHeader();
  5839. } else if (type.equalsIgnoreCase("cell")) {
  5840. // If wanted row is not visible, we need to scroll there.
  5841. Range visibleRowRange = getVisibleRowRange();
  5842. if (indices.length > 0) {
  5843. // Contains a row number, ensure it is available and visible
  5844. boolean rowInCache = visibleRowRange.contains(indices[0]);
  5845. // Scrolling might be a no-op if row is already in the viewport
  5846. scrollToRow(indices[0], ScrollDestination.ANY, 0);
  5847. if (!rowInCache) {
  5848. // Row was not in cache, scrolling caused lazy loading and
  5849. // the caller needs to wait and call this method again to be
  5850. // able to get the requested element
  5851. return null;
  5852. }
  5853. }
  5854. container = getBody();
  5855. } else if (type.equalsIgnoreCase("footer")) {
  5856. container = getFooter();
  5857. }
  5858. if (null != container) {
  5859. if (indices.length == 0) {
  5860. // No indexing. Just return the wanted container element
  5861. return container.getElement();
  5862. } else {
  5863. try {
  5864. return getSubPart(container, indices);
  5865. } catch (Exception e) {
  5866. getLogger().log(Level.SEVERE, e.getMessage());
  5867. }
  5868. }
  5869. }
  5870. return null;
  5871. }
  5872. private Element getSubPart(RowContainer container, int[] indices) {
  5873. Element targetElement = container.getRowElement(indices[0]);
  5874. // Scroll wanted column to view if able
  5875. if (indices.length > 1 && targetElement != null) {
  5876. if (getColumnConfiguration().getFrozenColumnCount() <= indices[1]) {
  5877. scrollToColumn(indices[1], ScrollDestination.ANY, 0);
  5878. }
  5879. targetElement = getCellFromRow(TableRowElement.as(targetElement),
  5880. indices[1]);
  5881. for (int i = 2; i < indices.length && targetElement != null; ++i) {
  5882. targetElement = (Element) targetElement.getChild(indices[i]);
  5883. }
  5884. }
  5885. return targetElement;
  5886. }
  5887. private static Element getCellFromRow(TableRowElement rowElement,
  5888. int index) {
  5889. int childCount = rowElement.getCells().getLength();
  5890. if (index < 0 || index >= childCount) {
  5891. return null;
  5892. }
  5893. TableCellElement currentCell = null;
  5894. boolean indexInColspan = false;
  5895. int i = 0;
  5896. while (!indexInColspan) {
  5897. currentCell = rowElement.getCells().getItem(i);
  5898. // Calculate if this is the cell we are looking for
  5899. int colSpan = currentCell.getColSpan();
  5900. indexInColspan = index < colSpan + i;
  5901. // Increment by colspan to skip over hidden cells
  5902. i += colSpan;
  5903. }
  5904. return currentCell;
  5905. }
  5906. private Element getSubPartElementSpacer(SubPartArguments args) {
  5907. if ("spacer".equals(args.getType()) && args.getIndicesLength() == 1) {
  5908. return body.spacerContainer.getSubPartElement(args.getIndex(0));
  5909. } else {
  5910. return null;
  5911. }
  5912. }
  5913. @Override
  5914. @SuppressWarnings("deprecation")
  5915. public String getSubPartName(
  5916. com.google.gwt.user.client.Element subElement) {
  5917. /*
  5918. * The spacer check needs to be before table structure check, because
  5919. * (for now) the table structure will take spacer elements into account
  5920. * as well, when it shouldn't.
  5921. */
  5922. String spacer = getSubPartNameSpacer(subElement);
  5923. if (spacer != null) {
  5924. return spacer;
  5925. }
  5926. String tableStructure = getSubPartNameTableStructure(subElement);
  5927. if (tableStructure != null) {
  5928. return tableStructure;
  5929. }
  5930. return null;
  5931. }
  5932. private String getSubPartNameTableStructure(Element subElement) {
  5933. List<RowContainer> containers = Arrays.asList(getHeader(), getBody(),
  5934. getFooter());
  5935. List<String> containerType = Arrays.asList("header", "cell", "footer");
  5936. for (int i = 0; i < containers.size(); ++i) {
  5937. RowContainer container = containers.get(i);
  5938. boolean containerRow = (subElement.getTagName()
  5939. .equalsIgnoreCase("tr")
  5940. && subElement.getParentElement() == container.getElement());
  5941. if (containerRow) {
  5942. /*
  5943. * Wanted SubPart is row that is a child of containers root to
  5944. * get indices, we use a cell that is a child of this row
  5945. */
  5946. subElement = subElement.getFirstChildElement();
  5947. }
  5948. Cell cell = container.getCell(subElement);
  5949. if (cell != null) {
  5950. // Skip the column index if subElement was a child of root
  5951. return containerType.get(i) + "[" + cell.getRow()
  5952. + (containerRow ? "]" : "][" + cell.getColumn() + "]");
  5953. }
  5954. }
  5955. return null;
  5956. }
  5957. private String getSubPartNameSpacer(Element subElement) {
  5958. return body.spacerContainer.getSubPartName(subElement);
  5959. }
  5960. private void logWarning(String message) {
  5961. getLogger().warning(message);
  5962. }
  5963. /**
  5964. * This is an internal method for calculating minimum width for Column
  5965. * resize.
  5966. *
  5967. * @return minimum width for column
  5968. */
  5969. double getMinCellWidth(int colIndex) {
  5970. return columnConfiguration.getMinCellWidth(colIndex);
  5971. }
  5972. /**
  5973. * Internal method for checking whether the browser is IE11 or Edge
  5974. *
  5975. * @return true only if the current browser is IE11, or Edge
  5976. */
  5977. private static boolean isCurrentBrowserIE11OrEdge() {
  5978. return BrowserInfo.get().isIE11() || BrowserInfo.get().isEdge();
  5979. }
  5980. }