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 339KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465
  1. /*
  2. * Copyright 2000-2018 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.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.Optional;
  28. import java.util.TreeMap;
  29. import java.util.function.Consumer;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;
  32. import java.util.stream.Stream;
  33. import com.google.gwt.animation.client.Animation;
  34. import com.google.gwt.animation.client.AnimationScheduler;
  35. import com.google.gwt.animation.client.AnimationScheduler.AnimationCallback;
  36. import com.google.gwt.animation.client.AnimationScheduler.AnimationHandle;
  37. import com.google.gwt.core.client.Duration;
  38. import com.google.gwt.core.client.JavaScriptException;
  39. import com.google.gwt.core.client.JavaScriptObject;
  40. import com.google.gwt.core.client.JsArray;
  41. import com.google.gwt.core.client.Scheduler;
  42. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  43. import com.google.gwt.dom.client.DivElement;
  44. import com.google.gwt.dom.client.Document;
  45. import com.google.gwt.dom.client.Element;
  46. import com.google.gwt.dom.client.NativeEvent;
  47. import com.google.gwt.dom.client.Node;
  48. import com.google.gwt.dom.client.NodeList;
  49. import com.google.gwt.dom.client.Style;
  50. import com.google.gwt.dom.client.Style.Display;
  51. import com.google.gwt.dom.client.Style.Unit;
  52. import com.google.gwt.dom.client.TableCellElement;
  53. import com.google.gwt.dom.client.TableRowElement;
  54. import com.google.gwt.dom.client.TableSectionElement;
  55. import com.google.gwt.dom.client.Touch;
  56. import com.google.gwt.event.dom.client.KeyCodes;
  57. import com.google.gwt.event.shared.HandlerRegistration;
  58. import com.google.gwt.logging.client.LogConfiguration;
  59. import com.google.gwt.user.client.DOM;
  60. import com.google.gwt.user.client.Event;
  61. import com.google.gwt.user.client.Window;
  62. import com.google.gwt.user.client.ui.RequiresResize;
  63. import com.google.gwt.user.client.ui.RootPanel;
  64. import com.google.gwt.user.client.ui.UIObject;
  65. import com.google.gwt.user.client.ui.Widget;
  66. import com.vaadin.client.BrowserInfo;
  67. import com.vaadin.client.ComputedStyle;
  68. import com.vaadin.client.DeferredWorker;
  69. import com.vaadin.client.Profiler;
  70. import com.vaadin.client.WidgetUtil;
  71. import com.vaadin.client.ui.SubPartAware;
  72. import com.vaadin.client.widget.escalator.Cell;
  73. import com.vaadin.client.widget.escalator.ColumnConfiguration;
  74. import com.vaadin.client.widget.escalator.EscalatorUpdater;
  75. import com.vaadin.client.widget.escalator.FlyweightCell;
  76. import com.vaadin.client.widget.escalator.FlyweightRow;
  77. import com.vaadin.client.widget.escalator.PositionFunction;
  78. import com.vaadin.client.widget.escalator.PositionFunction.Translate3DPosition;
  79. import com.vaadin.client.widget.escalator.PositionFunction.TranslatePosition;
  80. import com.vaadin.client.widget.escalator.PositionFunction.WebkitTranslate3DPosition;
  81. import com.vaadin.client.widget.escalator.Row;
  82. import com.vaadin.client.widget.escalator.RowContainer;
  83. import com.vaadin.client.widget.escalator.RowContainer.BodyRowContainer;
  84. import com.vaadin.client.widget.escalator.RowVisibilityChangeEvent;
  85. import com.vaadin.client.widget.escalator.RowVisibilityChangeHandler;
  86. import com.vaadin.client.widget.escalator.ScrollbarBundle;
  87. import com.vaadin.client.widget.escalator.ScrollbarBundle.Direction;
  88. import com.vaadin.client.widget.escalator.ScrollbarBundle.HorizontalScrollbarBundle;
  89. import com.vaadin.client.widget.escalator.ScrollbarBundle.VerticalScrollbarBundle;
  90. import com.vaadin.client.widget.escalator.Spacer;
  91. import com.vaadin.client.widget.escalator.SpacerUpdater;
  92. import com.vaadin.client.widget.escalator.events.RowHeightChangedEvent;
  93. import com.vaadin.client.widget.escalator.events.SpacerIndexChangedEvent;
  94. import com.vaadin.client.widget.escalator.events.SpacerVisibilityChangedEvent;
  95. import com.vaadin.client.widget.grid.events.ScrollEvent;
  96. import com.vaadin.client.widget.grid.events.ScrollHandler;
  97. import com.vaadin.client.widgets.Escalator.JsniUtil.TouchHandlerBundle;
  98. import com.vaadin.shared.Range;
  99. import com.vaadin.shared.ui.grid.HeightMode;
  100. import com.vaadin.shared.ui.grid.ScrollDestination;
  101. import com.vaadin.shared.util.SharedUtil;
  102. /*-
  103. Maintenance Notes! Reading these might save your day.
  104. (note for editors: line width is 80 chars, including the
  105. one-space indentation)
  106. == Row Container Structure
  107. AbstractRowContainer
  108. |-- AbstractStaticRowContainer
  109. | |-- HeaderRowContainer
  110. | `-- FooterContainer
  111. `---- BodyRowContainerImpl
  112. AbstractRowContainer is intended to contain all common logic
  113. between RowContainers. It manages the bookkeeping of row
  114. count, makes sure that all individual cells are rendered
  115. the same way, and so on.
  116. AbstractStaticRowContainer has some special logic that is
  117. required by all RowContainers that don't scroll (hence the
  118. word "static"). HeaderRowContainer and FooterRowContainer
  119. are pretty thin special cases of a StaticRowContainer
  120. (mostly relating to positioning of the root element).
  121. BodyRowContainerImpl could also be split into an additional
  122. "AbstractScrollingRowContainer", but I felt that no more
  123. inner classes were needed. So it contains both logic
  124. required for making things scroll about, and equivalent
  125. special cases for layouting, as are found in
  126. Header/FooterRowContainers.
  127. == The Three Indices
  128. Each RowContainer can be thought to have three levels of
  129. indices for any given displayed row (but the distinction
  130. matters primarily for the BodyRowContainerImpl, because of
  131. the way it scrolls through data):
  132. - Logical index
  133. - Physical (or DOM) index
  134. - Visual index
  135. LOGICAL INDEX is the index that is linked to the data
  136. source. If you want your data source to represent a SQL
  137. database with 10 000 rows, the 7 000:th row in the SQL has a
  138. logical index of 6 999, since the index is 0-based (unless
  139. that data source does some funky logic).
  140. PHYSICAL INDEX is the index for a row that you see in a
  141. browser's DOM inspector. If your row is the second <tr>
  142. element within a <tbody> tag, it has a physical index of 1
  143. (because of 0-based indices). In Header and
  144. FooterRowContainers, you are safe to assume that the logical
  145. index is the same as the physical index. But because the
  146. BodyRowContainerImpl never displays large data sources
  147. entirely in the DOM, a physical index usually has no
  148. apparent direct relationship with its logical index.
  149. This is the sectionRowIndex in TableRowElements.
  150. RowIndex in TableRowElements displays the physical index
  151. of all row elements, headers and footers included.
  152. VISUAL INDEX is the index relating to the order that you
  153. see a row in, in the browser, as it is rendered. The
  154. topmost row is 0, the second is 1, and so on. The visual
  155. index is similar to the physical index in the sense that
  156. Header and FooterRowContainers can assume a 1:1
  157. relationship between visual index and logical index. And
  158. again, BodyRowContainerImpl has no such relationship. The
  159. body's visual index has additionally no apparent
  160. relationship with its physical index. Because the <tr> tags
  161. are reused in the body and visually repositioned with CSS
  162. as the user scrolls, the relationship between physical
  163. index and visual index is quickly broken. You can get an
  164. element's visual index via the field
  165. BodyRowContainerImpl.visualRowOrder.
  166. Currently, the physical and visual indices are kept in sync
  167. _most of the time_ by a deferred rearrangement of rows.
  168. They become desynced when scrolling. This is to help screen
  169. readers to read the contents from the DOM in a natural
  170. order. See BodyRowContainerImpl.DeferredDomSorter for more
  171. about that.
  172. It should be noted that the entire visual range is not
  173. necessarily in view at any given time, although it should be
  174. optimised to not exceed the maximum amount of rows that can
  175. theoretically fit within the viewport when their associated
  176. spacers have zero height, except by the two rows that are
  177. required for tab navigation to work.
  178. */
  179. /**
  180. * A workaround-class for GWT and JSNI.
  181. * <p>
  182. * GWT is unable to handle some method calls to Java methods in inner-classes
  183. * from within JSNI blocks. Having that inner class extend a non-inner-class (or
  184. * implement such an interface), makes it possible for JSNI to indirectly refer
  185. * to the inner class, by invoking methods and fields in the non-inner-class
  186. * API.
  187. *
  188. * @see Escalator.Scroller
  189. */
  190. abstract class JsniWorkaround {
  191. /**
  192. * A JavaScript function that handles the scroll DOM event, and passes it on
  193. * to Java code.
  194. *
  195. * @see #createScrollListenerFunction(Escalator)
  196. * @see Escalator.Scroller#onScroll()
  197. */
  198. protected final JavaScriptObject scrollListenerFunction;
  199. /**
  200. * A JavaScript function that handles the mousewheel DOM event, and passes
  201. * it on to Java code.
  202. *
  203. * @see #createMousewheelListenerFunction(Escalator)
  204. * @see Escalator.Scroller#onScroll()
  205. */
  206. protected final JavaScriptObject mousewheelListenerFunction;
  207. /**
  208. * A JavaScript function that handles the touch start DOM event, and passes
  209. * it on to Java code.
  210. *
  211. * @see TouchHandlerBundle#touchStart(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  212. */
  213. protected JavaScriptObject touchStartFunction;
  214. /**
  215. * A JavaScript function that handles the touch move DOM event, and passes
  216. * it on to Java code.
  217. *
  218. * @see TouchHandlerBundle#touchMove(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  219. */
  220. protected JavaScriptObject touchMoveFunction;
  221. /**
  222. * A JavaScript function that handles the touch end and cancel DOM events,
  223. * and passes them on to Java code.
  224. *
  225. * @see TouchHandlerBundle#touchEnd(Escalator.JsniUtil.TouchHandlerBundle.CustomTouchEvent)
  226. */
  227. protected JavaScriptObject touchEndFunction;
  228. protected TouchHandlerBundle touchHandlerBundle;
  229. protected JsniWorkaround(final Escalator escalator) {
  230. scrollListenerFunction = createScrollListenerFunction(escalator);
  231. mousewheelListenerFunction = createMousewheelListenerFunction(
  232. escalator);
  233. touchHandlerBundle = new TouchHandlerBundle(escalator);
  234. touchStartFunction = touchHandlerBundle.getTouchStartHandler();
  235. touchMoveFunction = touchHandlerBundle.getTouchMoveHandler();
  236. touchEndFunction = touchHandlerBundle.getTouchEndHandler();
  237. }
  238. /**
  239. * A method that constructs the JavaScript function that will be stored into
  240. * {@link #scrollListenerFunction}.
  241. *
  242. * @param esc
  243. * a reference to the current instance of {@link Escalator}
  244. * @see Escalator.Scroller#onScroll()
  245. */
  246. protected abstract JavaScriptObject createScrollListenerFunction(
  247. Escalator esc);
  248. /**
  249. * A method that constructs the JavaScript function that will be stored into
  250. * {@link #mousewheelListenerFunction}.
  251. *
  252. * @param esc
  253. * a reference to the current instance of {@link Escalator}
  254. * @see Escalator.Scroller#onScroll()
  255. */
  256. protected abstract JavaScriptObject createMousewheelListenerFunction(
  257. Escalator esc);
  258. }
  259. /**
  260. * A low-level table-like widget that features a scrolling virtual viewport and
  261. * lazily generated rows.
  262. *
  263. * @since 7.4
  264. * @author Vaadin Ltd
  265. */
  266. public class Escalator extends Widget
  267. implements RequiresResize, DeferredWorker, SubPartAware {
  268. // todo comments legend
  269. /*
  270. * [[optimize]]: There's an opportunity to rewrite the code in such a way
  271. * that it _might_ perform better (remember to measure, implement,
  272. * re-measure)
  273. */
  274. /*
  275. * [[mpixscroll]]: This code will require alterations that are relevant for
  276. * supporting the scrolling through more pixels than some browsers normally
  277. * would support. (i.e. when we support more than "a million" pixels in the
  278. * escalator DOM). NOTE: these bits can most often also be identified by
  279. * searching for code that call scrollElem.getScrollTop();.
  280. */
  281. /*
  282. * [[spacer]]: Code that is important to make spacers work.
  283. */
  284. /**
  285. * A utility class that contains utility methods that are usually called
  286. * from JSNI.
  287. * <p>
  288. * The methods are moved in this class to minimize the amount of JSNI code
  289. * as much as feasible.
  290. */
  291. static class JsniUtil {
  292. public static class TouchHandlerBundle {
  293. public static final String POINTER_EVENT_TYPE_TOUCH = "touch";
  294. public static final int SIGNIFICANT_MOVE_THRESHOLD = 3;
  295. /**
  296. * A <a href=
  297. * "http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html"
  298. * >JavaScriptObject overlay</a> for the
  299. * <a href="http://www.w3.org/TR/touch-events/">JavaScript
  300. * TouchEvent</a> object.
  301. * <p>
  302. * This needs to be used in the touch event handlers, since GWT's
  303. * {@link com.google.gwt.event.dom.client.TouchEvent TouchEvent}
  304. * can't be cast from the JSNI call, and the
  305. * {@link com.google.gwt.dom.client.NativeEvent NativeEvent} isn't
  306. * properly populated with the correct values.
  307. */
  308. private static final class CustomTouchEvent
  309. extends JavaScriptObject {
  310. protected CustomTouchEvent() {
  311. }
  312. public native NativeEvent getNativeEvent()
  313. /*-{
  314. return this;
  315. }-*/;
  316. public native int getPageX()
  317. /*-{
  318. return this.targetTouches[0].pageX;
  319. }-*/;
  320. public native int getPageY()
  321. /*-{
  322. return this.targetTouches[0].pageY;
  323. }-*/;
  324. public native String getPointerType()
  325. /*-{
  326. return this.pointerType;
  327. }-*/;
  328. }
  329. private final Escalator escalator;
  330. public TouchHandlerBundle(final Escalator escalator) {
  331. this.escalator = escalator;
  332. }
  333. public native JavaScriptObject getTouchStartHandler()
  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.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchStart(*)(e);
  339. });
  340. }-*/;
  341. public native JavaScriptObject getTouchMoveHandler()
  342. /*-{
  343. // we need to store "this", since it won't be preserved on call.
  344. var self = this;
  345. return $entry(function (e) {
  346. self.@com.vaadin.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchMove(*)(e);
  347. });
  348. }-*/;
  349. public native JavaScriptObject getTouchEndHandler()
  350. /*-{
  351. // we need to store "this", since it won't be preserved on call.
  352. var self = this;
  353. return $entry(function (e) {
  354. self.@com.vaadin.client.widgets.Escalator.JsniUtil.TouchHandlerBundle::touchEnd(*)(e);
  355. });
  356. }-*/;
  357. // Duration of the inertial scrolling simulation. Devices with
  358. // larger screens take longer durations.
  359. private static final int DURATION = Window.getClientHeight();
  360. // multiply scroll velocity with repeated touching
  361. private int acceleration = 1;
  362. private boolean touching = false;
  363. // Two movement objects for storing status and processing touches
  364. private Movement yMov, xMov;
  365. // true if moved significantly since touch start
  366. private boolean movedSignificantly = false;
  367. private double touchStartTime;
  368. final double MIN_VEL = 0.6, MAX_VEL = 4, F_VEL = 1500, F_ACC = 0.7,
  369. F_AXIS = 1;
  370. // The object to deal with one direction scrolling
  371. private class Movement {
  372. final List<Double> speeds = new ArrayList<>();
  373. final ScrollbarBundle scroll;
  374. double position, offset, velocity, prevPos, prevTime, delta;
  375. boolean run, vertical;
  376. public Movement(boolean vertical) {
  377. this.vertical = vertical;
  378. scroll = vertical ? escalator.verticalScrollbar
  379. : escalator.horizontalScrollbar;
  380. }
  381. public void startTouch(CustomTouchEvent event) {
  382. speeds.clear();
  383. prevPos = pagePosition(event);
  384. prevTime = Duration.currentTimeMillis();
  385. }
  386. public void moveTouch(CustomTouchEvent event) {
  387. double pagePosition = pagePosition(event);
  388. if (pagePosition > -1) {
  389. delta = prevPos - pagePosition;
  390. double now = Duration.currentTimeMillis();
  391. double ellapsed = now - prevTime;
  392. velocity = delta / ellapsed;
  393. // if last speed was so low, reset speeds and start
  394. // storing again
  395. if (!speeds.isEmpty() && !validSpeed(speeds.get(0))) {
  396. speeds.clear();
  397. run = true;
  398. }
  399. speeds.add(0, velocity);
  400. prevTime = now;
  401. prevPos = pagePosition;
  402. }
  403. }
  404. public void endTouch(CustomTouchEvent event) {
  405. // Compute average speed
  406. velocity = 0;
  407. for (double s : speeds) {
  408. velocity += s / speeds.size();
  409. }
  410. position = scroll.getScrollPos();
  411. // Compute offset, and adjust it with an easing curve so as
  412. // movement is smoother.
  413. offset = F_VEL * velocity * acceleration
  414. * easingInOutCos(velocity, MAX_VEL);
  415. // Enable or disable inertia movement in this axis
  416. run = validSpeed(velocity);
  417. if (run) {
  418. event.getNativeEvent().preventDefault();
  419. }
  420. }
  421. void validate(Movement other) {
  422. if (!run || other.velocity > 0
  423. && Math.abs(velocity / other.velocity) < F_AXIS) {
  424. delta = offset = 0;
  425. run = false;
  426. }
  427. }
  428. void stepAnimation(double progress) {
  429. scroll.setScrollPos(position + offset * progress);
  430. }
  431. int pagePosition(CustomTouchEvent event) {
  432. // Use native event's screen x and y for IE11 and Edge
  433. // since there is no touches for these browsers (#18737)
  434. if (isCurrentBrowserIE11OrEdge()) {
  435. return vertical
  436. ? event.getNativeEvent().getClientY()
  437. + Window.getScrollTop()
  438. : event.getNativeEvent().getClientX()
  439. + Window.getScrollLeft();
  440. }
  441. JsArray<Touch> a = event.getNativeEvent().getTouches();
  442. return vertical ? a.get(0).getPageY() : a.get(0).getPageX();
  443. }
  444. boolean validSpeed(double speed) {
  445. return Math.abs(speed) > MIN_VEL;
  446. }
  447. }
  448. // Using GWT animations which take care of native animation frames.
  449. private Animation animation = new Animation() {
  450. @Override
  451. public void onUpdate(double progress) {
  452. xMov.stepAnimation(progress);
  453. yMov.stepAnimation(progress);
  454. }
  455. @Override
  456. public double interpolate(double progress) {
  457. return easingOutCirc(progress);
  458. };
  459. @Override
  460. public void onComplete() {
  461. touching = false;
  462. escalator.body.domSorter.reschedule();
  463. };
  464. @Override
  465. public void run(int duration) {
  466. if (xMov.run || yMov.run) {
  467. super.run(duration);
  468. } else {
  469. onComplete();
  470. }
  471. };
  472. };
  473. public void touchStart(final CustomTouchEvent event) {
  474. if (allowTouch(event)) {
  475. if (yMov == null) {
  476. yMov = new Movement(true);
  477. xMov = new Movement(false);
  478. }
  479. if (animation.isRunning()) {
  480. acceleration += F_ACC;
  481. event.getNativeEvent().preventDefault();
  482. animation.cancel();
  483. } else {
  484. acceleration = 1;
  485. }
  486. xMov.startTouch(event);
  487. yMov.startTouch(event);
  488. touchStartTime = Duration.currentTimeMillis();
  489. touching = true;
  490. movedSignificantly = false;
  491. } else {
  492. touching = false;
  493. animation.cancel();
  494. acceleration = 1;
  495. }
  496. }
  497. public void touchMove(final CustomTouchEvent event) {
  498. if (touching) {
  499. if (!movedSignificantly) {
  500. double distanceSquared = Math.abs(xMov.delta)
  501. * Math.abs(xMov.delta)
  502. + Math.abs(yMov.delta) * Math.abs(yMov.delta);
  503. movedSignificantly = distanceSquared > SIGNIFICANT_MOVE_THRESHOLD
  504. * SIGNIFICANT_MOVE_THRESHOLD;
  505. }
  506. // allow handling long press differently, without triggering
  507. // scrolling
  508. if (escalator.getDelayToCancelTouchScroll() >= 0
  509. && !movedSignificantly
  510. && Duration.currentTimeMillis()
  511. - touchStartTime > escalator
  512. .getDelayToCancelTouchScroll()) {
  513. // cancel touch handling, don't prevent event
  514. touching = false;
  515. animation.cancel();
  516. acceleration = 1;
  517. return;
  518. }
  519. xMov.moveTouch(event);
  520. yMov.moveTouch(event);
  521. xMov.validate(yMov);
  522. yMov.validate(xMov);
  523. moveScrollFromEvent(escalator, xMov.delta, yMov.delta,
  524. event.getNativeEvent());
  525. }
  526. }
  527. public void touchEnd(final CustomTouchEvent event) {
  528. if (touching) {
  529. xMov.endTouch(event);
  530. yMov.endTouch(event);
  531. xMov.validate(yMov);
  532. yMov.validate(xMov);
  533. // Adjust duration so as longer movements take more duration
  534. boolean vert = !xMov.run || yMov.run
  535. && Math.abs(yMov.offset) > Math.abs(xMov.offset);
  536. double delta = Math.abs((vert ? yMov : xMov).offset);
  537. animation.run((int) (3 * DURATION * easingOutExp(delta)));
  538. }
  539. }
  540. // Allow touchStart for IE11 and Edge even though there is no touch
  541. // (#18737),
  542. // otherwise allow touch only if there is a single touch in the
  543. // event
  544. private boolean allowTouch(
  545. final TouchHandlerBundle.CustomTouchEvent event) {
  546. if (isCurrentBrowserIE11OrEdge()) {
  547. return (POINTER_EVENT_TYPE_TOUCH
  548. .equals(event.getPointerType()));
  549. } else {
  550. return (event.getNativeEvent().getTouches().length() == 1);
  551. }
  552. }
  553. private double easingInOutCos(double val, double max) {
  554. return 0.5 - 0.5 * Math.cos(Math.PI * Math.signum(val)
  555. * Math.min(Math.abs(val), max) / max);
  556. }
  557. private double easingOutExp(double delta) {
  558. return (1 - Math.pow(2, -delta / 1000));
  559. }
  560. private double easingOutCirc(double progress) {
  561. return Math.sqrt(1 - (progress - 1) * (progress - 1));
  562. }
  563. }
  564. public static void moveScrollFromEvent(final Escalator escalator,
  565. final double deltaX, final double deltaY,
  566. final NativeEvent event) {
  567. boolean scrollPosXChanged = false;
  568. boolean scrollPosYChanged = false;
  569. if (!Double.isNaN(deltaX)) {
  570. double oldScrollPosX = escalator.horizontalScrollbar
  571. .getScrollPos();
  572. escalator.horizontalScrollbar.setScrollPosByDelta(deltaX);
  573. if (oldScrollPosX != escalator.horizontalScrollbar
  574. .getScrollPos()) {
  575. scrollPosXChanged = true;
  576. }
  577. }
  578. if (!Double.isNaN(deltaY)) {
  579. double oldScrollPosY = escalator.verticalScrollbar
  580. .getScrollPos();
  581. escalator.verticalScrollbar.setScrollPosByDelta(deltaY);
  582. if (oldScrollPosY != escalator.verticalScrollbar
  583. .getScrollPos()) {
  584. scrollPosYChanged = true;
  585. }
  586. }
  587. /*
  588. * Only prevent if internal scrolling happened. If there's no more
  589. * room to scroll internally, allow the event to pass further.
  590. */
  591. final boolean warrantedYScroll = deltaY != 0 && scrollPosYChanged
  592. && escalator.verticalScrollbar.showsScrollHandle();
  593. final boolean warrantedXScroll = deltaX != 0 && scrollPosXChanged
  594. && escalator.horizontalScrollbar.showsScrollHandle();
  595. if (warrantedYScroll || warrantedXScroll) {
  596. event.preventDefault();
  597. }
  598. }
  599. }
  600. /**
  601. * ScrollDestination case-specific handling logic.
  602. */
  603. private static double getScrollPos(final ScrollDestination destination,
  604. final double targetStartPx, final double targetEndPx,
  605. final double viewportStartPx, final double viewportEndPx,
  606. final double padding) {
  607. final double viewportLength = viewportEndPx - viewportStartPx;
  608. switch (destination) {
  609. /*
  610. * Scroll as little as possible to show the target element. If the
  611. * element fits into view, this works as START or END depending on the
  612. * current scroll position. If the element does not fit into view, this
  613. * works as START.
  614. */
  615. case ANY: {
  616. final double startScrollPos = targetStartPx - padding;
  617. final double endScrollPos = targetEndPx + padding - viewportLength;
  618. if (startScrollPos < viewportStartPx) {
  619. return startScrollPos;
  620. } else if (targetEndPx + padding > viewportEndPx) {
  621. return endScrollPos;
  622. } else {
  623. // NOOP, it's already visible
  624. return viewportStartPx;
  625. }
  626. }
  627. /*
  628. * Scrolls so that the element is shown at the end of the viewport. The
  629. * viewport will, however, not scroll before its first element.
  630. */
  631. case END: {
  632. return targetEndPx + padding - viewportLength;
  633. }
  634. /*
  635. * Scrolls so that the element is shown in the middle of the viewport.
  636. * The viewport will, however, not scroll beyond its contents, given
  637. * more elements than what the viewport is able to show at once. Under
  638. * no circumstances will the viewport scroll before its first element.
  639. */
  640. case MIDDLE: {
  641. final double targetMiddle = targetStartPx
  642. + (targetEndPx - targetStartPx) / 2;
  643. return targetMiddle - viewportLength / 2;
  644. }
  645. /*
  646. * Scrolls so that the element is shown at the start of the viewport.
  647. * The viewport will, however, not scroll beyond its contents.
  648. */
  649. case START: {
  650. return targetStartPx - padding;
  651. }
  652. /*
  653. * Throw an error if we're here. This can only mean that
  654. * ScrollDestination has been carelessly amended..
  655. */
  656. default: {
  657. throw new IllegalArgumentException(
  658. "Internal: ScrollDestination has been modified, "
  659. + "but Escalator.getScrollPos has not been updated "
  660. + "to match new values.");
  661. }
  662. }
  663. }
  664. /** An inner class that handles all logic related to scrolling. */
  665. private class Scroller extends JsniWorkaround {
  666. private double lastScrollTop = 0;
  667. private double lastScrollLeft = 0;
  668. public Scroller() {
  669. super(Escalator.this);
  670. }
  671. @Override
  672. protected native JavaScriptObject createScrollListenerFunction(
  673. Escalator esc)
  674. /*-{
  675. var vScroll = esc.@com.vaadin.client.widgets.Escalator::verticalScrollbar;
  676. var vScrollElem = vScroll.@com.vaadin.client.widget.escalator.ScrollbarBundle::getElement()();
  677. var hScroll = esc.@com.vaadin.client.widgets.Escalator::horizontalScrollbar;
  678. var hScrollElem = hScroll.@com.vaadin.client.widget.escalator.ScrollbarBundle::getElement()();
  679. return $entry(function(e) {
  680. var target = e.target;
  681. // in case the scroll event was native (i.e. scrollbars were dragged, or
  682. // the scrollTop/Left was manually modified), the bundles have old cache
  683. // values. We need to make sure that the caches are kept up to date.
  684. if (target === vScrollElem) {
  685. vScroll.@com.vaadin.client.widget.escalator.ScrollbarBundle::updateScrollPosFromDom()();
  686. } else if (target === hScrollElem) {
  687. hScroll.@com.vaadin.client.widget.escalator.ScrollbarBundle::updateScrollPosFromDom()();
  688. } else {
  689. $wnd.console.error("unexpected scroll target: "+target);
  690. }
  691. });
  692. }-*/;
  693. @Override
  694. protected native JavaScriptObject createMousewheelListenerFunction(
  695. Escalator esc)
  696. /*-{
  697. return $entry(function(e) {
  698. var deltaX = e.deltaX ? e.deltaX : -0.5*e.wheelDeltaX;
  699. var deltaY = e.deltaY ? e.deltaY : -0.5*e.wheelDeltaY;
  700. // Delta mode 0 is in pixels; we don't need to do anything...
  701. // A delta mode of 1 means we're scrolling by lines instead of pixels
  702. // We need to scale the number of lines by the default line height
  703. if (e.deltaMode === 1) {
  704. var brc = esc.@com.vaadin.client.widgets.Escalator::body;
  705. deltaY *= brc.@com.vaadin.client.widgets.Escalator.AbstractRowContainer::getDefaultRowHeight()();
  706. }
  707. // Other delta modes aren't supported
  708. if ((e.deltaMode !== undefined) && (e.deltaMode >= 2 || e.deltaMode < 0)) {
  709. var msg = "Unsupported wheel delta mode \"" + e.deltaMode + "\"";
  710. // Print warning message
  711. esc.@com.vaadin.client.widgets.Escalator::logWarning(*)(msg);
  712. }
  713. // IE8 has only delta y
  714. if (isNaN(deltaY)) {
  715. deltaY = -0.5*e.wheelDelta;
  716. }
  717. @com.vaadin.client.widgets.Escalator.JsniUtil::moveScrollFromEvent(*)(esc, deltaX, deltaY, e);
  718. });
  719. }-*/;
  720. /**
  721. * Recalculates the virtual viewport represented by the scrollbars, so
  722. * that the sizes of the scroll handles appear correct in the browser
  723. */
  724. public void recalculateScrollbarsForVirtualViewport() {
  725. double scrollContentHeight = body.calculateTotalRowHeight()
  726. + body.spacerContainer.getSpacerHeightsSum();
  727. double scrollContentWidth = columnConfiguration.calculateRowWidth();
  728. double tableWrapperHeight = heightOfEscalator;
  729. double tableWrapperWidth = widthOfEscalator;
  730. boolean verticalScrollNeeded = scrollContentHeight > tableWrapperHeight
  731. + WidgetUtil.PIXEL_EPSILON - header.getHeightOfSection()
  732. - footer.getHeightOfSection();
  733. boolean horizontalScrollNeeded = scrollContentWidth > tableWrapperWidth
  734. + WidgetUtil.PIXEL_EPSILON;
  735. // One dimension got scrollbars, but not the other. Recheck time!
  736. if (verticalScrollNeeded != horizontalScrollNeeded) {
  737. if (!verticalScrollNeeded && horizontalScrollNeeded) {
  738. verticalScrollNeeded = scrollContentHeight > tableWrapperHeight
  739. + WidgetUtil.PIXEL_EPSILON
  740. - header.getHeightOfSection()
  741. - footer.getHeightOfSection()
  742. - horizontalScrollbar.getScrollbarThickness();
  743. } else {
  744. horizontalScrollNeeded = scrollContentWidth > tableWrapperWidth
  745. + WidgetUtil.PIXEL_EPSILON
  746. - verticalScrollbar.getScrollbarThickness();
  747. }
  748. }
  749. // let's fix the table wrapper size, since it's now stable.
  750. if (verticalScrollNeeded) {
  751. tableWrapperWidth -= verticalScrollbar.getScrollbarThickness();
  752. tableWrapperWidth = Math.max(0, tableWrapperWidth);
  753. }
  754. if (horizontalScrollNeeded) {
  755. tableWrapperHeight -= horizontalScrollbar
  756. .getScrollbarThickness();
  757. tableWrapperHeight = Math.max(0, tableWrapperHeight);
  758. }
  759. tableWrapper.getStyle().setHeight(tableWrapperHeight, Unit.PX);
  760. tableWrapper.getStyle().setWidth(tableWrapperWidth, Unit.PX);
  761. double footerHeight = footer.getHeightOfSection();
  762. double headerHeight = header.getHeightOfSection();
  763. double vScrollbarHeight = Math.max(0,
  764. tableWrapperHeight - footerHeight - headerHeight);
  765. verticalScrollbar.setOffsetSize(vScrollbarHeight);
  766. verticalScrollbar.setScrollSize(scrollContentHeight);
  767. /*
  768. * If decreasing the amount of frozen columns, and scrolled to the
  769. * right, the scroll position might reset. So we need to remember
  770. * the scroll position, and re-apply it once the scrollbar size has
  771. * been adjusted.
  772. */
  773. double prevScrollPos = horizontalScrollbar.getScrollPos();
  774. double unfrozenPixels = columnConfiguration
  775. .getCalculatedColumnsWidth(Range.between(
  776. columnConfiguration.getFrozenColumnCount(),
  777. columnConfiguration.getColumnCount()));
  778. double frozenPixels = scrollContentWidth - unfrozenPixels;
  779. double hScrollOffsetWidth = tableWrapperWidth - frozenPixels;
  780. horizontalScrollbar.setOffsetSize(hScrollOffsetWidth);
  781. horizontalScrollbar.setScrollSize(unfrozenPixels);
  782. horizontalScrollbar.getElement().getStyle().setLeft(frozenPixels,
  783. Unit.PX);
  784. horizontalScrollbar.setScrollPos(prevScrollPos);
  785. /*
  786. * only show the scrollbar wrapper if the scrollbar itself is
  787. * visible.
  788. */
  789. if (horizontalScrollbar.showsScrollHandle()) {
  790. horizontalScrollbarDeco.getStyle().clearDisplay();
  791. } else {
  792. horizontalScrollbarDeco.getStyle().setDisplay(Display.NONE);
  793. }
  794. /*
  795. * only show corner background divs if the vertical scrollbar is
  796. * visible.
  797. */
  798. Style hCornerStyle = headerDeco.getStyle();
  799. Style fCornerStyle = footerDeco.getStyle();
  800. if (verticalScrollbar.showsScrollHandle()) {
  801. hCornerStyle.clearDisplay();
  802. fCornerStyle.clearDisplay();
  803. if (horizontalScrollbar.showsScrollHandle()) {
  804. double offset = horizontalScrollbar.getScrollbarThickness();
  805. fCornerStyle.setBottom(offset, Unit.PX);
  806. } else {
  807. fCornerStyle.clearBottom();
  808. }
  809. } else {
  810. hCornerStyle.setDisplay(Display.NONE);
  811. fCornerStyle.setDisplay(Display.NONE);
  812. }
  813. }
  814. /**
  815. * Logical scrolling event handler for the entire widget.
  816. */
  817. public void onScroll() {
  818. final double scrollTop = verticalScrollbar.getScrollPos();
  819. final double scrollLeft = horizontalScrollbar.getScrollPos();
  820. if (lastScrollLeft != scrollLeft) {
  821. for (int i = 0; i < columnConfiguration.frozenColumns; i++) {
  822. header.updateFreezePosition(i, scrollLeft);
  823. body.updateFreezePosition(i, scrollLeft);
  824. footer.updateFreezePosition(i, scrollLeft);
  825. }
  826. position.set(headElem, -scrollLeft, 0);
  827. position.set(footElem, -scrollLeft, 0);
  828. lastScrollLeft = scrollLeft;
  829. }
  830. body.setBodyScrollPosition(scrollLeft, scrollTop);
  831. lastScrollTop = scrollTop;
  832. body.updateEscalatorRowsOnScroll();
  833. body.spacerContainer.updateSpacerDecosVisibility();
  834. /*
  835. * TODO [[optimize]]: Might avoid a reflow by first calculating new
  836. * scrolltop and scrolleft, then doing the escalator magic based on
  837. * those numbers and only updating the positions after that.
  838. */
  839. }
  840. public native void attachScrollListener(Element element)
  841. /*
  842. * Attaching events with JSNI instead of the GWT event mechanism because
  843. * GWT didn't provide enough details in events, or triggering the event
  844. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  845. * and skill, it could be done with better success. JavaScript overlay
  846. * types might work. This might also get rid of the JsniWorkaround
  847. * class.
  848. */
  849. /*-{
  850. if (element.addEventListener) {
  851. element.addEventListener("scroll", this.@com.vaadin.client.widgets.JsniWorkaround::scrollListenerFunction);
  852. } else {
  853. element.attachEvent("onscroll", this.@com.vaadin.client.widgets.JsniWorkaround::scrollListenerFunction);
  854. }
  855. }-*/;
  856. public native void detachScrollListener(Element element)
  857. /*
  858. * Detaching events with JSNI instead of the GWT event mechanism because
  859. * GWT didn't provide enough details in events, or triggering the event
  860. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  861. * and skill, it could be done with better success. JavaScript overlay
  862. * types might work. This might also get rid of the JsniWorkaround
  863. * class.
  864. */
  865. /*-{
  866. if (element.addEventListener) {
  867. element.removeEventListener("scroll", this.@com.vaadin.client.widgets.JsniWorkaround::scrollListenerFunction);
  868. } else {
  869. element.detachEvent("onscroll", this.@com.vaadin.client.widgets.JsniWorkaround::scrollListenerFunction);
  870. }
  871. }-*/;
  872. public native void attachMousewheelListener(Element element)
  873. /*
  874. * Attaching events with JSNI instead of the GWT event mechanism because
  875. * GWT didn't provide enough details in events, or triggering the event
  876. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  877. * and skill, it could be done with better success. JavaScript overlay
  878. * types might work. This might also get rid of the JsniWorkaround
  879. * class.
  880. */
  881. /*-{
  882. // firefox likes "wheel", while others use "mousewheel"
  883. var eventName = 'onmousewheel' in element ? 'mousewheel' : 'wheel';
  884. element.addEventListener(eventName, this.@com.vaadin.client.widgets.JsniWorkaround::mousewheelListenerFunction);
  885. }-*/;
  886. public native void detachMousewheelListener(Element element)
  887. /*
  888. * Detaching events with JSNI instead of the GWT event mechanism because
  889. * GWT didn't provide enough details in events, or triggering the event
  890. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  891. * and skill, it could be done with better success. JavaScript overlay
  892. * types might work. This might also get rid of the JsniWorkaround
  893. * class.
  894. */
  895. /*-{
  896. // firefox likes "wheel", while others use "mousewheel"
  897. var eventName = element.onwheel===undefined?"mousewheel":"wheel";
  898. element.removeEventListener(eventName, this.@com.vaadin.client.widgets.JsniWorkaround::mousewheelListenerFunction);
  899. }-*/;
  900. public native void attachTouchListeners(Element element)
  901. /*
  902. * Detaching events with JSNI instead of the GWT event mechanism because
  903. * GWT didn't provide enough details in events, or triggering the event
  904. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  905. * and skill, it could be done with better success. JavaScript overlay
  906. * types might work. This might also get rid of the JsniWorkaround
  907. * class.
  908. */
  909. /*-{
  910. element.addEventListener("touchstart", this.@com.vaadin.client.widgets.JsniWorkaround::touchStartFunction);
  911. element.addEventListener("touchmove", this.@com.vaadin.client.widgets.JsniWorkaround::touchMoveFunction);
  912. element.addEventListener("touchend", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  913. element.addEventListener("touchcancel", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  914. }-*/;
  915. public native void detachTouchListeners(Element element)
  916. /*
  917. * Detaching events with JSNI instead of the GWT event mechanism because
  918. * GWT didn't provide enough details in events, or triggering the event
  919. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  920. * and skill, it could be done with better success. JavaScript overlay
  921. * types might work. This might also get rid of the JsniWorkaround
  922. * class.
  923. */
  924. /*-{
  925. element.removeEventListener("touchstart", this.@com.vaadin.client.widgets.JsniWorkaround::touchStartFunction);
  926. element.removeEventListener("touchmove", this.@com.vaadin.client.widgets.JsniWorkaround::touchMoveFunction);
  927. element.removeEventListener("touchend", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  928. element.removeEventListener("touchcancel", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  929. }-*/;
  930. /**
  931. * Using pointerdown, pointermove, pointerup, and pointercancel for IE11
  932. * and Edge instead of touch* listeners (#18737)
  933. *
  934. * @param element
  935. */
  936. public native void attachPointerEventListeners(Element element)
  937. /*
  938. * Attaching events with JSNI instead of the GWT event mechanism because
  939. * GWT didn't provide enough details in events, or triggering the event
  940. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  941. * and skill, it could be done with better success. JavaScript overlay
  942. * types might work. This might also get rid of the JsniWorkaround
  943. * class.
  944. */
  945. /*-{
  946. element.addEventListener("pointerdown", this.@com.vaadin.client.widgets.JsniWorkaround::touchStartFunction);
  947. element.addEventListener("pointermove", this.@com.vaadin.client.widgets.JsniWorkaround::touchMoveFunction);
  948. element.addEventListener("pointerup", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  949. element.addEventListener("pointercancel", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  950. }-*/;
  951. /**
  952. * Using pointerdown, pointermove, pointerup, and pointercancel for IE11
  953. * and Edge instead of touch* listeners (#18737)
  954. *
  955. * @param element
  956. */
  957. public native void detachPointerEventListeners(Element element)
  958. /*
  959. * Detaching events with JSNI instead of the GWT event mechanism because
  960. * GWT didn't provide enough details in events, or triggering the event
  961. * handlers with GWT bindings was unsuccessful. Maybe, with more time
  962. * and skill, it could be done with better success. JavaScript overlay
  963. * types might work. This might also get rid of the JsniWorkaround
  964. * class.
  965. */
  966. /*-{
  967. element.removeEventListener("pointerdown", this.@com.vaadin.client.widgets.JsniWorkaround::touchStartFunction);
  968. element.removeEventListener("pointermove", this.@com.vaadin.client.widgets.JsniWorkaround::touchMoveFunction);
  969. element.removeEventListener("pointerup", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  970. element.removeEventListener("pointercancel", this.@com.vaadin.client.widgets.JsniWorkaround::touchEndFunction);
  971. }-*/;
  972. public void scrollToColumn(final int columnIndex,
  973. final ScrollDestination destination, final int padding) {
  974. assert columnIndex >= columnConfiguration.frozenColumns : "Can't scroll to a frozen column";
  975. /*
  976. * To cope with frozen columns, we just pretend those columns are
  977. * not there at all when calculating the position of the target
  978. * column and the boundaries of the viewport. The resulting
  979. * scrollLeft will be correct without compensation since the DOM
  980. * structure effectively means that scrollLeft also ignores the
  981. * frozen columns.
  982. */
  983. final double frozenPixels = columnConfiguration
  984. .getCalculatedColumnsWidth(Range.withLength(0,
  985. columnConfiguration.frozenColumns));
  986. final double targetStartPx = columnConfiguration
  987. .getCalculatedColumnsWidth(Range.withLength(0, columnIndex))
  988. - frozenPixels;
  989. final double targetEndPx = targetStartPx
  990. + columnConfiguration.getColumnWidthActual(columnIndex);
  991. final double viewportStartPx = getScrollLeft();
  992. double viewportEndPx = viewportStartPx
  993. + getBoundingWidth(getElement()) - frozenPixels;
  994. if (verticalScrollbar.showsScrollHandle()) {
  995. viewportEndPx -= WidgetUtil.getNativeScrollbarSize();
  996. }
  997. final double scrollLeft = getScrollPos(destination, targetStartPx,
  998. targetEndPx, viewportStartPx, viewportEndPx, padding);
  999. /*
  1000. * note that it doesn't matter if the scroll would go beyond the
  1001. * content, since the browser will adjust for that, and everything
  1002. * fall into line accordingly.
  1003. */
  1004. setScrollLeft(scrollLeft);
  1005. }
  1006. public void scrollToRow(final int rowIndex,
  1007. final ScrollDestination destination, final double padding) {
  1008. body.scrollToRowSpacerOrBoth(rowIndex, destination, padding,
  1009. ScrollType.ROW);
  1010. }
  1011. }
  1012. /**
  1013. * Helper class that helps to implement the WAI-ARIA functionality for the
  1014. * Grid and TreeGrid component.
  1015. * <p>
  1016. * The following WAI-ARIA attributes are added through this class:
  1017. *
  1018. * <ul>
  1019. * <li>aria-rowcount (since 8.2)</li>
  1020. * <li>roles provided by {@link AriaGridRole} (since 8.2)</li>
  1021. * </ul>
  1022. *
  1023. * @since 8.2
  1024. */
  1025. public class AriaGridHelper {
  1026. /**
  1027. * This field contains the total number of rows from the grid including
  1028. * rows from thead, tbody and tfoot.
  1029. *
  1030. * @since 8.2
  1031. */
  1032. private int allRows;
  1033. /**
  1034. * Adds the given numberOfRows to allRows and calls
  1035. * {@link #updateAriaRowCount()}.
  1036. *
  1037. * @param numberOfRows
  1038. * number of rows that were added to the grid
  1039. *
  1040. * @since 8.2
  1041. */
  1042. public void addRows(int numberOfRows) {
  1043. allRows += numberOfRows;
  1044. updateAriaRowCount();
  1045. }
  1046. /**
  1047. * Removes the given numberOfRows from allRows and calls
  1048. * {@link #updateAriaRowCount()}.
  1049. *
  1050. * @param numberOfRows
  1051. * number of rows that were removed from the grid
  1052. *
  1053. * @since 8.2
  1054. */
  1055. public void removeRows(int numberOfRows) {
  1056. allRows -= numberOfRows;
  1057. updateAriaRowCount();
  1058. }
  1059. /**
  1060. * Sets the aria-rowcount attribute with the current value of
  1061. * {@link AriaGridHelper#allRows} if the grid is attached and
  1062. * {@link AriaGridHelper#allRows} > 0.
  1063. *
  1064. * @since 8.2
  1065. */
  1066. public void updateAriaRowCount() {
  1067. if (!isAttached() || 0 > allRows) {
  1068. return;
  1069. }
  1070. getTable().setAttribute("aria-rowcount", String.valueOf(allRows));
  1071. }
  1072. /**
  1073. * Sets the {@code role} attribute to the given element.
  1074. *
  1075. * @param element
  1076. * element that should get the role attribute
  1077. * @param role
  1078. * role to be added
  1079. *
  1080. * @since 8.2
  1081. */
  1082. public void updateRole(final Element element, AriaGridRole role) {
  1083. element.setAttribute("role", role.getName());
  1084. }
  1085. }
  1086. /**
  1087. * Holds the currently used aria roles within the grid for rows and cells.
  1088. *
  1089. * @since 8.2
  1090. */
  1091. public enum AriaGridRole {
  1092. ROW("row"), ROWHEADER("rowheader"), ROWGROUP("rowgroup"), GRIDCELL(
  1093. "gridcell"), COLUMNHEADER("columnheader");
  1094. private final String name;
  1095. AriaGridRole(String name) {
  1096. this.name = name;
  1097. }
  1098. /**
  1099. * Return the name of the {@link AriaGridRole}.
  1100. *
  1101. * @return String name to be used as role attribute
  1102. */
  1103. public String getName() {
  1104. return name;
  1105. }
  1106. }
  1107. public abstract class AbstractRowContainer implements RowContainer {
  1108. private EscalatorUpdater updater = EscalatorUpdater.NULL;
  1109. private int rows;
  1110. /**
  1111. * The table section element ({@code <thead>}, {@code <tbody>} or
  1112. * {@code <tfoot>}) the rows (i.e. <code>&lt;tr&gt;</code> tags) are
  1113. * contained in.
  1114. */
  1115. protected final TableSectionElement root;
  1116. /**
  1117. * The primary style name of the escalator. Most commonly provided by
  1118. * Escalator as "v-escalator".
  1119. */
  1120. private String primaryStyleName = null;
  1121. private boolean defaultRowHeightShouldBeAutodetected = true;
  1122. private double defaultRowHeight = INITIAL_DEFAULT_ROW_HEIGHT;
  1123. private boolean initialColumnSizesCalculated = false;
  1124. private boolean autodetectingRowHeightLater = false;
  1125. public AbstractRowContainer(
  1126. final TableSectionElement rowContainerElement) {
  1127. root = rowContainerElement;
  1128. ariaGridHelper.updateRole(root, AriaGridRole.ROWGROUP);
  1129. }
  1130. @Override
  1131. public TableSectionElement getElement() {
  1132. return root;
  1133. }
  1134. /**
  1135. * Gets the tag name of an element to represent a cell in a row.
  1136. * <p>
  1137. * Usually {@code "th"} or {@code "td"}.
  1138. * <p>
  1139. * <em>Note:</em> To actually <em>create</em> such an element, use
  1140. * {@link #createCellElement(double)} instead.
  1141. *
  1142. * @return the tag name for the element to represent cells as
  1143. * @see #createCellElement(double)
  1144. */
  1145. protected abstract String getCellElementTagName();
  1146. /**
  1147. * Gets the role attribute of an element to represent a cell in a row.
  1148. * <p>
  1149. * Usually {@link AriaGridRole#GRIDCELL} except for a cell in the
  1150. * header.
  1151. *
  1152. * @return the role attribute for the element to represent cells
  1153. *
  1154. * @since 8.2
  1155. */
  1156. protected AriaGridRole getCellElementRole() {
  1157. return AriaGridRole.GRIDCELL;
  1158. }
  1159. /**
  1160. * Gets the role attribute of an element to represent a row in a grid.
  1161. * <p>
  1162. * Usually {@link AriaGridRole#ROW} except for a row in the header.
  1163. *
  1164. * @return the role attribute for the element to represent rows
  1165. *
  1166. * @since 8.2
  1167. */
  1168. protected AriaGridRole getRowElementRole() {
  1169. return AriaGridRole.ROW;
  1170. }
  1171. @Override
  1172. public EscalatorUpdater getEscalatorUpdater() {
  1173. return updater;
  1174. }
  1175. /**
  1176. * {@inheritDoc}
  1177. * <p>
  1178. * <em>Implementation detail:</em> This method does no DOM modifications
  1179. * (i.e. is very cheap to call) if there is no data for rows or columns
  1180. * when this method is called.
  1181. *
  1182. * @see #hasColumnAndRowData()
  1183. */
  1184. @Override
  1185. public void setEscalatorUpdater(
  1186. final EscalatorUpdater escalatorUpdater) {
  1187. if (escalatorUpdater == null) {
  1188. throw new IllegalArgumentException(
  1189. "escalator updater cannot be null");
  1190. }
  1191. updater = escalatorUpdater;
  1192. if (hasColumnAndRowData() && getRowCount() > 0) {
  1193. refreshRows(0, getRowCount());
  1194. }
  1195. }
  1196. /**
  1197. * {@inheritDoc}
  1198. * <p>
  1199. * <em>Implementation detail:</em> This method does no DOM modifications
  1200. * (i.e. is very cheap to call) if there are no rows in the DOM when
  1201. * this method is called.
  1202. *
  1203. * @see #hasSomethingInDom()
  1204. */
  1205. @Override
  1206. public void removeRows(final int index, final int numberOfRows) {
  1207. assertArgumentsAreValidAndWithinRange(index, numberOfRows);
  1208. rows -= numberOfRows;
  1209. ariaGridHelper.removeRows(numberOfRows);
  1210. if (!isAttached()) {
  1211. return;
  1212. }
  1213. if (hasSomethingInDom()) {
  1214. paintRemoveRows(index, numberOfRows);
  1215. }
  1216. }
  1217. /**
  1218. * Removes those row elements from the DOM that correspond to the given
  1219. * range of logical indices. This may be fewer than {@code numberOfRows}
  1220. * , even zero, if not all the removed rows are actually visible.
  1221. * <p>
  1222. * The implementation must call
  1223. * {@link #paintRemoveRow(TableRowElement, int)} for each row that is
  1224. * removed from the DOM.
  1225. *
  1226. * @param index
  1227. * the logical index of the first removed row
  1228. * @param numberOfRows
  1229. * number of logical rows to remove
  1230. */
  1231. protected abstract void paintRemoveRows(final int index,
  1232. final int numberOfRows);
  1233. /**
  1234. * Removes a row element from the DOM, invoking
  1235. * {@link #getEscalatorUpdater()}
  1236. * {@link EscalatorUpdater#preDetach(Row, Iterable) preDetach} and
  1237. * {@link EscalatorUpdater#postDetach(Row, Iterable) postDetach} before
  1238. * and after removing the row, respectively.
  1239. * <p>
  1240. * This method must be called for each removed DOM row by any
  1241. * {@link #paintRemoveRows(int, int)} implementation.
  1242. *
  1243. * @param tr
  1244. * the row element to remove.
  1245. * @param logicalRowIndex
  1246. * logical index of the row that is to be removed
  1247. */
  1248. protected void paintRemoveRow(final TableRowElement tr,
  1249. final int logicalRowIndex) {
  1250. flyweightRow.setup(tr, logicalRowIndex,
  1251. columnConfiguration.getCalculatedColumnWidths());
  1252. getEscalatorUpdater().preDetach(flyweightRow,
  1253. flyweightRow.getCells());
  1254. tr.removeFromParent();
  1255. getEscalatorUpdater().postDetach(flyweightRow,
  1256. flyweightRow.getCells());
  1257. /*
  1258. * the "assert" guarantees that this code is run only during
  1259. * development/debugging.
  1260. */
  1261. assert flyweightRow.teardown();
  1262. }
  1263. protected void assertArgumentsAreValidAndWithinRange(final int index,
  1264. final int numberOfRows)
  1265. throws IllegalArgumentException, IndexOutOfBoundsException {
  1266. if (numberOfRows < 1) {
  1267. throw new IllegalArgumentException(
  1268. "Number of rows must be 1 or greater (was "
  1269. + numberOfRows + ")");
  1270. }
  1271. if (index < 0 || index + numberOfRows > getRowCount()) {
  1272. throw new IndexOutOfBoundsException("The given " + "row range ("
  1273. + index + ".." + (index + numberOfRows)
  1274. + ") was outside of the current number of rows ("
  1275. + getRowCount() + ")");
  1276. }
  1277. }
  1278. @Override
  1279. public int getRowCount() {
  1280. return rows;
  1281. }
  1282. /**
  1283. * This method calculates the current row count directly from the DOM.
  1284. * <p>
  1285. * While Escalator is stable, this value should equal to
  1286. * {@link #getRowCount()}, but while row counts are being updated, these
  1287. * two values might differ for a short while.
  1288. * <p>
  1289. * Any extra content, such as spacers for the body, should not be
  1290. * included in this count.
  1291. *
  1292. * @since 7.5.0
  1293. *
  1294. * @return the actual DOM count of rows
  1295. */
  1296. public abstract int getDomRowCount();
  1297. /**
  1298. * {@inheritDoc}
  1299. * <p>
  1300. * <em>Implementation detail:</em> This method does no DOM modifications
  1301. * (i.e. is very cheap to call) if there is no data for columns when
  1302. * this method is called.
  1303. *
  1304. * @see #hasColumnAndRowData()
  1305. */
  1306. @Override
  1307. public void insertRows(final int index, final int numberOfRows) {
  1308. if (index < 0 || index > getRowCount()) {
  1309. throw new IndexOutOfBoundsException("The given index (" + index
  1310. + ") was outside of the current number of rows (0.."
  1311. + getRowCount() + ")");
  1312. }
  1313. if (numberOfRows < 1) {
  1314. throw new IllegalArgumentException(
  1315. "Number of rows must be 1 or greater (was "
  1316. + numberOfRows + ")");
  1317. }
  1318. rows += numberOfRows;
  1319. ariaGridHelper.addRows(numberOfRows);
  1320. /*
  1321. * only add items in the DOM if the widget itself is attached to the
  1322. * DOM. We can't calculate sizes otherwise.
  1323. */
  1324. if (isAttached()) {
  1325. paintInsertRows(index, numberOfRows);
  1326. /*
  1327. * We are inserting the first rows in this container. We
  1328. * potentially need to set the widths for the cells for the
  1329. * first time.
  1330. */
  1331. if (rows == numberOfRows) {
  1332. Scheduler.get().scheduleFinally(() -> {
  1333. if (initialColumnSizesCalculated) {
  1334. return;
  1335. }
  1336. initialColumnSizesCalculated = true;
  1337. Map<Integer, Double> colWidths = new HashMap<>();
  1338. for (int i = 0; i < getColumnConfiguration()
  1339. .getColumnCount(); i++) {
  1340. Double width = Double.valueOf(
  1341. getColumnConfiguration().getColumnWidth(i));
  1342. Integer col = Integer.valueOf(i);
  1343. colWidths.put(col, width);
  1344. }
  1345. getColumnConfiguration().setColumnWidths(colWidths);
  1346. });
  1347. }
  1348. }
  1349. }
  1350. /**
  1351. * Actually add rows into the DOM, now that everything can be
  1352. * calculated.
  1353. *
  1354. * @param visualIndex
  1355. * the DOM index to add rows into
  1356. * @param numberOfRows
  1357. * the number of rows to insert
  1358. */
  1359. protected abstract void paintInsertRows(final int visualIndex,
  1360. final int numberOfRows);
  1361. protected List<TableRowElement> paintInsertStaticRows(
  1362. final int visualIndex, final int numberOfRows) {
  1363. assert isAttached() : "Can't paint rows if Escalator is not attached";
  1364. final List<TableRowElement> addedRows = new ArrayList<>();
  1365. if (numberOfRows < 1) {
  1366. return addedRows;
  1367. }
  1368. Node referenceRow;
  1369. if (root.getChildCount() != 0 && visualIndex != 0) {
  1370. // get the row node we're inserting stuff after
  1371. referenceRow = root.getChild(visualIndex - 1);
  1372. } else {
  1373. // index is 0, so just prepend.
  1374. referenceRow = null;
  1375. }
  1376. for (int row = visualIndex; row < visualIndex
  1377. + numberOfRows; row++) {
  1378. final TableRowElement tr = TableRowElement.as(DOM.createTR());
  1379. addedRows.add(tr);
  1380. tr.addClassName(getStylePrimaryName() + "-row");
  1381. ariaGridHelper.updateRole(tr, getRowElementRole());
  1382. for (int col = 0; col < columnConfiguration
  1383. .getColumnCount(); col++) {
  1384. final double colWidth = columnConfiguration
  1385. .getColumnWidthActual(col);
  1386. final TableCellElement cellElem = createCellElement(
  1387. colWidth);
  1388. tr.appendChild(cellElem);
  1389. // Set stylename and position if new cell is frozen
  1390. if (col < columnConfiguration.frozenColumns) {
  1391. cellElem.addClassName("frozen");
  1392. position.set(cellElem, scroller.lastScrollLeft, 0);
  1393. }
  1394. if (columnConfiguration.frozenColumns > 0
  1395. && col == columnConfiguration.frozenColumns - 1) {
  1396. cellElem.addClassName("last-frozen");
  1397. }
  1398. }
  1399. referenceRow = paintInsertRow(referenceRow, tr, row);
  1400. }
  1401. reapplyRowWidths();
  1402. recalculateSectionHeight();
  1403. return addedRows;
  1404. }
  1405. /**
  1406. * Inserts a single row into the DOM, invoking
  1407. * {@link #getEscalatorUpdater()}
  1408. * {@link EscalatorUpdater#preAttach(Row, Iterable) preAttach} and
  1409. * {@link EscalatorUpdater#postAttach(Row, Iterable) postAttach} before
  1410. * and after inserting the row, respectively. The row should have its
  1411. * cells already inserted.
  1412. *
  1413. * @param referenceRow
  1414. * the row after which to insert or null if insert as first
  1415. * @param tr
  1416. * the row to be inserted
  1417. * @param logicalRowIndex
  1418. * the logical index of the inserted row
  1419. * @return the inserted row to be used as the new reference
  1420. */
  1421. protected Node paintInsertRow(Node referenceRow,
  1422. final TableRowElement tr, int logicalRowIndex) {
  1423. flyweightRow.setup(tr, logicalRowIndex,
  1424. columnConfiguration.getCalculatedColumnWidths());
  1425. getEscalatorUpdater().preAttach(flyweightRow,
  1426. flyweightRow.getCells());
  1427. referenceRow = insertAfterReferenceAndUpdateIt(root, tr,
  1428. referenceRow);
  1429. getEscalatorUpdater().postAttach(flyweightRow,
  1430. flyweightRow.getCells());
  1431. updater.update(flyweightRow, flyweightRow.getCells());
  1432. /*
  1433. * the "assert" guarantees that this code is run only during
  1434. * development/debugging.
  1435. */
  1436. assert flyweightRow.teardown();
  1437. return referenceRow;
  1438. }
  1439. private Node insertAfterReferenceAndUpdateIt(final Element parent,
  1440. final Element elem, final Node referenceNode) {
  1441. if (referenceNode != null) {
  1442. parent.insertAfter(elem, referenceNode);
  1443. } else {
  1444. /*
  1445. * referencenode being null means we have offset 0, i.e. make it
  1446. * the first row
  1447. */
  1448. /*
  1449. * TODO [[optimize]]: Is insertFirst or append faster for an
  1450. * empty root?
  1451. */
  1452. parent.insertFirst(elem);
  1453. }
  1454. return elem;
  1455. }
  1456. protected abstract void recalculateSectionHeight();
  1457. /**
  1458. * Returns the height of all rows in the row container.
  1459. */
  1460. protected double calculateTotalRowHeight() {
  1461. return getDefaultRowHeight() * getRowCount();
  1462. }
  1463. /**
  1464. * {@inheritDoc}
  1465. * <p>
  1466. * <em>Implementation detail:</em> This method does no DOM modifications
  1467. * (i.e. is very cheap to call) if there is no data for columns when
  1468. * this method is called.
  1469. *
  1470. * @see #hasColumnAndRowData()
  1471. */
  1472. @Override
  1473. // overridden because of JavaDoc
  1474. public void refreshRows(final int index, final int numberOfRows) {
  1475. Range rowRange = Range.withLength(index, numberOfRows);
  1476. Range colRange = Range.withLength(0,
  1477. getColumnConfiguration().getColumnCount());
  1478. refreshCells(rowRange, colRange);
  1479. }
  1480. protected abstract void refreshCells(Range logicalRowRange,
  1481. Range colRange);
  1482. void refreshRow(TableRowElement tr, int logicalRowIndex) {
  1483. refreshRow(tr, logicalRowIndex, Range.withLength(0,
  1484. getColumnConfiguration().getColumnCount()));
  1485. }
  1486. void refreshRow(final TableRowElement tr, final int logicalRowIndex,
  1487. Range colRange) {
  1488. flyweightRow.setup(tr, logicalRowIndex,
  1489. columnConfiguration.getCalculatedColumnWidths());
  1490. Iterable<FlyweightCell> cellsToUpdate = flyweightRow
  1491. .getCells(colRange.getStart(), colRange.length());
  1492. updater.update(flyweightRow, cellsToUpdate);
  1493. /*
  1494. * the "assert" guarantees that this code is run only during
  1495. * development/debugging.
  1496. */
  1497. assert flyweightRow.teardown();
  1498. }
  1499. /**
  1500. * Create and setup an empty cell element.
  1501. *
  1502. * @param width
  1503. * the width of the cell, in pixels
  1504. *
  1505. * @return a set-up empty cell element
  1506. */
  1507. public TableCellElement createCellElement(final double width) {
  1508. final TableCellElement cellElem = TableCellElement
  1509. .as(DOM.createElement(getCellElementTagName()));
  1510. final double height = getDefaultRowHeight();
  1511. assert height >= 0 : "defaultRowHeight was negative. There's a setter leak somewhere.";
  1512. cellElem.getStyle().setHeight(height, Unit.PX);
  1513. if (width >= 0) {
  1514. cellElem.getStyle().setWidth(width, Unit.PX);
  1515. }
  1516. cellElem.addClassName(getStylePrimaryName() + "-cell");
  1517. ariaGridHelper.updateRole(cellElem, getCellElementRole());
  1518. return cellElem;
  1519. }
  1520. @Override
  1521. public TableRowElement getRowElement(int index) {
  1522. return getTrByVisualIndex(index);
  1523. }
  1524. /**
  1525. * Gets the child element that is visually at a certain index.
  1526. *
  1527. * @param index
  1528. * the index of the element to retrieve
  1529. * @return the element at position {@code index}
  1530. * @throws IndexOutOfBoundsException
  1531. * if {@code index} is not valid within {@link #root}
  1532. */
  1533. protected abstract TableRowElement getTrByVisualIndex(int index)
  1534. throws IndexOutOfBoundsException;
  1535. protected void paintRemoveColumns(final int offset,
  1536. final int numberOfColumns) {
  1537. for (int i = 0; i < getDomRowCount(); i++) {
  1538. TableRowElement row = getTrByVisualIndex(i);
  1539. flyweightRow.setup(row, i,
  1540. columnConfiguration.getCalculatedColumnWidths());
  1541. Iterable<FlyweightCell> attachedCells = flyweightRow
  1542. .getCells(offset, numberOfColumns);
  1543. getEscalatorUpdater().preDetach(flyweightRow, attachedCells);
  1544. for (int j = 0; j < numberOfColumns; j++) {
  1545. row.getCells().getItem(offset).removeFromParent();
  1546. }
  1547. Iterable<FlyweightCell> detachedCells = flyweightRow
  1548. .getUnattachedCells(offset, numberOfColumns);
  1549. getEscalatorUpdater().postDetach(flyweightRow, detachedCells);
  1550. assert flyweightRow.teardown();
  1551. }
  1552. }
  1553. protected void paintInsertColumns(final int offset,
  1554. final int numberOfColumns, boolean frozen) {
  1555. for (int row = 0; row < getDomRowCount(); row++) {
  1556. final TableRowElement tr = getTrByVisualIndex(row);
  1557. int logicalRowIndex = getLogicalRowIndex(tr);
  1558. paintInsertCells(tr, logicalRowIndex, offset, numberOfColumns);
  1559. }
  1560. reapplyRowWidths();
  1561. if (frozen) {
  1562. for (int col = offset; col < offset + numberOfColumns; col++) {
  1563. setColumnFrozen(col, true);
  1564. }
  1565. }
  1566. }
  1567. /**
  1568. * Inserts new cell elements into a single row element, invoking
  1569. * {@link #getEscalatorUpdater()}
  1570. * {@link EscalatorUpdater#preAttach(Row, Iterable) preAttach} and
  1571. * {@link EscalatorUpdater#postAttach(Row, Iterable) postAttach} before
  1572. * and after inserting the cells, respectively.
  1573. * <p>
  1574. * Precondition: The row must be already attached to the DOM and the
  1575. * FlyweightCell instances corresponding to the new columns added to
  1576. * {@code flyweightRow}.
  1577. *
  1578. * @param tr
  1579. * the row in which to insert the cells
  1580. * @param logicalRowIndex
  1581. * the index of the row
  1582. * @param offset
  1583. * the index of the first cell
  1584. * @param numberOfCells
  1585. * the number of cells to insert
  1586. */
  1587. private void paintInsertCells(final TableRowElement tr,
  1588. int logicalRowIndex, final int offset,
  1589. final int numberOfCells) {
  1590. assert root.isOrHasChild(
  1591. tr) : "The row must be attached to the document";
  1592. flyweightRow.setup(tr, logicalRowIndex,
  1593. columnConfiguration.getCalculatedColumnWidths());
  1594. Iterable<FlyweightCell> cells = flyweightRow
  1595. .getUnattachedCells(offset, numberOfCells);
  1596. for (FlyweightCell cell : cells) {
  1597. final double colWidth = columnConfiguration
  1598. .getColumnWidthActual(cell.getColumn());
  1599. final TableCellElement cellElem = createCellElement(colWidth);
  1600. cell.setElement(cellElem);
  1601. }
  1602. getEscalatorUpdater().preAttach(flyweightRow, cells);
  1603. Node referenceCell;
  1604. if (offset != 0) {
  1605. referenceCell = tr.getChild(offset - 1);
  1606. } else {
  1607. referenceCell = null;
  1608. }
  1609. for (FlyweightCell cell : cells) {
  1610. referenceCell = insertAfterReferenceAndUpdateIt(tr,
  1611. cell.getElement(), referenceCell);
  1612. }
  1613. getEscalatorUpdater().postAttach(flyweightRow, cells);
  1614. getEscalatorUpdater().update(flyweightRow, cells);
  1615. assert flyweightRow.teardown();
  1616. }
  1617. public void setColumnFrozen(int column, boolean frozen) {
  1618. toggleFrozenColumnClass(column, frozen, "frozen");
  1619. if (frozen) {
  1620. updateFreezePosition(column, scroller.lastScrollLeft);
  1621. }
  1622. }
  1623. private void toggleFrozenColumnClass(int column, boolean frozen,
  1624. String className) {
  1625. final NodeList<TableRowElement> childRows = root.getRows();
  1626. for (int row = 0; row < childRows.getLength(); row++) {
  1627. final TableRowElement tr = childRows.getItem(row);
  1628. if (!rowCanBeFrozen(tr)) {
  1629. continue;
  1630. }
  1631. TableCellElement cell = tr.getCells().getItem(column);
  1632. if (frozen) {
  1633. cell.addClassName(className);
  1634. } else {
  1635. cell.removeClassName(className);
  1636. position.reset(cell);
  1637. }
  1638. }
  1639. }
  1640. public void setColumnLastFrozen(int column, boolean lastFrozen) {
  1641. toggleFrozenColumnClass(column, lastFrozen, "last-frozen");
  1642. }
  1643. public void updateFreezePosition(int column, double scrollLeft) {
  1644. final NodeList<TableRowElement> childRows = root.getRows();
  1645. for (int row = 0; row < childRows.getLength(); row++) {
  1646. final TableRowElement tr = childRows.getItem(row);
  1647. if (rowCanBeFrozen(tr)) {
  1648. TableCellElement cell = tr.getCells().getItem(column);
  1649. position.set(cell, scrollLeft, 0);
  1650. }
  1651. }
  1652. }
  1653. /**
  1654. * Checks whether a row is an element, or contains such elements, that
  1655. * can be frozen.
  1656. * <p>
  1657. * In practice, this applies for all header and footer rows. For body
  1658. * rows, it applies for all rows except spacer rows.
  1659. *
  1660. * @since 7.5.0
  1661. *
  1662. * @param tr
  1663. * the row element to check whether it, or any of its its
  1664. * descendants can be frozen
  1665. * @return <code>true</code> if the given element, or any of its
  1666. * descendants, can be frozen
  1667. */
  1668. protected abstract boolean rowCanBeFrozen(TableRowElement tr);
  1669. /**
  1670. * Iterates through all the cells in a column and returns the width of
  1671. * the widest element in this RowContainer.
  1672. *
  1673. * @param index
  1674. * the index of the column to inspect
  1675. * @return the pixel width of the widest element in the indicated column
  1676. */
  1677. public double calculateMaxColWidth(int index) {
  1678. TableRowElement row = TableRowElement
  1679. .as(root.getFirstChildElement());
  1680. double maxWidth = 0;
  1681. while (row != null) {
  1682. final TableCellElement cell = row.getCells().getItem(index);
  1683. final boolean isVisible = !cell.getStyle().getDisplay()
  1684. .equals(Display.NONE.getCssName());
  1685. if (isVisible) {
  1686. maxWidth = Math.max(maxWidth, getBoundingWidth(cell));
  1687. }
  1688. row = TableRowElement.as(row.getNextSiblingElement());
  1689. }
  1690. return maxWidth;
  1691. }
  1692. /**
  1693. * Reapplies all the cells' widths according to the calculated widths in
  1694. * the column configuration.
  1695. */
  1696. public void reapplyColumnWidths() {
  1697. Element row = root.getFirstChildElement();
  1698. while (row != null) {
  1699. // Only handle non-spacer rows
  1700. if (!body.spacerContainer.isSpacer(row)) {
  1701. Element cell = row.getFirstChildElement();
  1702. int columnIndex = 0;
  1703. while (cell != null) {
  1704. final double width = getCalculatedColumnWidthWithColspan(
  1705. cell, columnIndex);
  1706. /*
  1707. * TODO Should Escalator implement ProvidesResize at
  1708. * some point, this is where we need to do that.
  1709. */
  1710. cell.getStyle().setWidth(width, Unit.PX);
  1711. cell = cell.getNextSiblingElement();
  1712. columnIndex++;
  1713. }
  1714. }
  1715. row = row.getNextSiblingElement();
  1716. }
  1717. reapplyRowWidths();
  1718. }
  1719. private double getCalculatedColumnWidthWithColspan(final Element cell,
  1720. final int columnIndex) {
  1721. final int colspan = cell.getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  1722. Range spannedColumns = Range.withLength(columnIndex, colspan);
  1723. /*
  1724. * Since browsers don't explode with overflowing colspans, escalator
  1725. * shouldn't either.
  1726. */
  1727. if (spannedColumns.getEnd() > columnConfiguration
  1728. .getColumnCount()) {
  1729. spannedColumns = Range.between(columnIndex,
  1730. columnConfiguration.getColumnCount());
  1731. }
  1732. return columnConfiguration
  1733. .getCalculatedColumnsWidth(spannedColumns);
  1734. }
  1735. /**
  1736. * Applies the total length of the columns to each row element.
  1737. * <p>
  1738. * <em>Note:</em> In contrast to {@link #reapplyColumnWidths()}, this
  1739. * method only modifies the width of the {@code
  1740. *
  1741. <tr>
  1742. * } element, not the cells within.
  1743. */
  1744. protected void reapplyRowWidths() {
  1745. double rowWidth = columnConfiguration.calculateRowWidth();
  1746. if (rowWidth < 0) {
  1747. return;
  1748. }
  1749. Element row = root.getFirstChildElement();
  1750. while (row != null) {
  1751. // IF there is a rounding error when summing the columns, we
  1752. // need to round the tr width up to ensure that columns fit and
  1753. // do not wrap
  1754. // E.g.122.95+123.25+103.75+209.25+83.52+88.57+263.45+131.21+126.85+113.13=1365.9299999999998
  1755. // For this we must set 1365.93 or the last column will wrap
  1756. row.getStyle().setWidth(WidgetUtil.roundSizeUp(rowWidth),
  1757. Unit.PX);
  1758. row = row.getNextSiblingElement();
  1759. }
  1760. }
  1761. /**
  1762. * The primary style name for the container.
  1763. *
  1764. * @param primaryStyleName
  1765. * the style name to use as prefix for all row and cell style
  1766. * names.
  1767. */
  1768. protected void setStylePrimaryName(String primaryStyleName) {
  1769. String oldStyle = getStylePrimaryName();
  1770. if (SharedUtil.equals(oldStyle, primaryStyleName)) {
  1771. return;
  1772. }
  1773. this.primaryStyleName = primaryStyleName;
  1774. // Update already rendered rows and cells
  1775. Element row = root.getRows().getItem(0);
  1776. while (row != null) {
  1777. UIObject.setStylePrimaryName(row, primaryStyleName + "-row");
  1778. Element cell = TableRowElement.as(row).getCells().getItem(0);
  1779. while (cell != null) {
  1780. assert TableCellElement.is(cell);
  1781. UIObject.setStylePrimaryName(cell,
  1782. primaryStyleName + "-cell");
  1783. cell = cell.getNextSiblingElement();
  1784. }
  1785. row = row.getNextSiblingElement();
  1786. }
  1787. }
  1788. /**
  1789. * Returns the primary style name of the container.
  1790. *
  1791. * @return The primary style name or <code>null</code> if not set.
  1792. */
  1793. protected String getStylePrimaryName() {
  1794. return primaryStyleName;
  1795. }
  1796. @Override
  1797. public void setDefaultRowHeight(double px)
  1798. throws IllegalArgumentException {
  1799. if (px < 1) {
  1800. throw new IllegalArgumentException(
  1801. "Height must be positive. " + px + " was given.");
  1802. }
  1803. defaultRowHeightShouldBeAutodetected = false;
  1804. defaultRowHeight = px;
  1805. reapplyDefaultRowHeights();
  1806. applyHeightByRows();
  1807. }
  1808. @Override
  1809. public double getDefaultRowHeight() {
  1810. return defaultRowHeight;
  1811. }
  1812. /**
  1813. * The default height of rows has (most probably) changed.
  1814. * <p>
  1815. * Make sure that the displayed rows with a default height are updated
  1816. * in height and top position.
  1817. * <p>
  1818. * <em>Note:</em>This implementation should not call
  1819. * {@link Escalator#recalculateElementSizes()} - it is done by the
  1820. * discretion of the caller of this method.
  1821. */
  1822. protected abstract void reapplyDefaultRowHeights();
  1823. protected void reapplyRowHeight(final TableRowElement tr,
  1824. final double heightPx) {
  1825. assert heightPx >= 0 : "Height must not be negative";
  1826. Element cellElem = tr.getFirstChildElement();
  1827. while (cellElem != null) {
  1828. cellElem.getStyle().setHeight(heightPx, Unit.PX);
  1829. cellElem = cellElem.getNextSiblingElement();
  1830. }
  1831. /*
  1832. * no need to apply height to tr-element, it'll be resized
  1833. * implicitly.
  1834. */
  1835. }
  1836. protected void setRowPosition(final TableRowElement tr, final int x,
  1837. final double y) {
  1838. positions.set(tr, x, y);
  1839. }
  1840. /**
  1841. * Returns <em>the assigned</em> top position for the given element.
  1842. * <p>
  1843. * <em>Note:</em> This method does not calculate what a row's top
  1844. * position should be. It just returns an assigned value, correct or
  1845. * not.
  1846. *
  1847. * @param tr
  1848. * the table row element to measure
  1849. * @return the current top position for {@code tr}
  1850. * @see BodyRowContainerImpl#getRowTop(int)
  1851. */
  1852. protected double getRowTop(final TableRowElement tr) {
  1853. return positions.getTop(tr);
  1854. }
  1855. protected void removeRowPosition(TableRowElement tr) {
  1856. positions.remove(tr);
  1857. }
  1858. /**
  1859. * Triggers delayed auto-detection of default row height if it hasn't
  1860. * been set by that point and the Escalator is both attached and
  1861. * displayed.
  1862. */
  1863. public void autodetectRowHeightLater() {
  1864. autodetectingRowHeightLater = true;
  1865. Scheduler.get().scheduleFinally(() -> {
  1866. if (defaultRowHeightShouldBeAutodetected && isAttached()
  1867. && WidgetUtil.isDisplayed(getElement())) {
  1868. autodetectRowHeightNow();
  1869. defaultRowHeightShouldBeAutodetected = false;
  1870. }
  1871. autodetectingRowHeightLater = false;
  1872. });
  1873. }
  1874. @Override
  1875. public boolean isAutodetectingRowHeightLater() {
  1876. return autodetectingRowHeightLater;
  1877. }
  1878. private void fireRowHeightChangedEventFinally() {
  1879. if (!rowHeightChangedEventFired) {
  1880. rowHeightChangedEventFired = true;
  1881. Scheduler.get().scheduleFinally(() -> {
  1882. fireEvent(new RowHeightChangedEvent());
  1883. rowHeightChangedEventFired = false;
  1884. });
  1885. }
  1886. }
  1887. /**
  1888. * Auto-detect row height immediately, if possible. If Escalator isn't
  1889. * attached and displayed yet, auto-detecting cannot be performed
  1890. * correctly. In such cases auto-detecting is left to wait for these
  1891. * conditions to change, and will be performed when they do.
  1892. */
  1893. public void autodetectRowHeightNow() {
  1894. if (!isAttached() || !WidgetUtil.isDisplayed(getElement())) {
  1895. // Run again when attached and displayed
  1896. defaultRowHeightShouldBeAutodetected = true;
  1897. return;
  1898. }
  1899. final double oldRowHeight = defaultRowHeight;
  1900. final Element detectionTr = DOM.createTR();
  1901. detectionTr.setClassName(getStylePrimaryName() + "-row");
  1902. final Element cellElem = DOM.createElement(getCellElementTagName());
  1903. cellElem.setClassName(getStylePrimaryName() + "-cell");
  1904. cellElem.setInnerText("Ij");
  1905. detectionTr.appendChild(cellElem);
  1906. root.appendChild(detectionTr);
  1907. double boundingHeight = getBoundingHeight(cellElem);
  1908. defaultRowHeight = Math.max(1.0d, boundingHeight);
  1909. root.removeChild(detectionTr);
  1910. if (root.hasChildNodes()) {
  1911. reapplyDefaultRowHeights();
  1912. applyHeightByRows();
  1913. }
  1914. if (oldRowHeight != defaultRowHeight) {
  1915. fireRowHeightChangedEventFinally();
  1916. }
  1917. }
  1918. @Override
  1919. public Cell getCell(final Element element) {
  1920. if (element == null) {
  1921. throw new IllegalArgumentException("Element cannot be null");
  1922. }
  1923. /*
  1924. * Ensure that element is not root nor the direct descendant of root
  1925. * (a row or spacer) and ensure the element is inside the dom
  1926. * hierarchy of the root element. If not, return null.
  1927. */
  1928. if (root == element || element.getParentElement() == root
  1929. || !root.isOrHasChild(element)) {
  1930. return null;
  1931. }
  1932. /*
  1933. * Ensure element is the cell element by iterating up the DOM
  1934. * hierarchy until reaching cell element.
  1935. */
  1936. Element cellElementCandidate = element;
  1937. while (cellElementCandidate.getParentElement()
  1938. .getParentElement() != root) {
  1939. cellElementCandidate = cellElementCandidate.getParentElement();
  1940. }
  1941. final TableCellElement cellElement = TableCellElement
  1942. .as(cellElementCandidate);
  1943. // Find dom column
  1944. int domColumnIndex = -1;
  1945. for (Element e = cellElement; e != null; e = e
  1946. .getPreviousSiblingElement()) {
  1947. domColumnIndex++;
  1948. }
  1949. // Find dom row
  1950. int domRowIndex = -1;
  1951. for (Element e = cellElement.getParentElement(); e != null; e = e
  1952. .getPreviousSiblingElement()) {
  1953. domRowIndex++;
  1954. }
  1955. return new Cell(domRowIndex, domColumnIndex, cellElement);
  1956. }
  1957. double measureCellWidth(TableCellElement cell, boolean withContent) {
  1958. /*
  1959. * To get the actual width of the contents, we need to get the cell
  1960. * content without any hardcoded height or width.
  1961. *
  1962. * But we don't want to modify the existing column, because that
  1963. * might trigger some unnecessary listeners and whatnot. So,
  1964. * instead, we make a deep clone of that cell, but without any
  1965. * explicit dimensions, and measure that instead.
  1966. */
  1967. TableCellElement cellClone = TableCellElement
  1968. .as((Element) cell.cloneNode(withContent));
  1969. if (!withContent || columnConfiguration
  1970. .getColumnWidth(cell.getCellIndex()) < 0) {
  1971. clearRelativeWidthContents(cellClone);
  1972. }
  1973. cellClone.getStyle().clearHeight();
  1974. cellClone.getStyle().clearWidth();
  1975. cell.getParentElement().insertBefore(cellClone, cell);
  1976. double requiredWidth = getBoundingWidth(cellClone);
  1977. if (BrowserInfo.get().isIE()) {
  1978. /*
  1979. * IE browsers have some issues with subpixels. Occasionally
  1980. * content is overflown even if not necessary. Increase the
  1981. * counted required size by 0.01 just to be on the safe side.
  1982. */
  1983. requiredWidth += 0.01;
  1984. }
  1985. cellClone.removeFromParent();
  1986. return requiredWidth;
  1987. }
  1988. /**
  1989. * Contents of an element that is configured to have relative width
  1990. * shouldn't be taken into consideration when measuring minimum widths.
  1991. * Thus any such contents within the element hierarchy need to be
  1992. * cleared out for accurate results. The element itself should remain,
  1993. * however, in case it has styles that affect the end results.
  1994. *
  1995. * @param elem
  1996. * an element that might have unnecessary content that
  1997. * interferes with minimum width calculations
  1998. */
  1999. private void clearRelativeWidthContents(Element elem) {
  2000. try {
  2001. String width = elem.getStyle().getWidth();
  2002. if (width != null && width.endsWith("%")) {
  2003. if (elem.hasChildNodes()) {
  2004. elem.removeAllChildren();
  2005. // add a fake child so that :empty behavior doesn't
  2006. // change
  2007. elem.setInnerHTML("<a/>");
  2008. } else {
  2009. elem.setInnerHTML(null);
  2010. }
  2011. }
  2012. } catch (JavaScriptException e) {
  2013. // no width set, move on
  2014. }
  2015. for (int i = 0; i < elem.getChildCount(); ++i) {
  2016. Node node = elem.getChild(i);
  2017. if (node instanceof Element) {
  2018. clearRelativeWidthContents((Element) node);
  2019. }
  2020. }
  2021. }
  2022. /**
  2023. * Gets the minimum width needed to display the cell properly.
  2024. *
  2025. * @param colIndex
  2026. * index of column to measure
  2027. * @param withContent
  2028. * <code>true</code> if content is taken into account,
  2029. * <code>false</code> if not
  2030. * @return cell width needed for displaying correctly
  2031. */
  2032. double measureMinCellWidth(int colIndex, boolean withContent) {
  2033. assert isAttached() : "Can't measure max width of cell, since Escalator is not attached to the DOM.";
  2034. double minCellWidth = -1;
  2035. NodeList<TableRowElement> rows = root.getRows();
  2036. for (int row = 0; row < rows.getLength(); row++) {
  2037. TableCellElement cell = rows.getItem(row).getCells()
  2038. .getItem(colIndex);
  2039. if (cell != null && !cellIsPartOfSpan(cell)) {
  2040. double cellWidth = measureCellWidth(cell, withContent);
  2041. minCellWidth = Math.max(minCellWidth, cellWidth);
  2042. }
  2043. }
  2044. return minCellWidth;
  2045. }
  2046. private boolean cellIsPartOfSpan(TableCellElement cell) {
  2047. boolean cellHasColspan = cell.getColSpan() > 1;
  2048. boolean cellIsHidden = Display.NONE.getCssName()
  2049. .equals(cell.getStyle().getDisplay());
  2050. return cellHasColspan || cellIsHidden;
  2051. }
  2052. void refreshColumns(int index, int numberOfColumns) {
  2053. if (getRowCount() > 0) {
  2054. Range rowRange = Range.withLength(0, getRowCount());
  2055. Range colRange = Range.withLength(index, numberOfColumns);
  2056. refreshCells(rowRange, colRange);
  2057. }
  2058. }
  2059. /**
  2060. * The height of this table section.
  2061. * <p>
  2062. * Note that {@link Escalator#getBody() the body} will calculate its
  2063. * height, while the others will return a precomputed value.
  2064. *
  2065. * @since 7.5.0
  2066. *
  2067. * @return the height of this table section
  2068. */
  2069. protected abstract double getHeightOfSection();
  2070. /**
  2071. * Gets the logical row index for the given table row element.
  2072. *
  2073. * @param tr
  2074. * the table row element inside this container.
  2075. * @return the logical index of the given element
  2076. */
  2077. public int getLogicalRowIndex(final TableRowElement tr) {
  2078. // Note: BodyRowContainerImpl overrides this behaviour, since the
  2079. // physical index and logical index don't match there. For header
  2080. // and footer there is a match.
  2081. return tr.getSectionRowIndex();
  2082. };
  2083. }
  2084. private abstract class AbstractStaticRowContainer
  2085. extends AbstractRowContainer {
  2086. /** The height of the combined rows in the DOM. Never negative. */
  2087. private double heightOfSection = 0;
  2088. public AbstractStaticRowContainer(
  2089. final TableSectionElement headElement) {
  2090. super(headElement);
  2091. }
  2092. @Override
  2093. public int getDomRowCount() {
  2094. return root.getChildCount();
  2095. }
  2096. @Override
  2097. protected void paintRemoveRows(final int index,
  2098. final int numberOfRows) {
  2099. for (int i = index; i < index + numberOfRows; i++) {
  2100. final TableRowElement tr = root.getRows().getItem(index);
  2101. paintRemoveRow(tr, index);
  2102. }
  2103. recalculateSectionHeight();
  2104. }
  2105. @Override
  2106. protected TableRowElement getTrByVisualIndex(final int index)
  2107. throws IndexOutOfBoundsException {
  2108. if (index >= 0 && index < root.getChildCount()) {
  2109. return root.getRows().getItem(index);
  2110. } else {
  2111. throw new IndexOutOfBoundsException(
  2112. "No such visual index: " + index);
  2113. }
  2114. }
  2115. @Override
  2116. public void insertRows(int index, int numberOfRows) {
  2117. super.insertRows(index, numberOfRows);
  2118. recalculateElementSizes();
  2119. applyHeightByRows();
  2120. }
  2121. @Override
  2122. public void removeRows(int index, int numberOfRows) {
  2123. /*
  2124. * While the rows in a static section are removed, the scrollbar is
  2125. * temporarily shrunk and then re-expanded. This leads to the fact
  2126. * that the scroll position is scooted up a bit. This means that we
  2127. * need to reset the position here.
  2128. *
  2129. * If Escalator, at some point, gets a JIT evaluation functionality,
  2130. * this re-setting is a strong candidate for removal.
  2131. */
  2132. double oldScrollPos = verticalScrollbar.getScrollPos();
  2133. super.removeRows(index, numberOfRows);
  2134. recalculateElementSizes();
  2135. applyHeightByRows();
  2136. verticalScrollbar.setScrollPos(oldScrollPos);
  2137. }
  2138. @Override
  2139. protected void reapplyDefaultRowHeights() {
  2140. if (root.getChildCount() == 0) {
  2141. return;
  2142. }
  2143. Profiler.enter(
  2144. "Escalator.AbstractStaticRowContainer.reapplyDefaultRowHeights");
  2145. Element tr = root.getRows().getItem(0);
  2146. while (tr != null) {
  2147. reapplyRowHeight(TableRowElement.as(tr), getDefaultRowHeight());
  2148. tr = tr.getNextSiblingElement();
  2149. }
  2150. /*
  2151. * Because all rows are immediately displayed in the static row
  2152. * containers, the section's overall height has most probably
  2153. * changed.
  2154. */
  2155. recalculateSectionHeight();
  2156. Profiler.leave(
  2157. "Escalator.AbstractStaticRowContainer.reapplyDefaultRowHeights");
  2158. }
  2159. @Override
  2160. protected void recalculateSectionHeight() {
  2161. Profiler.enter(
  2162. "Escalator.AbstractStaticRowContainer.recalculateSectionHeight");
  2163. double newHeight = calculateTotalRowHeight();
  2164. if (newHeight != heightOfSection) {
  2165. heightOfSection = newHeight;
  2166. sectionHeightCalculated();
  2167. /*
  2168. * We need to update the scrollbar dimension at this point. If
  2169. * we are scrolled too far down and the static section shrinks,
  2170. * the body will try to render rows that don't exist during
  2171. * body.verifyEscalatorCount. This is because the logical row
  2172. * indices are calculated from the scrollbar position.
  2173. */
  2174. verticalScrollbar.setOffsetSize(
  2175. heightOfEscalator - header.getHeightOfSection()
  2176. - footer.getHeightOfSection());
  2177. body.verifyEscalatorCount();
  2178. body.spacerContainer.updateSpacerDecosVisibility();
  2179. }
  2180. Profiler.leave(
  2181. "Escalator.AbstractStaticRowContainer.recalculateSectionHeight");
  2182. }
  2183. /**
  2184. * Informs the row container that the height of its respective table
  2185. * section has changed.
  2186. * <p>
  2187. * These calculations might affect some layouting logic, such as the
  2188. * body is being offset by the footer, the footer needs to be readjusted
  2189. * according to its height, and so on.
  2190. * <p>
  2191. * A table section is either header, body or footer.
  2192. */
  2193. protected abstract void sectionHeightCalculated();
  2194. @Override
  2195. protected void refreshCells(Range logicalRowRange, Range colRange) {
  2196. assertArgumentsAreValidAndWithinRange(logicalRowRange.getStart(),
  2197. logicalRowRange.length());
  2198. if (!isAttached()) {
  2199. return;
  2200. }
  2201. Profiler.enter("Escalator.AbstractStaticRowContainer.refreshCells");
  2202. if (hasColumnAndRowData()) {
  2203. for (int row = logicalRowRange.getStart(); row < logicalRowRange
  2204. .getEnd(); row++) {
  2205. final TableRowElement tr = getTrByVisualIndex(row);
  2206. refreshRow(tr, row, colRange);
  2207. }
  2208. }
  2209. Profiler.leave("Escalator.AbstractStaticRowContainer.refreshCells");
  2210. }
  2211. @Override
  2212. protected void paintInsertRows(int visualIndex, int numberOfRows) {
  2213. paintInsertStaticRows(visualIndex, numberOfRows);
  2214. }
  2215. @Override
  2216. protected boolean rowCanBeFrozen(TableRowElement tr) {
  2217. assert root.isOrHasChild(
  2218. tr) : "Row does not belong to this table section";
  2219. return true;
  2220. }
  2221. @Override
  2222. protected double getHeightOfSection() {
  2223. return Math.max(0, heightOfSection);
  2224. }
  2225. }
  2226. private class HeaderRowContainer extends AbstractStaticRowContainer {
  2227. public HeaderRowContainer(final TableSectionElement headElement) {
  2228. super(headElement);
  2229. }
  2230. @Override
  2231. protected void sectionHeightCalculated() {
  2232. double heightOfSection = getHeightOfSection();
  2233. bodyElem.getStyle().setMarginTop(heightOfSection, Unit.PX);
  2234. spacerDecoContainer.getStyle().setMarginTop(heightOfSection,
  2235. Unit.PX);
  2236. verticalScrollbar.getElement().getStyle().setTop(heightOfSection,
  2237. Unit.PX);
  2238. headerDeco.getStyle().setHeight(heightOfSection, Unit.PX);
  2239. }
  2240. @Override
  2241. protected String getCellElementTagName() {
  2242. return "th";
  2243. }
  2244. @Override
  2245. protected AriaGridRole getRowElementRole() {
  2246. return AriaGridRole.ROWHEADER;
  2247. }
  2248. @Override
  2249. protected AriaGridRole getCellElementRole() {
  2250. return AriaGridRole.COLUMNHEADER;
  2251. }
  2252. @Override
  2253. public void setStylePrimaryName(String primaryStyleName) {
  2254. super.setStylePrimaryName(primaryStyleName);
  2255. UIObject.setStylePrimaryName(root, primaryStyleName + "-header");
  2256. }
  2257. }
  2258. private class FooterRowContainer extends AbstractStaticRowContainer {
  2259. public FooterRowContainer(final TableSectionElement footElement) {
  2260. super(footElement);
  2261. }
  2262. @Override
  2263. public void setStylePrimaryName(String primaryStyleName) {
  2264. super.setStylePrimaryName(primaryStyleName);
  2265. UIObject.setStylePrimaryName(root, primaryStyleName + "-footer");
  2266. }
  2267. @Override
  2268. protected String getCellElementTagName() {
  2269. return "td";
  2270. }
  2271. @Override
  2272. protected void sectionHeightCalculated() {
  2273. double headerHeight = header.getHeightOfSection();
  2274. double footerHeight = footer.getHeightOfSection();
  2275. int vscrollHeight = (int) Math
  2276. .floor(heightOfEscalator - headerHeight - footerHeight);
  2277. final boolean horizontalScrollbarNeeded = columnConfiguration
  2278. .calculateRowWidth() > widthOfEscalator;
  2279. if (horizontalScrollbarNeeded) {
  2280. vscrollHeight -= horizontalScrollbar.getScrollbarThickness();
  2281. }
  2282. footerDeco.getStyle().setHeight(footer.getHeightOfSection(),
  2283. Unit.PX);
  2284. verticalScrollbar.setOffsetSize(vscrollHeight);
  2285. }
  2286. }
  2287. private class BodyRowContainerImpl extends AbstractRowContainer
  2288. implements BodyRowContainer {
  2289. /*
  2290. * TODO [[optimize]]: check whether a native JsArray might be faster
  2291. * than LinkedList
  2292. */
  2293. /**
  2294. * The order in which row elements are rendered visually in the browser,
  2295. * with the help of CSS tricks. Usually has nothing to do with the DOM
  2296. * order.
  2297. *
  2298. * @see #sortDomElements()
  2299. */
  2300. private final LinkedList<TableRowElement> visualRowOrder = new LinkedList<>();
  2301. /**
  2302. * The logical index of the topmost row.
  2303. *
  2304. * @deprecated Use the accessors {@link #setTopRowLogicalIndex(int)},
  2305. * {@link #updateTopRowLogicalIndex(int)} and
  2306. * {@link #getTopRowLogicalIndex()} instead
  2307. */
  2308. @Deprecated
  2309. private int topRowLogicalIndex = 0;
  2310. /**
  2311. * A callback function to be executed after new rows are added to the
  2312. * escalator.
  2313. */
  2314. private Consumer<List<TableRowElement>> newEscalatorRowCallback;
  2315. /**
  2316. * Set the logical index of the first dom row in visual order.
  2317. * <p>
  2318. * NOTE: this is not necessarily the first dom row in the dom tree, just
  2319. * the one positioned to the top with CSS. See maintenance notes at the
  2320. * top of this class for further information.
  2321. *
  2322. * @param topRowLogicalIndex
  2323. * logical index of the first dom row in visual order, might
  2324. * not match the dom tree order
  2325. */
  2326. private void setTopRowLogicalIndex(int topRowLogicalIndex) {
  2327. if (LogConfiguration.loggingIsEnabled(Level.INFO)) {
  2328. Logger.getLogger("Escalator.BodyRowContainer")
  2329. .fine("topRowLogicalIndex: " + this.topRowLogicalIndex
  2330. + " -> " + topRowLogicalIndex);
  2331. }
  2332. assert topRowLogicalIndex >= 0 : "topRowLogicalIndex became negative (top left cell contents: "
  2333. + visualRowOrder.getFirst().getCells().getItem(0)
  2334. .getInnerText()
  2335. + ") ";
  2336. /*
  2337. * if there's a smart way of evaluating and asserting the max index,
  2338. * this would be a nice place to put it. I haven't found out an
  2339. * effective and generic solution.
  2340. */
  2341. this.topRowLogicalIndex = topRowLogicalIndex;
  2342. }
  2343. /**
  2344. * Returns the logical index of the first dom row in visual order. This
  2345. * also gives the offset between the logical and visual indexes.
  2346. * <p>
  2347. * NOTE: this is not necessarily the first dom row in the dom tree, just
  2348. * the one positioned to the top with CSS. See maintenance notes at the
  2349. * top of this class for further information.
  2350. *
  2351. * @return logical index of the first dom row in visual order, might not
  2352. * match the dom tree order
  2353. */
  2354. public int getTopRowLogicalIndex() {
  2355. return topRowLogicalIndex;
  2356. }
  2357. /**
  2358. * Updates the logical index of the first dom row in visual order with
  2359. * the given difference.
  2360. * <p>
  2361. * NOTE: this is not necessarily the first dom row in the dom tree, just
  2362. * the one positioned to the top with CSS. See maintenance notes at the
  2363. * top of this class for further information.
  2364. *
  2365. * @param diff
  2366. * the amount to increase or decrease the logical index of
  2367. * the first dom row in visual order
  2368. */
  2369. private void updateTopRowLogicalIndex(int diff) {
  2370. setTopRowLogicalIndex(topRowLogicalIndex + diff);
  2371. }
  2372. private class DeferredDomSorter {
  2373. private static final int SORT_DELAY_MILLIS = 50;
  2374. // as it happens, 3 frames = 50ms @ 60fps.
  2375. private static final int REQUIRED_FRAMES_PASSED = 3;
  2376. private final AnimationCallback frameCounter = new AnimationCallback() {
  2377. @Override
  2378. public void execute(double timestamp) {
  2379. framesPassed++;
  2380. boolean domWasSorted = sortIfConditionsMet();
  2381. if (!domWasSorted) {
  2382. animationHandle = AnimationScheduler.get()
  2383. .requestAnimationFrame(this);
  2384. } else {
  2385. waiting = false;
  2386. }
  2387. }
  2388. };
  2389. private int framesPassed;
  2390. private double startTime;
  2391. private AnimationHandle animationHandle;
  2392. /** <code>true</code> if a sort is scheduled */
  2393. public boolean waiting = false;
  2394. public void reschedule() {
  2395. waiting = true;
  2396. resetConditions();
  2397. animationHandle = AnimationScheduler.get()
  2398. .requestAnimationFrame(frameCounter);
  2399. }
  2400. private boolean sortIfConditionsMet() {
  2401. boolean enoughFramesHavePassed = framesPassed >= REQUIRED_FRAMES_PASSED;
  2402. boolean enoughTimeHasPassed = (Duration.currentTimeMillis()
  2403. - startTime) >= SORT_DELAY_MILLIS;
  2404. boolean notTouchActivity = !scroller.touchHandlerBundle.touching;
  2405. boolean conditionsMet = enoughFramesHavePassed
  2406. && enoughTimeHasPassed && notTouchActivity;
  2407. if (conditionsMet) {
  2408. resetConditions();
  2409. sortDomElements();
  2410. }
  2411. return conditionsMet;
  2412. }
  2413. private void resetConditions() {
  2414. if (animationHandle != null) {
  2415. animationHandle.cancel();
  2416. animationHandle = null;
  2417. }
  2418. startTime = Duration.currentTimeMillis();
  2419. framesPassed = 0;
  2420. }
  2421. }
  2422. private DeferredDomSorter domSorter = new DeferredDomSorter();
  2423. private final SpacerContainer spacerContainer = new SpacerContainer();
  2424. private boolean insertingOrRemoving = false;
  2425. public BodyRowContainerImpl(final TableSectionElement bodyElement) {
  2426. super(bodyElement);
  2427. }
  2428. @Override
  2429. public void setStylePrimaryName(String primaryStyleName) {
  2430. super.setStylePrimaryName(primaryStyleName);
  2431. UIObject.setStylePrimaryName(root, primaryStyleName + "-body");
  2432. spacerContainer.setStylePrimaryName(primaryStyleName);
  2433. }
  2434. public void updateEscalatorRowsOnScroll() {
  2435. if (visualRowOrder.isEmpty()) {
  2436. return;
  2437. }
  2438. boolean rowsWereMoved = false;
  2439. final double topElementPosition;
  2440. final double nextRowBottomOffset;
  2441. SpacerContainer.SpacerImpl topSpacer = spacerContainer
  2442. .getSpacer(getTopRowLogicalIndex() - 1);
  2443. if (topSpacer != null) {
  2444. topElementPosition = topSpacer.getTop();
  2445. nextRowBottomOffset = topSpacer.getHeight()
  2446. + getDefaultRowHeight();
  2447. } else {
  2448. topElementPosition = getRowTop(visualRowOrder.getFirst());
  2449. nextRowBottomOffset = getDefaultRowHeight();
  2450. }
  2451. // TODO [[mpixscroll]]
  2452. final double scrollTop = tBodyScrollTop;
  2453. final double sectionHeight = getHeightOfSection();
  2454. /*
  2455. * Calculate how the visual range is situated in relation to the
  2456. * viewport. Negative value means part of visual range is hidden
  2457. * above or below the viewport, positive value means there is a gap
  2458. * at the top or the bottom of the viewport, zero means exact match.
  2459. * If there is a gap, some rows that are out of view may need to be
  2460. * recycled from the opposite end.
  2461. */
  2462. final double viewportOffsetTop = topElementPosition - scrollTop;
  2463. final double viewportOffsetBottom = scrollTop + sectionHeight
  2464. - getRowTop(
  2465. getTopRowLogicalIndex() + visualRowOrder.size());
  2466. /*
  2467. * You can only scroll far enough to leave a gap if visualRowOrder
  2468. * contains a maximal amount of rows and there is at least one more
  2469. * outside of the visual range. Consequently there can only be a gap
  2470. * in one end of the viewport at a time.
  2471. */
  2472. if (viewportOffsetTop > 0 || (viewportOffsetTop == 0
  2473. && getTopRowLogicalIndex() > 0)) {
  2474. /*
  2475. * Scrolling up. Either there's empty room on top, or there
  2476. * should be a buffer row for tab navigation on top, but there
  2477. * isn't.
  2478. */
  2479. recycleRowsUpOnScroll(viewportOffsetTop);
  2480. rowsWereMoved = true;
  2481. } else if ((viewportOffsetBottom > 0
  2482. && (viewportOffsetTop + nextRowBottomOffset <= 0))
  2483. || (viewportOffsetBottom == 0 && (getTopRowLogicalIndex()
  2484. + visualRowOrder.size() < getRowCount() - 2))) {
  2485. /*
  2486. * Scrolling down. Either there's empty room at the bottom and
  2487. * the viewport has been scrolled more than the topmost visual
  2488. * row, or there should be a buffer row at the bottom to ensure
  2489. * tab navigation works, but there isn't.
  2490. */
  2491. recycleRowsDownOnScroll(topElementPosition, scrollTop);
  2492. // Moving rows may have removed more spacers and created another
  2493. // gap, this time the scroll position needs adjusting. The last
  2494. // row within visual range should be just below the viewport as
  2495. // a buffer for helping with tab navigation, unless it's the
  2496. // last row altogether.
  2497. int lastRowInVisualRange = getTopRowLogicalIndex()
  2498. + visualRowOrder.size() - 1;
  2499. double expectedBottom = getRowTop(lastRowInVisualRange);
  2500. if (lastRowInVisualRange == getRowCount() - 1) {
  2501. expectedBottom += getDefaultRowHeight() + spacerContainer
  2502. .getSpacerHeight(lastRowInVisualRange);
  2503. }
  2504. if (expectedBottom < scrollTop + sectionHeight) {
  2505. double expectedTop = Math.max(0,
  2506. expectedBottom - sectionHeight);
  2507. setBodyScrollPosition(tBodyScrollLeft, expectedTop);
  2508. setScrollTop(expectedTop);
  2509. }
  2510. rowsWereMoved = true;
  2511. }
  2512. if (rowsWereMoved) {
  2513. fireRowVisibilityChangeEvent();
  2514. // schedule updating of the physical indexes
  2515. domSorter.reschedule();
  2516. }
  2517. }
  2518. /**
  2519. * Recycling rows up for {@link #updateEscalatorRowsOnScroll()}.
  2520. * <p>
  2521. * NOTE: This method should not be called directly from anywhere else.
  2522. *
  2523. * @param viewportOffsetTop
  2524. */
  2525. private void recycleRowsUpOnScroll(double viewportOffsetTop) {
  2526. /*
  2527. * We can ignore spacers here, because we keep enough rows within
  2528. * the visual range to fill the viewport completely whether or not
  2529. * any spacers are shown. There is a small tradeoff of having some
  2530. * rows rendered even if they are outside of the viewport, but this
  2531. * simplifies the handling significantly (we can't know what height
  2532. * any individual spacer has before it has been rendered, which
  2533. * happens with a delay) and keeps the visual range size stable
  2534. * while scrolling. Consequently, even if there are spacers within
  2535. * the current visual range, repositioning this many rows won't
  2536. * cause us to run out of rows at the bottom.
  2537. *
  2538. * The viewportOffsetTop is positive and we round up, and
  2539. * visualRowOrder can't be empty since we are scrolling, so there is
  2540. * always going to be at least one row to move. There should also be
  2541. * one buffer row that actually falls outside of the viewport, in
  2542. * order to ensure that tabulator navigation works if the rows have
  2543. * components in them. The buffer row is only needed if filling the
  2544. * gap doesn't bring us to the top row already.
  2545. */
  2546. int rowsToFillTheGap = (int) Math
  2547. .ceil(viewportOffsetTop / getDefaultRowHeight());
  2548. // ensure we don't try to move more rows than are available
  2549. // above
  2550. rowsToFillTheGap = Math.min(rowsToFillTheGap,
  2551. getTopRowLogicalIndex());
  2552. // add the buffer row if there is room for it
  2553. if (rowsToFillTheGap < getTopRowLogicalIndex()) {
  2554. ++rowsToFillTheGap;
  2555. }
  2556. // we may have scrolled up past all the rows and beyond, can
  2557. // only recycle as many rows as we have
  2558. int rowsToRecycle = Math.min(rowsToFillTheGap,
  2559. visualRowOrder.size());
  2560. // select the rows to recycle from the end of the visual range
  2561. int end = visualRowOrder.size();
  2562. int start = end - rowsToRecycle;
  2563. /*
  2564. * Calculate the logical index for insertion point based on how many
  2565. * rows would be needed to fill the gap. Because we are recycling
  2566. * rows to the top the insertion index will also be the new top row
  2567. * logical index.
  2568. */
  2569. int newTopRowLogicalIndex = getTopRowLogicalIndex()
  2570. - rowsToFillTheGap;
  2571. // recycle the rows and move them to their new positions
  2572. moveAndUpdateEscalatorRows(Range.between(start, end), 0,
  2573. newTopRowLogicalIndex);
  2574. setTopRowLogicalIndex(newTopRowLogicalIndex);
  2575. }
  2576. /**
  2577. * Recycling rows down for {@link #updateEscalatorRowsOnScroll()}.
  2578. * <p>
  2579. * NOTE: This method should not be called directly from anywhere else.
  2580. *
  2581. * @param topElementPosition
  2582. * @param scrollTop
  2583. */
  2584. private void recycleRowsDownOnScroll(double topElementPosition,
  2585. double scrollTop) {
  2586. /*
  2587. * It's better to have any extra rows below than above, so move as
  2588. * many of them as possible regardless of how many are needed to
  2589. * fill the gap, as long as one buffer row remains at the top. It
  2590. * should not be possible to scroll down enough to create a gap
  2591. * without it being possible to recycle rows to fill the gap, so
  2592. * viewport itself doesn't need adjusting no matter what.
  2593. */
  2594. // we already have the rows and spacers here and we don't want
  2595. // to recycle rows that are going to stay visible, so the
  2596. // spacers have to be taken into account
  2597. double extraRowPxAbove = getRowHeightsSumBetweenPxExcludingSpacers(
  2598. topElementPosition, scrollTop);
  2599. // how many rows fit within that extra space and can be
  2600. // recycled, rounded towards zero to avoid moving any partially
  2601. // visible rows
  2602. int rowsToCoverTheExtra = (int) Math
  2603. .floor(extraRowPxAbove / getDefaultRowHeight());
  2604. // leave one to ensure there is a buffer row to help with tab
  2605. // navigation
  2606. if (rowsToCoverTheExtra > 0) {
  2607. --rowsToCoverTheExtra;
  2608. }
  2609. /*
  2610. * Don't move more rows than there are to move, but also don't move
  2611. * more rows than should exist at the bottom. However, it's not
  2612. * possible to scroll down beyond available rows, so there is always
  2613. * at least one row to recycle.
  2614. */
  2615. int rowsToRecycle = Math.min(
  2616. Math.min(rowsToCoverTheExtra, visualRowOrder.size()),
  2617. getRowCount() - getTopRowLogicalIndex()
  2618. - visualRowOrder.size());
  2619. // are only some of the rows getting recycled instead of all
  2620. // of them
  2621. boolean partialMove = rowsToRecycle < visualRowOrder.size();
  2622. // calculate the logical index where the rows should be moved
  2623. int logicalTargetIndex;
  2624. if (partialMove) {
  2625. /*
  2626. * We scroll so little that we can just keep adding the rows
  2627. * immediately below the current escalator.
  2628. */
  2629. logicalTargetIndex = getTopRowLogicalIndex()
  2630. + visualRowOrder.size();
  2631. } else {
  2632. /*
  2633. * Since all escalator rows are getting recycled all spacers are
  2634. * going to get removed and the calculations have to ignore the
  2635. * spacers again in order to figure out which rows are to be
  2636. * displayed. In practice we may end up scrolling further down
  2637. * than the scroll position indicated initially as the spacers
  2638. * that get removed give room for more rows than expected.
  2639. *
  2640. * We can rely on calculations here because there won't be any
  2641. * old rows left to end up mismatched with.
  2642. */
  2643. logicalTargetIndex = (int) Math
  2644. .floor(scrollTop / getDefaultRowHeight());
  2645. /*
  2646. * Make sure we don't try to move rows below the actual row
  2647. * count, even if some of the rows end up hidden at the top as a
  2648. * result. This won't leave us with any old rows in any case,
  2649. * because we already checked earlier that there is room to
  2650. * recycle all the rows. It's only a question of how the new
  2651. * visual range gets positioned in relation to the viewport.
  2652. */
  2653. if (logicalTargetIndex
  2654. + visualRowOrder.size() > getRowCount()) {
  2655. logicalTargetIndex = getRowCount() - visualRowOrder.size();
  2656. }
  2657. }
  2658. /*
  2659. * Recycle the rows and move them to their new positions. Since we
  2660. * are moving the viewport downwards, the visual target index is
  2661. * always at the bottom and matches the length of the visual range.
  2662. * Note: Due to how moveAndUpdateEscalatorRows works, this will work
  2663. * out even if we move all the rows, and try to place them
  2664. * "at the end".
  2665. */
  2666. moveAndUpdateEscalatorRows(Range.between(0, rowsToRecycle),
  2667. visualRowOrder.size(), logicalTargetIndex);
  2668. // top row logical index needs to be updated differently
  2669. // depending on which update strategy was used, since the rows
  2670. // are being moved down
  2671. if (partialMove) {
  2672. // move down by the amount of recycled rows
  2673. updateTopRowLogicalIndex(rowsToRecycle);
  2674. } else {
  2675. // the insertion index is the new top row logical index
  2676. setTopRowLogicalIndex(logicalTargetIndex);
  2677. }
  2678. }
  2679. /**
  2680. * Calculates how much of the given range contains only rows with
  2681. * spacers excluded.
  2682. *
  2683. * @param y1
  2684. * start position
  2685. * @param y2
  2686. * end position
  2687. * @return position difference excluding any space taken up by spacers
  2688. */
  2689. private double getRowHeightsSumBetweenPxExcludingSpacers(double y1,
  2690. double y2) {
  2691. assert y1 < y2 : "y1 must be smaller than y2";
  2692. double viewportPx = y2 - y1;
  2693. double spacerPx = spacerContainer.getSpacerHeightsSumBetweenPx(y1,
  2694. SpacerInclusionStrategy.PARTIAL, y2,
  2695. SpacerInclusionStrategy.PARTIAL);
  2696. return viewportPx - spacerPx;
  2697. }
  2698. @Override
  2699. public void insertRows(int index, int numberOfRows) {
  2700. insertingOrRemoving = true;
  2701. super.insertRows(index, numberOfRows);
  2702. insertingOrRemoving = false;
  2703. if (heightMode == HeightMode.UNDEFINED) {
  2704. setHeightByRows(getRowCount());
  2705. }
  2706. }
  2707. @Override
  2708. public void removeRows(int index, int numberOfRows) {
  2709. insertingOrRemoving = true;
  2710. super.removeRows(index, numberOfRows);
  2711. insertingOrRemoving = false;
  2712. if (heightMode == HeightMode.UNDEFINED) {
  2713. setHeightByRows(getRowCount());
  2714. }
  2715. }
  2716. @Override
  2717. protected void paintInsertRows(final int index,
  2718. final int numberOfRows) {
  2719. assert index >= 0
  2720. && index < getRowCount() : "Attempting to insert a row "
  2721. + "outside of the available range.";
  2722. assert numberOfRows > 0 : "Attempting to insert a non-positive "
  2723. + "amount of rows, something must be wrong.";
  2724. if (numberOfRows <= 0) {
  2725. return;
  2726. }
  2727. /*
  2728. * NOTE: this method handles and manipulates logical, visual, and
  2729. * physical indexes a lot. If you don't remember what those mean and
  2730. * how they relate to each other, see the top of this class for
  2731. * Maintenance Notes.
  2732. *
  2733. * At the beginning of this method the logical index of the data
  2734. * provider has already been updated to include the new rows, but
  2735. * visual and physical indexes have not, nor has the spacer indexing
  2736. * been updated, and the topRowLogicalIndex may be out of date as
  2737. * well.
  2738. */
  2739. // top of visible area before any rows are actually added
  2740. double scrollTop = getScrollTop();
  2741. // logical index of the first row within the visual range before any
  2742. // rows are actually added
  2743. int oldTopRowLogicalIndex = getTopRowLogicalIndex();
  2744. // length of the visual range before any rows are actually added
  2745. int oldVisualRangeLength = visualRowOrder.size();
  2746. /*
  2747. * If there is room for more dom rows within the maximum visual
  2748. * range, add them. Calling this method repositions all the rows and
  2749. * spacers below the insertion point and updates the spacer indexes
  2750. * accordingly.
  2751. *
  2752. * TODO: Details rows should be added and populated here, since they
  2753. * have variable heights and affect the position calculations.
  2754. * Currently that's left to be triggered at the end and with a
  2755. * delay. If any new spacers exist, everything below them is going
  2756. * to be repositioned again for every spacer addition.
  2757. */
  2758. final List<TableRowElement> addedRows = fillAndPopulateEscalatorRowsIfNeeded(
  2759. index - oldTopRowLogicalIndex, index, numberOfRows);
  2760. // is the insertion point for new rows below visual range (viewport
  2761. // is irrelevant)
  2762. final boolean newRowsInsertedBelowVisualRange = index >= oldVisualRangeLength
  2763. + oldTopRowLogicalIndex;
  2764. // is the insertion point for new rows above initial visual range
  2765. final boolean newRowsInsertedAboveVisualRange = index <= oldTopRowLogicalIndex;
  2766. // is the insertion point for new rows above viewport
  2767. final boolean newRowsInsertedAboveCurrentViewport = getRowTop(
  2768. index) < scrollTop;
  2769. if (newRowsInsertedBelowVisualRange) {
  2770. /*
  2771. * There is no change to scroll position, and all other changes
  2772. * to positioning and indexing are out of visual range or
  2773. * already done (if addedRows is not empty).
  2774. */
  2775. } else if (newRowsInsertedAboveVisualRange && addedRows.isEmpty()
  2776. && newRowsInsertedAboveCurrentViewport) {
  2777. /*
  2778. * This section can only be reached if the insertion point is
  2779. * above the visual range, the visual range already covers a
  2780. * maximal amount of rows, and we are scrolled down enough that
  2781. * the top row is either partially or completely hidden. The
  2782. * last two points happen by default if the first row of the
  2783. * visual range has any other logical index than zero. Any other
  2784. * use cases involving the top row within the visual range need
  2785. * different handling.
  2786. */
  2787. paintInsertRowsAboveViewPort(index, numberOfRows,
  2788. oldTopRowLogicalIndex);
  2789. } else if (newRowsInsertedAboveCurrentViewport) {
  2790. /*
  2791. * Rows were inserted within the visual range but above the
  2792. * viewport. This includes the use case where the insertion
  2793. * point is just above the visual range and we are scrolled down
  2794. * a bit but the visual range doesn't have maximal amount of
  2795. * rows yet (can only happen with spacers in play), so more rows
  2796. * were added to the visual range but no rows need to be
  2797. * recycled.
  2798. */
  2799. paintInsertRowsWithinVisualRangeButAboveViewport(index,
  2800. numberOfRows, oldTopRowLogicalIndex, addedRows.size());
  2801. } else {
  2802. /*
  2803. * Rows added within visual range and either within or below the
  2804. * viewport. Recycled rows come from the END of the visual
  2805. * range.
  2806. */
  2807. paintInsertRowsWithinVisualRangeAndWithinOrBelowViewport(index,
  2808. numberOfRows, oldTopRowLogicalIndex, addedRows.size());
  2809. }
  2810. /*
  2811. * Calling insertRows will always change the number of rows - update
  2812. * the scrollbar sizes. This calculation isn't affected by actual
  2813. * dom rows amount or contents except for spacer heights. Spacers
  2814. * that don't fit the visual range are considered to have no height
  2815. * and might affect scrollbar calculations aversely, but that can't
  2816. * be avoided since they have unknown and variable heights.
  2817. */
  2818. scroller.recalculateScrollbarsForVirtualViewport();
  2819. }
  2820. /**
  2821. * Row insertion handling for {@link #paintInsertRows(int, int)} when
  2822. * the range will be inserted above the visual range.
  2823. * <p>
  2824. * NOTE: This method should not be called directly from anywhere else.
  2825. *
  2826. * @param index
  2827. * @param numberOfRows
  2828. * @param oldTopRowLogicalIndex
  2829. */
  2830. private void paintInsertRowsAboveViewPort(int index, int numberOfRows,
  2831. int oldTopRowLogicalIndex) {
  2832. /*
  2833. * Because there is no need to expand the visual range, no row or
  2834. * spacer contents get updated. All rows, spacers, and scroll
  2835. * position simply need to be shifted down accordingly and the
  2836. * spacer indexes need updating.
  2837. */
  2838. spacerContainer.updateSpacerIndexesForRowAndAfter(index,
  2839. oldTopRowLogicalIndex + visualRowOrder.size(),
  2840. numberOfRows);
  2841. // height of a single row
  2842. double defaultRowHeight = getDefaultRowHeight();
  2843. // height of new rows, out of visual range so spacers assumed to
  2844. // have no height
  2845. double newRowsHeight = numberOfRows * defaultRowHeight;
  2846. // update the positions
  2847. moveViewportAndContent(index, newRowsHeight, newRowsHeight,
  2848. newRowsHeight);
  2849. // top row logical index moves down by the number of new rows
  2850. updateTopRowLogicalIndex(numberOfRows);
  2851. }
  2852. /**
  2853. * Row insertion handling for {@link #paintInsertRows(int, int)} when
  2854. * the range will be inserted within the visual range above the
  2855. * viewport.
  2856. * <p>
  2857. * NOTE: This method should not be called directly from anywhere else.
  2858. *
  2859. * @param index
  2860. * @param numberOfRows
  2861. * @param oldTopRowLogicalIndex
  2862. * @param addedRowCount
  2863. */
  2864. private void paintInsertRowsWithinVisualRangeButAboveViewport(int index,
  2865. int numberOfRows, int oldTopRowLogicalIndex,
  2866. int addedRowCount) {
  2867. /*
  2868. * Unless we are scrolled all the way to the top the visual range is
  2869. * always out of view because we need a buffer row for tabulator
  2870. * navigation. Depending on the scroll position and spacers there
  2871. * might even be several rendered rows above the viewport,
  2872. * especially when we are scrolled all the way to the bottom.
  2873. *
  2874. * Even though the new rows will be initially out of view they still
  2875. * need to be correctly populated and positioned. Their contents
  2876. * won't be refreshed if they become visible later on (e.g. when a
  2877. * spacer gets hidden, which causes more rows to fit within the
  2878. * viewport) because they are expected to be already up to date.
  2879. *
  2880. * Note that it's not possible to insert content so that it's
  2881. * partially visible at the top. A partially visible row at top will
  2882. * still be the exact same partially visible row after the
  2883. * insertion, no matter which side of that row the new content gets
  2884. * inserted to. This section handles the use case where the new
  2885. * content is inserted above the partially visible row.
  2886. *
  2887. * Because the insertion point is out of view above the viewport,
  2888. * the only thing that should change for the end user visually is
  2889. * the scroll handle, which gets a new position and possibly turns a
  2890. * bit smaller if a lot of rows got inserted.
  2891. *
  2892. * From a technical point of view this also means that any rows that
  2893. * might need to get recycled should be taken from the BEGINNING of
  2894. * the visual range, above the insertion point. There might still be
  2895. * some "extra" rows below the viewport as well, but those should be
  2896. * left alone. They are going to be needed where they are if any
  2897. * spacers get closed or reduced in size.
  2898. *
  2899. * On a practical level we need to tweak the virtual viewport --
  2900. * scroll handle positions, row and spacer positions, and ensure the
  2901. * scroll area height is calculated correctly. Viewport should
  2902. * remain in a fixed position in relation to the existing rows and
  2903. * display no new rows. If any rows get recycled and have spacers
  2904. * either before or after the update the height of those spacers
  2905. * affects the position calculations.
  2906. *
  2907. * Insertion point can be anywhere from just before the previous
  2908. * first row of the visual range to just before the first actually
  2909. * visible row. The insertion shifts down the content below
  2910. * insertion point, which excludes any dom rows that remain above
  2911. * the insertion point after recycling is finished. After the rows
  2912. * below insertion point have been moved the viewport needs to be
  2913. * shifted down a similar amount to regain its old relative position
  2914. * again.
  2915. *
  2916. * The visual range only ever contains at most as many rows as would
  2917. * fit within the viewport without any spacers with one extra row on
  2918. * both at the top and at the bottom as buffer rows, so the amount
  2919. * of rows that needs to be checked is always reasonably limited.
  2920. */
  2921. // insertion index within the visual range
  2922. int visualTargetIndex = index - oldTopRowLogicalIndex;
  2923. // how many dom rows before insertion point versus how many new
  2924. // rows didn't get their own dom rows -- smaller amount
  2925. // determines how many rows can and need to be recycled
  2926. int rowsToUpdate = Math.min(visualTargetIndex,
  2927. numberOfRows - addedRowCount);
  2928. // height of a single row
  2929. double defaultRowHeight = getDefaultRowHeight();
  2930. boolean rowVisibilityChanged = false;
  2931. if (rowsToUpdate > 0) {
  2932. // recycle the rows and update the positions, adjust
  2933. // logical index for inserted rows that won't fit within
  2934. // visual range
  2935. int logicalIndex = index + numberOfRows - rowsToUpdate;
  2936. if (visualTargetIndex > 0) {
  2937. // move after any added dom rows
  2938. moveAndUpdateEscalatorRows(Range.between(0, rowsToUpdate),
  2939. visualTargetIndex + addedRowCount, logicalIndex);
  2940. } else {
  2941. // move before any added dom rows
  2942. moveAndUpdateEscalatorRows(Range.between(0, rowsToUpdate),
  2943. visualTargetIndex, logicalIndex);
  2944. }
  2945. // adjust viewport down to maintain the initial position
  2946. double newRowsHeight = numberOfRows * defaultRowHeight;
  2947. double newSpacerHeights = spacerContainer
  2948. .getSpacerHeightsSumUntilIndex(
  2949. logicalIndex + rowsToUpdate)
  2950. - spacerContainer.getSpacerHeightsSumUntilIndex(index);
  2951. /*
  2952. * FIXME: spacers haven't been added yet and they can cause
  2953. * escalator contents to shift after the fact in a way that
  2954. * can't be countered for here.
  2955. *
  2956. * FIXME: verticalScrollbar internal state causes this update to
  2957. * fail partially and the next attempt at scrolling causes
  2958. * things to jump.
  2959. *
  2960. * Couldn't find a quick fix to either problem and this use case
  2961. * is somewhat marginal so left them here for now.
  2962. */
  2963. moveViewportAndContent(null, 0, 0,
  2964. newSpacerHeights + newRowsHeight);
  2965. rowVisibilityChanged = true;
  2966. } else {
  2967. // no rows to recycle but update the spacer indexes
  2968. spacerContainer.updateSpacerIndexesForRowAndAfter(index,
  2969. index + numberOfRows - addedRowCount,
  2970. numberOfRows - addedRowCount);
  2971. double newRowsHeight = numberOfRows * defaultRowHeight;
  2972. if (addedRowCount > 0) {
  2973. // update the viewport, rows and spacers were
  2974. // repositioned already by the method for adding dom
  2975. // rows
  2976. moveViewportAndContent(null, 0, 0, newRowsHeight);
  2977. rowVisibilityChanged = true;
  2978. } else {
  2979. // all changes are actually above the viewport after
  2980. // all, update all positions
  2981. moveViewportAndContent(index, newRowsHeight, newRowsHeight,
  2982. newRowsHeight);
  2983. }
  2984. }
  2985. if (numberOfRows > addedRowCount) {
  2986. /*
  2987. * If there are more new rows than how many new dom rows got
  2988. * added, the top row logical index necessarily gets shifted
  2989. * down by that difference because recycling doesn't replace any
  2990. * logical rows, just shifts them off the visual range, and the
  2991. * inserted rows that don't fit to the visual range also push
  2992. * the other rows down. If every new row got new dom rows as
  2993. * well the top row logical index doesn't change, because the
  2994. * insertion point was within the visual range.
  2995. */
  2996. updateTopRowLogicalIndex(numberOfRows - addedRowCount);
  2997. }
  2998. if (rowVisibilityChanged) {
  2999. fireRowVisibilityChangeEvent();
  3000. }
  3001. if (rowsToUpdate > 0) {
  3002. // update the physical index
  3003. sortDomElements();
  3004. }
  3005. }
  3006. /**
  3007. * Row insertion handling for {@link #paintInsertRows(int, int)} when
  3008. * the range will be inserted within the visual range either within or
  3009. * below the viewport.
  3010. * <p>
  3011. * NOTE: This method should not be called directly from anywhere else.
  3012. *
  3013. * @param index
  3014. * @param numberOfRows
  3015. * @param oldTopRowLogicalIndex
  3016. * @param addedRowCount
  3017. */
  3018. private void paintInsertRowsWithinVisualRangeAndWithinOrBelowViewport(
  3019. int index, int numberOfRows, int oldTopRowLogicalIndex,
  3020. int addedRowCount) {
  3021. // insertion index within the visual range
  3022. int visualIndex = index - oldTopRowLogicalIndex;
  3023. // how many dom rows after insertion point versus how many new
  3024. // rows to add -- smaller amount determines how many rows can or
  3025. // need to be recycled, excluding the rows that already got new
  3026. // dom rows
  3027. int rowsToUpdate = Math.max(
  3028. Math.min(visualRowOrder.size() - visualIndex, numberOfRows)
  3029. - addedRowCount,
  3030. 0);
  3031. if (rowsToUpdate > 0) {
  3032. moveAndUpdateEscalatorRows(
  3033. Range.between(visualRowOrder.size() - rowsToUpdate,
  3034. visualRowOrder.size()),
  3035. visualIndex + addedRowCount, index + addedRowCount);
  3036. fireRowVisibilityChangeEvent();
  3037. // update the physical index
  3038. sortDomElements();
  3039. }
  3040. }
  3041. /**
  3042. * Move escalator rows around, and make sure everything gets
  3043. * appropriately repositioned and repainted. In the case of insertion or
  3044. * removal, following spacer indexes get updated as well.
  3045. *
  3046. * @param visualSourceRange
  3047. * the range of rows to move to a new place
  3048. * @param visualTargetIndex
  3049. * the visual index where the rows will be placed to
  3050. * @param logicalTargetIndex
  3051. * the logical index to be assigned to the first moved row
  3052. */
  3053. private void moveAndUpdateEscalatorRows(final Range visualSourceRange,
  3054. final int visualTargetIndex, final int logicalTargetIndex)
  3055. throws IllegalArgumentException {
  3056. if (visualSourceRange.isEmpty()) {
  3057. return;
  3058. }
  3059. int sourceRangeLength = visualSourceRange.length();
  3060. int domRowCount = getDomRowCount();
  3061. int rowCount = getRowCount();
  3062. assert visualSourceRange.getStart() >= 0 : "Visual source start "
  3063. + "must be 0 or greater (was "
  3064. + visualSourceRange.getStart() + ")";
  3065. assert logicalTargetIndex >= 0 : "Logical target must be 0 or "
  3066. + "greater (was " + logicalTargetIndex + ")";
  3067. assert visualTargetIndex >= 0 : "Visual target must be 0 or greater (was "
  3068. + visualTargetIndex + ")";
  3069. assert visualTargetIndex <= domRowCount : "Visual target "
  3070. + "must not be greater than the number of escalator rows (was "
  3071. + visualTargetIndex + ", escalator rows " + domRowCount
  3072. + ")";
  3073. assert logicalTargetIndex
  3074. + sourceRangeLength <= rowCount : "Logical "
  3075. + "target leads to rows outside of the data range ("
  3076. + Range.withLength(logicalTargetIndex,
  3077. sourceRangeLength)
  3078. + " goes beyond " + Range.withLength(0, rowCount)
  3079. + ")";
  3080. /*
  3081. * Since we move a range into another range, the indices might move
  3082. * about. Having 10 rows, if we move 0..1 to index 10 (to the end of
  3083. * the collection), the target range will end up being 8..9, instead
  3084. * of 10..11.
  3085. *
  3086. * This applies only if we move elements forward in the collection,
  3087. * not backward.
  3088. */
  3089. final int adjustedVisualTargetIndex;
  3090. if (visualSourceRange.getStart() < visualTargetIndex) {
  3091. adjustedVisualTargetIndex = visualTargetIndex
  3092. - sourceRangeLength;
  3093. } else {
  3094. adjustedVisualTargetIndex = visualTargetIndex;
  3095. }
  3096. int oldTopRowLogicalIndex = getTopRowLogicalIndex();
  3097. // first moved row's logical index before move
  3098. int oldSourceRangeLogicalStart = oldTopRowLogicalIndex
  3099. + visualSourceRange.getStart();
  3100. // new top row logical index
  3101. int newTopRowLogicalIndex = logicalTargetIndex
  3102. - adjustedVisualTargetIndex;
  3103. // variables for update types that require special handling
  3104. boolean recycledToTop = logicalTargetIndex < oldTopRowLogicalIndex;
  3105. boolean recycledFromTop = visualSourceRange.getStart() == 0;
  3106. boolean scrollingUp = recycledToTop
  3107. && visualSourceRange.getEnd() == visualRowOrder.size();
  3108. boolean scrollingDown = recycledFromTop
  3109. && logicalTargetIndex >= oldTopRowLogicalIndex
  3110. + visualRowOrder.size();
  3111. if (visualSourceRange.getStart() != adjustedVisualTargetIndex) {
  3112. /*
  3113. * Reorder the rows to their correct places within
  3114. * visualRowOrder (unless rows are moved back to their original
  3115. * places)
  3116. */
  3117. /*
  3118. * TODO [[optimize]]: move whichever set is smaller: the ones
  3119. * explicitly moved, or the others. So, with 10 escalator rows,
  3120. * if we are asked to move idx[0..8] to the end of the list,
  3121. * it's faster to just move idx[9] to the beginning.
  3122. */
  3123. final List<TableRowElement> removedRows = new ArrayList<>(
  3124. sourceRangeLength);
  3125. for (int i = 0; i < sourceRangeLength; i++) {
  3126. final TableRowElement tr = visualRowOrder
  3127. .remove(visualSourceRange.getStart());
  3128. removedRows.add(tr);
  3129. }
  3130. visualRowOrder.addAll(adjustedVisualTargetIndex, removedRows);
  3131. }
  3132. // refresh contents of rows to be recycled, returns the combined
  3133. // height of the spacers that got removed from visual range
  3134. double spacerHeightsOfRecycledRowsBefore = refreshRecycledRowContents(
  3135. logicalTargetIndex, adjustedVisualTargetIndex,
  3136. sourceRangeLength, oldSourceRangeLogicalStart);
  3137. boolean movedDown = adjustedVisualTargetIndex != visualTargetIndex;
  3138. boolean recycledToOrFromTop = recycledToTop || recycledFromTop;
  3139. // update spacer indexes unless we are scrolling -- with scrolling
  3140. // the remaining spacers are where they belong, the recycled ones
  3141. // were already removed, and new ones will be added with delay
  3142. if (!(scrollingUp || scrollingDown)) {
  3143. if (recycledToOrFromTop) {
  3144. updateSpacerIndexesForMoveWhenRecycledToOrFromTop(
  3145. oldSourceRangeLogicalStart, sourceRangeLength,
  3146. oldTopRowLogicalIndex, newTopRowLogicalIndex,
  3147. recycledFromTop);
  3148. } else {
  3149. updateSpacerIndexesForMoveWhenNotRecycledToOrFromTop(
  3150. logicalTargetIndex, oldSourceRangeLogicalStart,
  3151. sourceRangeLength, movedDown);
  3152. }
  3153. }
  3154. // Would be useful if new spacer heights could be determined
  3155. // here already but their contents are populated with delay.
  3156. // If the heights ever become available immediately, the
  3157. // handling that follows needs to be updated to take the new
  3158. // spacer heights into account.
  3159. repositionMovedRows(adjustedVisualTargetIndex, sourceRangeLength,
  3160. newTopRowLogicalIndex);
  3161. // variables for reducing the amount of necessary parameters
  3162. boolean scrollingDownAndNoSpacersRemoved = scrollingDown
  3163. && spacerHeightsOfRecycledRowsBefore <= 0d;
  3164. boolean spacerHeightsChanged = spacerHeightsOfRecycledRowsBefore > 0d;
  3165. repositionRowsShiftedByTheMove(visualSourceRange, visualTargetIndex,
  3166. adjustedVisualTargetIndex, newTopRowLogicalIndex,
  3167. scrollingDownAndNoSpacersRemoved, scrollingUp,
  3168. recycledToTop);
  3169. repositionRowsBelowMovedAndShiftedIfNeeded(visualSourceRange,
  3170. visualTargetIndex, adjustedVisualTargetIndex,
  3171. newTopRowLogicalIndex, (scrollingUp || scrollingDown),
  3172. recycledToOrFromTop, spacerHeightsChanged);
  3173. }
  3174. /**
  3175. * Refresh the contents of the affected rows for
  3176. * {@link #moveAndUpdateEscalatorRows(Range, int, int)}
  3177. * <p>
  3178. * NOTE: This method should not be called directly from anywhere else.
  3179. *
  3180. * @param logicalTargetIndex
  3181. * @param adjustedVisualTargetIndex
  3182. * @param sourceRangeLength
  3183. * @param spacerHeightsBeforeMoveTotal
  3184. * @param oldSourceRangeLogicalStart
  3185. * @return the combined height of any removed spacers
  3186. */
  3187. private double refreshRecycledRowContents(int logicalTargetIndex,
  3188. int adjustedVisualTargetIndex, int sourceRangeLength,
  3189. int oldSourceRangeLogicalStart) {
  3190. final ListIterator<TableRowElement> iter = visualRowOrder
  3191. .listIterator(adjustedVisualTargetIndex);
  3192. double removedSpacerHeights = 0d;
  3193. for (int i = 0; i < sourceRangeLength; ++i) {
  3194. final TableRowElement tr = iter.next();
  3195. int logicalIndex = logicalTargetIndex + i;
  3196. // clear old spacer
  3197. SpacerContainer.SpacerImpl spacer = spacerContainer
  3198. .getSpacer(oldSourceRangeLogicalStart + i);
  3199. if (spacer != null) {
  3200. double spacerHeight = spacer.getHeight();
  3201. removedSpacerHeights += spacerHeight;
  3202. spacerContainer
  3203. .removeSpacer(oldSourceRangeLogicalStart + i);
  3204. }
  3205. refreshRow(tr, logicalIndex);
  3206. }
  3207. return removedSpacerHeights;
  3208. }
  3209. /**
  3210. * Update the spacer indexes to correspond with logical indexes for
  3211. * {@link #moveAndUpdateEscalatorRows(Range, int, int)} when the move
  3212. * recycles rows to or from top
  3213. * <p>
  3214. * NOTE: This method should not be called directly from anywhere else.
  3215. *
  3216. * @param oldSourceRangeLogicalStart
  3217. * @param sourceRangeLength
  3218. * @param oldTopRowLogicalIndex
  3219. * @param newTopRowLogicalIndex
  3220. * @param recycledFromTop
  3221. */
  3222. private void updateSpacerIndexesForMoveWhenRecycledToOrFromTop(
  3223. int oldSourceRangeLogicalStart, int sourceRangeLength,
  3224. int oldTopRowLogicalIndex, int newTopRowLogicalIndex,
  3225. boolean recycledFromTop) {
  3226. if (recycledFromTop) {
  3227. // first rows are getting recycled thanks to insertion or
  3228. // removal, all the indexes below need to be updated
  3229. // accordingly
  3230. int indexesToShift;
  3231. if (newTopRowLogicalIndex != oldTopRowLogicalIndex) {
  3232. indexesToShift = newTopRowLogicalIndex
  3233. - oldTopRowLogicalIndex;
  3234. } else {
  3235. indexesToShift = -sourceRangeLength;
  3236. }
  3237. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3238. oldSourceRangeLogicalStart + sourceRangeLength,
  3239. oldTopRowLogicalIndex + visualRowOrder.size(),
  3240. indexesToShift);
  3241. } else {
  3242. // rows recycled to the top, move the remaining spacer
  3243. // indexes up
  3244. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3245. oldSourceRangeLogicalStart + sourceRangeLength,
  3246. getRowCount() + sourceRangeLength, -sourceRangeLength);
  3247. }
  3248. }
  3249. /**
  3250. * Update the spacer indexes to correspond with logical indexes for
  3251. * {@link #moveAndUpdateEscalatorRows(Range, int, int)} when the move
  3252. * does not recycle rows to or from top
  3253. * <p>
  3254. * NOTE: This method should not be called directly from anywhere else.
  3255. *
  3256. * @param logicalTargetIndex
  3257. * @param oldSourceRangeLogicalStart
  3258. * @param sourceRangeLength
  3259. * @param movedDown
  3260. */
  3261. private void updateSpacerIndexesForMoveWhenNotRecycledToOrFromTop(
  3262. int logicalTargetIndex, int oldSourceRangeLogicalStart,
  3263. int sourceRangeLength, boolean movedDown) {
  3264. if (movedDown) {
  3265. // move the shifted spacer indexes up to fill the freed
  3266. // space
  3267. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3268. oldSourceRangeLogicalStart + sourceRangeLength,
  3269. logicalTargetIndex + sourceRangeLength,
  3270. -sourceRangeLength);
  3271. } else {
  3272. // move the shifted spacer indexes down to fill the freed
  3273. // space
  3274. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3275. logicalTargetIndex, oldSourceRangeLogicalStart,
  3276. sourceRangeLength);
  3277. }
  3278. }
  3279. /**
  3280. * Reposition the rows that were moved for
  3281. * {@link #moveAndUpdateEscalatorRows(Range, int, int)}
  3282. * <p>
  3283. * NOTE: This method should not be called directly from anywhere else.
  3284. *
  3285. * @param adjustedVisualTargetIndex
  3286. * @param sourceRangeLength
  3287. * @param newTopRowLogicalIndex
  3288. */
  3289. private void repositionMovedRows(int adjustedVisualTargetIndex,
  3290. int sourceRangeLength, int newTopRowLogicalIndex) {
  3291. int start = adjustedVisualTargetIndex;
  3292. updateRowPositions(newTopRowLogicalIndex + start, start,
  3293. sourceRangeLength);
  3294. }
  3295. /**
  3296. * Reposition the rows that were shifted by the move for
  3297. * {@link #moveAndUpdateEscalatorRows(Range, int, int)}
  3298. * <p>
  3299. * NOTE: This method should not be called directly from anywhere else.
  3300. *
  3301. * @param visualSourceRange
  3302. * @param visualTargetIndex
  3303. * @param adjustedVisualTargetIndex
  3304. * @param newTopRowLogicalIndex
  3305. * @param scrollingDownAndNoSpacersRemoved
  3306. * @param scrollingUp
  3307. * @param recycledToTop
  3308. */
  3309. private void repositionRowsShiftedByTheMove(Range visualSourceRange,
  3310. int visualTargetIndex, int adjustedVisualTargetIndex,
  3311. int newTopRowLogicalIndex,
  3312. boolean scrollingDownAndNoSpacersRemoved, boolean scrollingUp,
  3313. boolean recycledToTop) {
  3314. if (visualSourceRange.length() == visualRowOrder.size()) {
  3315. // all rows got updated and were repositioned already
  3316. return;
  3317. }
  3318. if (scrollingDownAndNoSpacersRemoved || scrollingUp) {
  3319. // scrolling, no spacers got removed from or added above any
  3320. // remaining rows so everything is where it belongs already
  3321. // (there is no check for added spacers because adding happens
  3322. // with delay, whether any spacers are coming or not they don't
  3323. // exist yet and thus can't be taken into account here)
  3324. return;
  3325. }
  3326. if (adjustedVisualTargetIndex != visualTargetIndex) {
  3327. // rows moved down, shifted rows need to be moved up
  3328. int start = visualSourceRange.getStart();
  3329. updateRowPositions(newTopRowLogicalIndex + start, start,
  3330. adjustedVisualTargetIndex - start);
  3331. } else {
  3332. // rows moved up, shifted rows need to be repositioned
  3333. // unless it's just a recycling and no spacer heights
  3334. // above got updated
  3335. if (recycledToTop) {
  3336. // rows below the shifted ones need to be moved up (which is
  3337. // done in the next helper method) but the shifted rows
  3338. // themselves are already where they belong
  3339. // (this should only be done if no spacers were added, but
  3340. // we can't know that yet so we'll have to adjust for them
  3341. // afterwards if any do appear)
  3342. return;
  3343. }
  3344. int start = adjustedVisualTargetIndex
  3345. + visualSourceRange.length();
  3346. updateRowPositions(newTopRowLogicalIndex + start, start,
  3347. visualSourceRange.getEnd() - start);
  3348. }
  3349. }
  3350. /**
  3351. * If necessary, reposition the rows that are below those rows that got
  3352. * moved or shifted for
  3353. * {@link #moveAndUpdateEscalatorRows(Range, int, int)}
  3354. * <p>
  3355. * NOTE: This method should not be called directly from anywhere else.
  3356. *
  3357. * @param visualSourceRange
  3358. * @param visualTargetIndex
  3359. * @param adjustedVisualTargetIndex
  3360. * @param newTopRowLogicalIndex
  3361. * @param scrolling
  3362. * @param recycledToOrFromTop
  3363. * @param spacerHeightsChanged
  3364. */
  3365. private void repositionRowsBelowMovedAndShiftedIfNeeded(
  3366. Range visualSourceRange, int visualTargetIndex,
  3367. int adjustedVisualTargetIndex, int newTopRowLogicalIndex,
  3368. boolean scrolling, boolean recycledToOrFromTop,
  3369. boolean spacerHeightsChanged) {
  3370. /*
  3371. * There is no need to check if any rows preceding the source and
  3372. * target range need their positions adjusted, but rows below both
  3373. * may very well need it if spacer heights changed or rows got
  3374. * inserted or removed instead of just moved around.
  3375. *
  3376. * When scrolling to either direction all the rows already got
  3377. * processed by earlier stages, there are no unprocessed rows left
  3378. * either above or below.
  3379. */
  3380. if (!scrolling && (recycledToOrFromTop || spacerHeightsChanged)) {
  3381. int firstBelow;
  3382. if (adjustedVisualTargetIndex != visualTargetIndex) {
  3383. // rows moved down
  3384. firstBelow = adjustedVisualTargetIndex
  3385. + visualSourceRange.length();
  3386. } else {
  3387. // rows moved up
  3388. firstBelow = visualSourceRange.getEnd();
  3389. }
  3390. updateRowPositions(newTopRowLogicalIndex + firstBelow,
  3391. firstBelow, visualRowOrder.size() - firstBelow);
  3392. }
  3393. }
  3394. @Override
  3395. public void updateRowPositions(int index, int numberOfRows) {
  3396. Range visibleRowRange = getVisibleRowRange();
  3397. Range rangeToUpdate = Range.withLength(index, numberOfRows);
  3398. Range intersectingRange = visibleRowRange
  3399. .partitionWith(rangeToUpdate)[1];
  3400. if (intersectingRange.isEmpty()) {
  3401. // no overlap with the visual range, ignore the positioning
  3402. return;
  3403. }
  3404. int adjustedIndex = intersectingRange.getStart();
  3405. int adjustedVisualIndex = adjustedIndex - getTopRowLogicalIndex();
  3406. updateRowPositions(adjustedIndex, adjustedVisualIndex,
  3407. intersectingRange.length());
  3408. // make sure there is no unnecessary gap
  3409. adjustScrollPositionIfNeeded();
  3410. scroller.recalculateScrollbarsForVirtualViewport();
  3411. }
  3412. /**
  3413. * Re-calculates and updates the positions of rows and spacers within
  3414. * the given range. Doesn't touch the scroll positions.
  3415. *
  3416. * @param logicalIndex
  3417. * logical index of the first row to reposition
  3418. * @param visualIndex
  3419. * visual index of the first row to reposition
  3420. * @param numberOfRows
  3421. * the number of rows to reposition
  3422. */
  3423. private void updateRowPositions(int logicalIndex, int visualIndex,
  3424. int numberOfRows) {
  3425. double newRowTop = getRowTop(logicalIndex);
  3426. for (int i = 0; i < numberOfRows; ++i) {
  3427. TableRowElement tr = visualRowOrder.get(visualIndex + i);
  3428. setRowPosition(tr, 0, newRowTop);
  3429. newRowTop += getDefaultRowHeight();
  3430. SpacerContainer.SpacerImpl spacer = spacerContainer
  3431. .getSpacer(logicalIndex + i);
  3432. if (spacer != null) {
  3433. spacer.setPosition(0, newRowTop);
  3434. newRowTop += spacer.getHeight();
  3435. }
  3436. }
  3437. }
  3438. /**
  3439. * Checks whether there is an unexpected gap below the visible rows and
  3440. * adjusts the viewport if necessary.
  3441. */
  3442. private void adjustScrollPositionIfNeeded() {
  3443. double scrollTop = getScrollTop();
  3444. int firstBelowVisualRange = getTopRowLogicalIndex()
  3445. + visualRowOrder.size();
  3446. double gapBelow = scrollTop + getHeightOfSection()
  3447. - getRowTop(firstBelowVisualRange);
  3448. boolean bufferRowNeeded = gapBelow == 0
  3449. && firstBelowVisualRange < getRowCount();
  3450. if (scrollTop > 0 && (gapBelow > 0 || bufferRowNeeded)) {
  3451. /*
  3452. * This situation can be reached e.g. by removing a spacer.
  3453. * Scroll position must be adjusted accordingly but no more than
  3454. * there is room to scroll up. If a buffer row is needed make
  3455. * sure the last row ends up at least slightly below the
  3456. * viewport.
  3457. */
  3458. double adjustedGap = Math.max(gapBelow,
  3459. bufferRowNeeded ? 1 : 0);
  3460. double yDeltaScroll = Math.min(adjustedGap, scrollTop);
  3461. moveViewportAndContent(null, 0, 0, -yDeltaScroll);
  3462. }
  3463. }
  3464. /**
  3465. * Adjust the scroll position and move the contained rows.
  3466. * <p>
  3467. * The difference between using this method and simply scrolling is that
  3468. * this method "takes the rows and spacers with it" and renders them
  3469. * appropriately. The viewport may be scrolled any arbitrary amount, and
  3470. * the contents are moved appropriately, but always snapped into a
  3471. * plausible place.
  3472. * <p>
  3473. * <dl>
  3474. * <dt>Example 1</dt>
  3475. * <dd>An Escalator with default row height 20px. Adjusting the scroll
  3476. * position with 7.5px will move the viewport 7.5px down, but leave the
  3477. * row where it is.</dd>
  3478. * <dt>Example 2</dt>
  3479. * <dd>An Escalator with default row height 20px. Adjusting the scroll
  3480. * position with 27.5px will move the viewport 27.5px down, and place
  3481. * the row at 20px.</dd>
  3482. * </dl>
  3483. *
  3484. * @deprecated This method isn't used by Escalator anymore since Vaadin
  3485. * 8.9 and the general row handling logic has been
  3486. * rewritten, so attempting to call this method may lead to
  3487. * unexpected consequences. This method is likely to get
  3488. * removed soon.
  3489. * @param yDelta
  3490. * the delta of pixels by which to move the viewport and
  3491. * content. A positive value moves everything downwards,
  3492. * while a negative value moves everything upwards
  3493. */
  3494. @Deprecated
  3495. public void moveViewportAndContent(final double yDelta) {
  3496. if (yDelta == 0) {
  3497. return;
  3498. }
  3499. double newTop = tBodyScrollTop + yDelta;
  3500. verticalScrollbar.setScrollPos(newTop);
  3501. final double defaultRowHeight = getDefaultRowHeight();
  3502. double rowPxDelta = yDelta - (yDelta % defaultRowHeight);
  3503. int rowIndexDelta = (int) (yDelta / defaultRowHeight);
  3504. if (!WidgetUtil.pixelValuesEqual(rowPxDelta, 0)) {
  3505. Collection<SpacerContainer.SpacerImpl> spacers = spacerContainer
  3506. .getSpacersAfterPx(tBodyScrollTop,
  3507. SpacerInclusionStrategy.PARTIAL);
  3508. for (SpacerContainer.SpacerImpl spacer : spacers) {
  3509. spacer.setPositionDiff(0, rowPxDelta);
  3510. spacer.setRowIndex(spacer.getRow() + rowIndexDelta);
  3511. }
  3512. for (TableRowElement tr : visualRowOrder) {
  3513. setRowPosition(tr, 0, getRowTop(tr) + rowPxDelta);
  3514. }
  3515. }
  3516. setBodyScrollPosition(tBodyScrollLeft, newTop);
  3517. }
  3518. /**
  3519. * Move rows, spacers, and/or viewport up or down. For rows and spacers
  3520. * either everything within visual range is affected (index
  3521. * {@code null}) or only those from the given row index forward.
  3522. * <p>
  3523. * This method does not update spacer indexes.
  3524. *
  3525. * @param index
  3526. * the logical index from which forward the rows and spacers
  3527. * should be updated, or {@code null} if all of them
  3528. * @param yDeltaRows
  3529. * how much rows should be shifted in pixels
  3530. * @param yDeltaSpacers
  3531. * how much spacers should be shifted in pixels
  3532. * @param yDeltaScroll
  3533. * how much scroll position should be shifted in pixels
  3534. */
  3535. private void moveViewportAndContent(Integer index,
  3536. final double yDeltaRows, final double yDeltaSpacers,
  3537. final double yDeltaScroll) {
  3538. if (!WidgetUtil.pixelValuesEqual(yDeltaScroll, 0d)) {
  3539. double newTop = tBodyScrollTop + yDeltaScroll;
  3540. verticalScrollbar.setScrollPos(newTop);
  3541. setBodyScrollPosition(tBodyScrollLeft, newTop);
  3542. }
  3543. if (!WidgetUtil.pixelValuesEqual(yDeltaSpacers, 0d)) {
  3544. Collection<SpacerContainer.SpacerImpl> spacers;
  3545. if (index == null) {
  3546. spacers = spacerContainer.getSpacersAfterPx(tBodyScrollTop,
  3547. SpacerInclusionStrategy.PARTIAL);
  3548. } else {
  3549. spacers = spacerContainer.getSpacersForRowAndAfter(index);
  3550. }
  3551. for (SpacerContainer.SpacerImpl spacer : spacers) {
  3552. spacer.setPositionDiff(0, yDeltaSpacers);
  3553. }
  3554. }
  3555. if (!WidgetUtil.pixelValuesEqual(yDeltaRows, 0d)) {
  3556. if (index == null) {
  3557. // move all visible rows to the desired direction
  3558. for (TableRowElement tr : visualRowOrder) {
  3559. setRowPosition(tr, 0, getRowTop(tr) + yDeltaRows);
  3560. }
  3561. } else {
  3562. // move all visible rows, including the index row, to the
  3563. // desired direction
  3564. shiftRowPositions(index - 1, yDeltaRows);
  3565. }
  3566. }
  3567. }
  3568. /**
  3569. * Adds new physical escalator rows to the DOM at the given visual index
  3570. * if there's still a need for more escalator rows.
  3571. * <p>
  3572. * If Escalator already is at (or beyond) max capacity, this method does
  3573. * nothing to the DOM.
  3574. * <p>
  3575. * Calling this method repositions all the rows and spacers below the
  3576. * insertion point.
  3577. *
  3578. * @param visualIndex
  3579. * the index at which to add new escalator rows to DOM
  3580. * @param logicalIndex
  3581. * the logical index that corresponds with the first new
  3582. * escalator row, should usually be the same as visual index
  3583. * because there is still need for new rows, but this is not
  3584. * always the case e.g. if row height is changed
  3585. * @param numberOfRows
  3586. * the number of rows to add at <code>index</code>
  3587. * @return a list of the added rows
  3588. */
  3589. private List<TableRowElement> fillAndPopulateEscalatorRowsIfNeeded(
  3590. final int visualIndex, final int logicalIndex,
  3591. final int numberOfRows) {
  3592. /*
  3593. * We want to maintain enough rows to fill the entire viewport even
  3594. * if their spacers have no height. If their spacers do have height
  3595. * some of these rows may end up outside of the viewport, but that's
  3596. * ok.
  3597. */
  3598. final int escalatorRowsStillFit = getMaxVisibleRowCount()
  3599. - getDomRowCount();
  3600. final int escalatorRowsNeeded = Math.min(numberOfRows,
  3601. escalatorRowsStillFit);
  3602. if (escalatorRowsNeeded > 0) {
  3603. int rowsBeforeAddition = visualRowOrder.size();
  3604. // this is AbstractRowContainer method and not easily overridden
  3605. // to consider logical indexes separately from visual indexes,
  3606. // so as a workaround we create the rows as if those two were
  3607. // the same and then update the contents if needed
  3608. final List<TableRowElement> addedRows = paintInsertStaticRows(
  3609. visualIndex, escalatorRowsNeeded);
  3610. visualRowOrder.addAll(visualIndex, addedRows);
  3611. if (visualIndex != logicalIndex) {
  3612. // row got populated with wrong contents, need to update
  3613. int adjustedLogicalIndex = 0;
  3614. if (visualIndex == 0) {
  3615. // added to the beginning of visual range, use the
  3616. // end of insertion range because the beginning might
  3617. // not fit completely
  3618. adjustedLogicalIndex = logicalIndex + numberOfRows
  3619. - addedRows.size();
  3620. } else {
  3621. // added anywhere else, use the beginning of
  3622. // insertion range and the rest of the rows get
  3623. // recycled below if there is room for them
  3624. adjustedLogicalIndex = logicalIndex;
  3625. }
  3626. for (int i = 0; i < addedRows.size(); ++i) {
  3627. TableRowElement tr = addedRows.get(i);
  3628. refreshRow(tr, adjustedLogicalIndex + i);
  3629. }
  3630. }
  3631. // if something is getting inserted instead of just being
  3632. // brought to visual range, the rows below the insertion point
  3633. // need to have their spacer indexes updated accordingly
  3634. if (logicalIndex >= getTopRowLogicalIndex()
  3635. && visualIndex < rowsBeforeAddition) {
  3636. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3637. logicalIndex, getRowCount(), addedRows.size());
  3638. }
  3639. // update the positions of the added rows and the rows below
  3640. // them
  3641. // TODO: this can lead to moving things around twice in case
  3642. // some rows didn't get new dom rows (e.g. when expanding a
  3643. // TreeGrid node with more children than can fit within the max
  3644. // visual range size), consider moving this update elsewhere
  3645. double rowTop = getRowTop(logicalIndex);
  3646. for (int i = visualIndex; i < visualRowOrder.size(); i++) {
  3647. final TableRowElement tr = visualRowOrder.get(i);
  3648. setRowPosition(tr, 0, rowTop);
  3649. rowTop += getDefaultRowHeight();
  3650. SpacerContainer.SpacerImpl spacer = spacerContainer
  3651. .getSpacer(logicalIndex - visualIndex + i);
  3652. if (spacer != null) {
  3653. spacer.setPosition(0, rowTop);
  3654. rowTop += spacer.getHeight();
  3655. }
  3656. }
  3657. // Execute the registered callback function for newly created
  3658. // rows
  3659. Optional.ofNullable(newEscalatorRowCallback)
  3660. .ifPresent(callback -> callback.accept(addedRows));
  3661. return addedRows;
  3662. } else {
  3663. return Collections.emptyList();
  3664. }
  3665. }
  3666. private int getMaxVisibleRowCount() {
  3667. double heightOfSection = getHeightOfSection();
  3668. // By including the possibly shown scrollbar height, we get a
  3669. // consistent count and do not add/remove rows whenever a scrollbar
  3670. // is shown. Make sure that two extra rows are included for
  3671. // assisting with tab navigation on both sides of the viewport.
  3672. heightOfSection += horizontalScrollbarDeco.getOffsetHeight();
  3673. double defaultRowHeight = getDefaultRowHeight();
  3674. final int maxVisibleRowCount = (int) Math
  3675. .ceil(heightOfSection / defaultRowHeight) + 2;
  3676. /*
  3677. * maxVisibleRowCount can become negative if the headers and footers
  3678. * start to overlap. This is a crazy situation, but Vaadin blinks
  3679. * the components a lot, so it's feasible.
  3680. */
  3681. return Math.max(0, maxVisibleRowCount);
  3682. }
  3683. @Override
  3684. protected void paintRemoveRows(final int index,
  3685. final int numberOfRows) {
  3686. if (numberOfRows == 0) {
  3687. return;
  3688. }
  3689. /*
  3690. * NOTE: this method handles and manipulates logical, visual, and
  3691. * physical indexes a lot. If you don't remember what those mean and
  3692. * how they relate to each other, see the top of this class for
  3693. * Maintenance Notes.
  3694. *
  3695. * At the beginning of this method the logical index of the data
  3696. * provider has already been updated to include the new rows, but
  3697. * visual and physical indexes have not, nor has the spacer indexing
  3698. * been updated, and the topRowLogicalIndex may be out of date as
  3699. * well.
  3700. */
  3701. // logical index of the first old row, also the difference between
  3702. // logical index and visual index before any rows have been removed
  3703. final int oldTopRowLogicalIndex = getTopRowLogicalIndex();
  3704. // length of the visual range before anything gets removed
  3705. final int oldVisualRangeLength = visualRowOrder.size();
  3706. // logical range of the removed rows
  3707. final Range removedRowsLogicalRange = Range.withLength(index,
  3708. numberOfRows);
  3709. // check which parts of the removed range fall within or beyond the
  3710. // visual range
  3711. final Range[] partitions = removedRowsLogicalRange
  3712. .partitionWith(Range.withLength(oldTopRowLogicalIndex,
  3713. oldVisualRangeLength));
  3714. final Range removedLogicalAbove = partitions[0];
  3715. final Range removedLogicalBelow = partitions[2];
  3716. final Range removedLogicalWithin = partitions[1];
  3717. if (removedLogicalBelow.length() == numberOfRows) {
  3718. /*
  3719. * Rows were removed entirely from below the visual range. No
  3720. * rows to recycle or scroll position to adjust, just need to
  3721. * recalculate scrollbar height. No need to touch the spacer
  3722. * indexing or the physical index.
  3723. */
  3724. scroller.recalculateScrollbarsForVirtualViewport();
  3725. // Visual range contents remain the same, no need to fire a
  3726. // RowVisibilityChangeEvent.
  3727. } else if (removedLogicalAbove.length() == numberOfRows) {
  3728. /*
  3729. * Rows were removed entirely from above the visual range. No
  3730. * rows to recycle, just need to update the spacer indexing and
  3731. * the content positions. No need to touch the physical index.
  3732. */
  3733. // update the logical indexes of remaining spacers
  3734. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3735. oldTopRowLogicalIndex,
  3736. oldTopRowLogicalIndex + oldVisualRangeLength,
  3737. -numberOfRows);
  3738. // default height of a single row
  3739. final double defaultRowHeight = getDefaultRowHeight();
  3740. // how much viewport, rows, and spacers should be shifted based
  3741. // on the removed rows, assume there were no spacers to remove
  3742. final double yDelta = numberOfRows * defaultRowHeight;
  3743. // shift everything up
  3744. moveViewportAndContent(null, -yDelta, -yDelta, -yDelta);
  3745. // update the top row logical index according to any removed
  3746. // rows
  3747. updateTopRowLogicalIndex(-numberOfRows);
  3748. // update scrollbar
  3749. scroller.recalculateScrollbarsForVirtualViewport();
  3750. // Visual range contents remain the same, no need to fire a
  3751. // RowVisibilityChangeEvent.
  3752. } else {
  3753. /*
  3754. * Rows are being removed at least partially from within the
  3755. * visual range. This is where things get tricky. We might have
  3756. * to scroll up or down or nowhere at all, depending on the
  3757. * situation.
  3758. */
  3759. // Visual range contents changed, RowVisibilityChangeEvent will
  3760. // be triggered within this method
  3761. paintRemoveRowsWithinVisualRange(index, numberOfRows,
  3762. oldTopRowLogicalIndex, oldVisualRangeLength,
  3763. removedLogicalAbove.length(), removedLogicalWithin);
  3764. }
  3765. }
  3766. /**
  3767. * Row removal handling for {@link #paintRemoveRows(int, int)} when the
  3768. * removed range intersects the visual range at least partially.
  3769. * <p>
  3770. * NOTE: This method should not be called directly from anywhere else.
  3771. *
  3772. * @param index
  3773. * @param numberOfRows
  3774. * @param oldTopRowLogicalIndex
  3775. * @param oldVisualRangeLength
  3776. * @param removedAboveLength
  3777. * @param removedLogicalWithin
  3778. */
  3779. private void paintRemoveRowsWithinVisualRange(int index,
  3780. int numberOfRows, int oldTopRowLogicalIndex,
  3781. int oldVisualRangeLength, int removedAboveLength,
  3782. Range removedLogicalWithin) {
  3783. /*
  3784. * Calculating where the visual range should start after the
  3785. * removals is not entirely trivial.
  3786. *
  3787. * Initially, any rows removed from within the visual range won't
  3788. * affect the top index, even if they are removed from the
  3789. * beginning, as the rows are also removed from the logical index.
  3790. * Likewise we don't need to care about rows removed from below the
  3791. * visual range. On the other hand, any rows removed from above the
  3792. * visual range do shift the index down.
  3793. *
  3794. * However, in all of these cases, if there aren't enough rows below
  3795. * the visual range to replace the content removed from within the
  3796. * visual range, more rows need to be brought in from above the old
  3797. * visual range in turn. This shifts the index down even further.
  3798. */
  3799. // scroll position before any rows or spacers are removed
  3800. double scrollTop = getScrollTop();
  3801. Range removedVisualWithin = convertToVisual(removedLogicalWithin);
  3802. int remainingVisualRangeRowCount = visualRowOrder.size()
  3803. - removedVisualWithin.length();
  3804. int newTopRowLogicalIndex = oldTopRowLogicalIndex
  3805. - removedAboveLength;
  3806. int rowsToIncludeFromBelow = Math.min(
  3807. getRowCount() - newTopRowLogicalIndex
  3808. - remainingVisualRangeRowCount,
  3809. removedLogicalWithin.length());
  3810. int rowsToIncludeFromAbove = removedLogicalWithin.length()
  3811. - rowsToIncludeFromBelow;
  3812. int rowsToRemoveFromDom = 0;
  3813. if (rowsToIncludeFromAbove > 0) {
  3814. // don't try to bring in more rows than exist, it's possible
  3815. // to remove enough rows that visual range won't be full
  3816. // anymore
  3817. rowsToRemoveFromDom = Math
  3818. .max(rowsToIncludeFromAbove - newTopRowLogicalIndex, 0);
  3819. rowsToIncludeFromAbove -= rowsToRemoveFromDom;
  3820. newTopRowLogicalIndex -= rowsToIncludeFromAbove;
  3821. }
  3822. int visualIndexToRemove = Math.max(index - oldTopRowLogicalIndex,
  3823. 0);
  3824. // remove extra dom rows and their spacers if any
  3825. double removedFromDomSpacerHeights = 0d;
  3826. if (rowsToRemoveFromDom > 0) {
  3827. for (int i = 0; i < rowsToRemoveFromDom; ++i) {
  3828. TableRowElement tr = visualRowOrder
  3829. .remove(visualIndexToRemove);
  3830. // logical index of this row before anything got removed
  3831. int logicalRowIndex = oldTopRowLogicalIndex
  3832. + visualIndexToRemove + i;
  3833. double spacerHeight = spacerContainer
  3834. .getSpacerHeight(logicalRowIndex);
  3835. removedFromDomSpacerHeights += spacerHeight;
  3836. spacerContainer.removeSpacer(logicalRowIndex);
  3837. paintRemoveRow(tr, removedVisualWithin.getStart());
  3838. removeRowPosition(tr);
  3839. }
  3840. // update the associated row indexes for remaining spacers,
  3841. // even for those rows that are going to get recycled
  3842. spacerContainer.updateSpacerIndexesForRowAndAfter(
  3843. oldTopRowLogicalIndex + visualIndexToRemove
  3844. + rowsToRemoveFromDom,
  3845. oldTopRowLogicalIndex + oldVisualRangeLength,
  3846. -rowsToRemoveFromDom);
  3847. }
  3848. // add new content from below visual range, if there is any
  3849. if (rowsToIncludeFromBelow > 0) {
  3850. // removed rows are recycled to just below the old visual
  3851. // range, calculate the logical index of the insertion
  3852. // point that is just below the existing rows, taking into
  3853. // account that the indexing has changed with the removal
  3854. int firstBelow = newTopRowLogicalIndex + rowsToIncludeFromAbove
  3855. + remainingVisualRangeRowCount;
  3856. moveAndUpdateEscalatorRows(
  3857. Range.withLength(visualIndexToRemove,
  3858. rowsToIncludeFromBelow),
  3859. visualRowOrder.size(), firstBelow);
  3860. }
  3861. // add new content from above visual range, if there is any
  3862. // -- this is left last because most of the time it isn't even
  3863. // needed
  3864. if (rowsToIncludeFromAbove > 0) {
  3865. moveAndUpdateEscalatorRows(
  3866. Range.withLength(visualIndexToRemove,
  3867. rowsToIncludeFromAbove),
  3868. 0, newTopRowLogicalIndex);
  3869. }
  3870. // recycling updates all relevant row and spacer positions but
  3871. // if we only removed DOM rows and didn't recycle any we still
  3872. // need to shift up the rows below the removal point
  3873. if (rowsToIncludeFromAbove <= 0 && rowsToIncludeFromBelow <= 0) {
  3874. // update the positions for the rows and spacers below the
  3875. // removed ones, assume there is no need to update scroll
  3876. // position since the final check adjusts that if needed
  3877. double yDelta = numberOfRows * getDefaultRowHeight()
  3878. + removedFromDomSpacerHeights;
  3879. moveViewportAndContent(
  3880. newTopRowLogicalIndex + visualIndexToRemove, -yDelta,
  3881. -yDelta, 0);
  3882. }
  3883. setTopRowLogicalIndex(newTopRowLogicalIndex);
  3884. scroller.recalculateScrollbarsForVirtualViewport();
  3885. // calling this method also triggers adding new spacers to the
  3886. // recycled rows, if any are needed
  3887. fireRowVisibilityChangeEvent();
  3888. // populating the spacers might take a while, delay calculations
  3889. // or the viewport might get adjusted too high
  3890. Scheduler.get().scheduleFinally(() -> {
  3891. // make sure there isn't a gap at the bottom after removal
  3892. // and adjust the viewport if there is
  3893. // FIXME: this should be doable with
  3894. // adjustScrollPositionIfNeeded() but it uses current
  3895. // scrollTop, which may have ended in wrong position and
  3896. // results in assuming too big gap and consequently
  3897. // scrolling up too much
  3898. double extraSpaceAtBottom = scrollTop + getHeightOfSection()
  3899. - getRowTop(getTopRowLogicalIndex()
  3900. + visualRowOrder.size());
  3901. if (extraSpaceAtBottom > 0 && scrollTop > 0) {
  3902. // we need to move the viewport up to adjust, while the
  3903. // rows and spacers can remain where they are
  3904. double yDeltaScroll = Math.min(extraSpaceAtBottom,
  3905. scrollTop);
  3906. moveViewportAndContent(null, 0, 0, -yDeltaScroll);
  3907. }
  3908. });
  3909. // update physical index
  3910. sortDomElements();
  3911. }
  3912. @Override
  3913. public int getLogicalRowIndex(final TableRowElement tr) {
  3914. assert tr
  3915. .getParentNode() == root : "The given element isn't a row element in the body";
  3916. int internalIndex = visualRowOrder.indexOf(tr);
  3917. return getTopRowLogicalIndex() + internalIndex;
  3918. }
  3919. @Override
  3920. protected void recalculateSectionHeight() {
  3921. // NOOP for body, since it doesn't make any sense.
  3922. }
  3923. /**
  3924. * Adjusts the row index and number to be relevant for the current
  3925. * virtual viewport.
  3926. * <p>
  3927. * It converts a logical range of rows index to the matching visual
  3928. * range, truncating the resulting range with the viewport.
  3929. * <p>
  3930. * <ul>
  3931. * <li>Escalator contains logical rows 0..100
  3932. * <li>Current viewport showing logical rows 20..29
  3933. * <li>convertToVisual([20..29]) &rarr; [0..9]
  3934. * <li>convertToVisual([15..24]) &rarr; [0..4]
  3935. * <li>convertToVisual([25..29]) &rarr; [5..9]
  3936. * <li>convertToVisual([26..39]) &rarr; [6..9]
  3937. * <li>convertToVisual([0..5]) &rarr; [0..-1] <em>(empty)</em>
  3938. * <li>convertToVisual([35..1]) &rarr; [0..-1] <em>(empty)</em>
  3939. * <li>convertToVisual([0..100]) &rarr; [0..9]
  3940. * </ul>
  3941. *
  3942. * @return a logical range converted to a visual range, truncated to the
  3943. * current viewport. The first visual row has the index 0.
  3944. */
  3945. private Range convertToVisual(final Range logicalRange) {
  3946. if (logicalRange.isEmpty()) {
  3947. return logicalRange;
  3948. } else if (visualRowOrder.isEmpty()) {
  3949. // empty range
  3950. return Range.withLength(0, 0);
  3951. }
  3952. final int currentTopRowIndex = getTopRowLogicalIndex();
  3953. final Range[] partitions = logicalRange
  3954. .partitionWith(getVisibleRowRange());
  3955. final Range insideRange = partitions[1];
  3956. return insideRange.offsetBy(-currentTopRowIndex);
  3957. }
  3958. @Override
  3959. protected String getCellElementTagName() {
  3960. return "td";
  3961. }
  3962. @Override
  3963. protected double getHeightOfSection() {
  3964. final int tableHeight = tableWrapper.getOffsetHeight();
  3965. final double footerHeight = footer.getHeightOfSection();
  3966. final double headerHeight = header.getHeightOfSection();
  3967. double heightOfSection = tableHeight - footerHeight - headerHeight;
  3968. return Math.max(0, heightOfSection);
  3969. }
  3970. @Override
  3971. protected void refreshCells(Range logicalRowRange, Range colRange) {
  3972. Profiler.enter("Escalator.BodyRowContainer.refreshRows");
  3973. final Range visualRange = convertToVisual(logicalRowRange);
  3974. if (!visualRange.isEmpty()) {
  3975. final int firstLogicalRowIndex = getLogicalRowIndex(
  3976. visualRowOrder.getFirst());
  3977. for (int rowNumber = visualRange
  3978. .getStart(); rowNumber < visualRange
  3979. .getEnd(); rowNumber++) {
  3980. refreshRow(visualRowOrder.get(rowNumber),
  3981. firstLogicalRowIndex + rowNumber, colRange);
  3982. }
  3983. }
  3984. Profiler.leave("Escalator.BodyRowContainer.refreshRows");
  3985. }
  3986. @Override
  3987. protected TableRowElement getTrByVisualIndex(final int index)
  3988. throws IndexOutOfBoundsException {
  3989. if (index >= 0 && index < visualRowOrder.size()) {
  3990. return visualRowOrder.get(index);
  3991. } else {
  3992. throw new IndexOutOfBoundsException(
  3993. "No such visual index: " + index);
  3994. }
  3995. }
  3996. @Override
  3997. public TableRowElement getRowElement(int index) {
  3998. if (index < 0 || index >= getRowCount()) {
  3999. throw new IndexOutOfBoundsException(
  4000. "No such logical index: " + index);
  4001. }
  4002. int visualIndex = index
  4003. - getLogicalRowIndex(visualRowOrder.getFirst());
  4004. if (visualIndex >= 0 && visualIndex < visualRowOrder.size()) {
  4005. return super.getRowElement(visualIndex);
  4006. } else {
  4007. throw new IllegalStateException("Row with logical index "
  4008. + index + " is currently not available in the DOM");
  4009. }
  4010. }
  4011. private void setBodyScrollPosition(final double scrollLeft,
  4012. final double scrollTop) {
  4013. tBodyScrollLeft = scrollLeft;
  4014. tBodyScrollTop = scrollTop;
  4015. position.set(bodyElem, -tBodyScrollLeft, -tBodyScrollTop);
  4016. position.set(spacerDecoContainer, 0, -tBodyScrollTop);
  4017. }
  4018. /**
  4019. * Make sure that there is a correct amount of escalator rows: Add more
  4020. * if needed, or remove any superfluous ones.
  4021. * <p>
  4022. * This method should be called when e.g. the height of the Escalator
  4023. * changes.
  4024. * <p>
  4025. * <em>Note:</em> This method will make sure that the escalator rows are
  4026. * placed in the proper places. By default new rows are added below, but
  4027. * if the content is scrolled down, the rows are populated on top
  4028. * instead.
  4029. */
  4030. public void verifyEscalatorCount() {
  4031. /*
  4032. * This method indeed has a smell very similar to paintRemoveRows
  4033. * and paintInsertRows.
  4034. *
  4035. * Unfortunately, the code of those can't trivially be shared, since
  4036. * there are some slight differences in the respective
  4037. * responsibilities. The "paint" methods fake the addition and
  4038. * removal of rows, and make sure to either push existing data out
  4039. * of view, or draw new data into view. Only in some special cases
  4040. * will the DOM element count change.
  4041. *
  4042. * This method, however, has the explicit responsibility to verify
  4043. * that when "something" happens, we still have the correct amount
  4044. * of escalator rows in the DOM, and if not, we make sure to modify
  4045. * that count. Only in some special cases do we need to take into
  4046. * account other things than simply modifying the DOM element count.
  4047. */
  4048. Profiler.enter("Escalator.BodyRowContainer.verifyEscalatorCount");
  4049. if (!isAttached()) {
  4050. return;
  4051. }
  4052. int oldTopRowLogicalIndex = getTopRowLogicalIndex();
  4053. int oldVisualRangeLength = visualRowOrder.size();
  4054. final int maxVisibleRowCount = getMaxVisibleRowCount();
  4055. final int neededEscalatorRows = Math.min(maxVisibleRowCount,
  4056. body.getRowCount());
  4057. final int rowDiff = neededEscalatorRows - oldVisualRangeLength;
  4058. if (rowDiff > 0) {
  4059. // more rows are needed
  4060. // calculate the indexes for adding rows below the last row of
  4061. // the visual range
  4062. final int visualTargetIndex = oldVisualRangeLength;
  4063. final int logicalTargetIndex;
  4064. if (!visualRowOrder.isEmpty()) {
  4065. logicalTargetIndex = oldTopRowLogicalIndex
  4066. + visualTargetIndex;
  4067. } else {
  4068. logicalTargetIndex = 0;
  4069. }
  4070. // prioritise adding to the bottom so that there's less chance
  4071. // for a gap if a details row is later closed (e.g. by user)
  4072. final int addToBottom = Math.min(rowDiff,
  4073. getRowCount() - logicalTargetIndex);
  4074. final int addToTop = Math.max(rowDiff - addToBottom, 0);
  4075. if (addToTop > 0) {
  4076. fillAndPopulateEscalatorRowsIfNeeded(0,
  4077. oldTopRowLogicalIndex - addToTop, addToTop);
  4078. updateTopRowLogicalIndex(-addToTop);
  4079. }
  4080. if (addToBottom > 0) {
  4081. // take into account that rows may have got added to top as
  4082. // well, affects visual but not logical indexing
  4083. fillAndPopulateEscalatorRowsIfNeeded(
  4084. visualTargetIndex + addToTop, logicalTargetIndex,
  4085. addToBottom);
  4086. // adding new rows due to resizing may have created a gap in
  4087. // the middle, check whether the existing rows need moving
  4088. double rowTop = getRowTop(oldTopRowLogicalIndex);
  4089. if (rowTop > getRowTop(visualRowOrder.get(addToTop))) {
  4090. for (int i = addToTop; i < visualTargetIndex; i++) {
  4091. final TableRowElement tr = visualRowOrder.get(i);
  4092. setRowPosition(tr, 0, rowTop);
  4093. rowTop += getDefaultRowHeight();
  4094. SpacerContainer.SpacerImpl spacer = spacerContainer
  4095. .getSpacer(oldTopRowLogicalIndex + i);
  4096. if (spacer != null) {
  4097. spacer.setPosition(0, rowTop);
  4098. rowTop += spacer.getHeight();
  4099. }
  4100. }
  4101. }
  4102. }
  4103. } else if (rowDiff < 0) {
  4104. // rows need to be removed
  4105. // prioritise removing rows from above the viewport as they are
  4106. // less likely to be needed in a hurry -- the rows below are
  4107. // more likely to slide into view when spacer contents are
  4108. // updated
  4109. // top of visible area before any rows are actually added
  4110. double scrollTop = getScrollTop();
  4111. // visual index of the first actually visible row, including
  4112. // spacer
  4113. int oldFirstVisibleVisualIndex = -1;
  4114. ListIterator<TableRowElement> iter = visualRowOrder
  4115. .listIterator(0);
  4116. for (int i = 0; i < visualRowOrder.size(); ++i) {
  4117. if (positions.getTop(iter.next()) > scrollTop) {
  4118. break;
  4119. }
  4120. oldFirstVisibleVisualIndex = i;
  4121. }
  4122. int rowsToRemoveFromAbove = Math.max(0, Math
  4123. .min(Math.abs(rowDiff), oldFirstVisibleVisualIndex));
  4124. boolean spacersRemovedFromAbove = false;
  4125. if (rowsToRemoveFromAbove > 0) {
  4126. double initialSpacerHeightSum = spacerContainer
  4127. .getSpacerHeightsSum();
  4128. iter = visualRowOrder.listIterator(0);
  4129. for (int i = 0; i < rowsToRemoveFromAbove; ++i) {
  4130. final Element first = iter.next();
  4131. first.removeFromParent();
  4132. iter.remove();
  4133. spacerContainer.removeSpacer(oldTopRowLogicalIndex + i);
  4134. }
  4135. spacersRemovedFromAbove = initialSpacerHeightSum != spacerContainer
  4136. .getSpacerHeightsSum();
  4137. }
  4138. // if there weren't enough rows above, remove the rest from
  4139. // below
  4140. int rowsToRemoveFromBelow = Math.abs(rowDiff)
  4141. - rowsToRemoveFromAbove;
  4142. if (rowsToRemoveFromBelow > 0) {
  4143. iter = visualRowOrder.listIterator(visualRowOrder.size());
  4144. for (int i = 1; i <= rowsToRemoveFromBelow; ++i) {
  4145. final Element last = iter.previous();
  4146. last.removeFromParent();
  4147. iter.remove();
  4148. spacerContainer.removeSpacer(oldTopRowLogicalIndex
  4149. + oldVisualRangeLength - i);
  4150. }
  4151. }
  4152. updateTopRowLogicalIndex(rowsToRemoveFromAbove);
  4153. if (spacersRemovedFromAbove) {
  4154. updateRowPositions(oldTopRowLogicalIndex, 0,
  4155. visualRowOrder.size());
  4156. }
  4157. // removing rows might cause a gap at the bottom
  4158. adjustScrollPositionIfNeeded();
  4159. }
  4160. if (rowDiff != 0) {
  4161. scroller.recalculateScrollbarsForVirtualViewport();
  4162. fireRowVisibilityChangeEvent();
  4163. }
  4164. Profiler.leave("Escalator.BodyRowContainer.verifyEscalatorCount");
  4165. }
  4166. @Override
  4167. protected void reapplyDefaultRowHeights() {
  4168. if (visualRowOrder.isEmpty()) {
  4169. return;
  4170. }
  4171. Profiler.enter(
  4172. "Escalator.BodyRowContainer.reapplyDefaultRowHeights");
  4173. double spacerHeightsAboveViewport = spacerContainer
  4174. .getSpacerHeightsSumUntilPx(
  4175. verticalScrollbar.getScrollPos());
  4176. double allSpacerHeights = spacerContainer.getSpacerHeightsSum();
  4177. /* step 1: resize and reposition rows */
  4178. // there should be no spacers above the visual range
  4179. double spacerHeights = 0;
  4180. for (int i = 0; i < visualRowOrder.size(); i++) {
  4181. TableRowElement tr = visualRowOrder.get(i);
  4182. reapplyRowHeight(tr, getDefaultRowHeight());
  4183. final int logicalIndex = getTopRowLogicalIndex() + i;
  4184. double y = logicalIndex * getDefaultRowHeight() + spacerHeights;
  4185. setRowPosition(tr, 0, y);
  4186. SpacerContainer.SpacerImpl spacer = spacerContainer
  4187. .getSpacer(logicalIndex);
  4188. if (spacer != null) {
  4189. spacer.setPosition(0, y + getDefaultRowHeight());
  4190. spacerHeights += spacer.getHeight();
  4191. }
  4192. }
  4193. /*
  4194. * step 2: move scrollbar so that it corresponds to its previous
  4195. * place
  4196. */
  4197. // scrollRatio has to be calculated without spacers for it to be
  4198. // comparable between different row heights
  4199. double scrollRatio = (verticalScrollbar.getScrollPos()
  4200. - spacerHeightsAboveViewport)
  4201. / (verticalScrollbar.getScrollSize() - allSpacerHeights);
  4202. scroller.recalculateScrollbarsForVirtualViewport();
  4203. // spacer heights have to be added back for setting new scrollPos
  4204. verticalScrollbar.setScrollPos(
  4205. (int) ((getDefaultRowHeight() * getRowCount() * scrollRatio)
  4206. + spacerHeightsAboveViewport));
  4207. setBodyScrollPosition(horizontalScrollbar.getScrollPos(),
  4208. verticalScrollbar.getScrollPos());
  4209. scroller.onScroll();
  4210. /*
  4211. * step 3: make sure we have the correct amount of escalator rows.
  4212. */
  4213. verifyEscalatorCount();
  4214. Profiler.leave(
  4215. "Escalator.BodyRowContainer.reapplyDefaultRowHeights");
  4216. }
  4217. /**
  4218. * Sorts the rows in the DOM to correspond to the visual order.
  4219. *
  4220. * @see #visualRowOrder
  4221. */
  4222. private void sortDomElements() {
  4223. final String profilingName = "Escalator.BodyRowContainer.sortDomElements";
  4224. Profiler.enter(profilingName);
  4225. /*
  4226. * Focus is lost from an element if that DOM element is (or any of
  4227. * its parents are) removed from the document. Therefore, we sort
  4228. * everything around that row instead.
  4229. */
  4230. final TableRowElement focusedRow = getRowWithFocus();
  4231. if (focusedRow != null) {
  4232. assert focusedRow
  4233. .getParentElement() == root : "Trying to sort around a row that doesn't exist in body";
  4234. assert visualRowOrder.contains(focusedRow)
  4235. || body.spacerContainer.isSpacer(
  4236. focusedRow) : "Trying to sort around a row that doesn't exist in visualRowOrder or is not a spacer.";
  4237. }
  4238. /*
  4239. * Two cases handled simultaneously:
  4240. *
  4241. * 1) No focus on rows. We iterate visualRowOrder backwards, and
  4242. * take the respective element in the DOM, and place it as the first
  4243. * child in the body element. Then we take the next-to-last from
  4244. * visualRowOrder, and put that first, pushing the previous row as
  4245. * the second child. And so on...
  4246. *
  4247. * 2) Focus on some row within Escalator body. Again, we iterate
  4248. * visualRowOrder backwards. This time, we use the focused row as a
  4249. * pivot: Instead of placing rows from the bottom of visualRowOrder
  4250. * and placing it first, we place it underneath the focused row.
  4251. * Once we hit the focused row, we don't move it (to not reset
  4252. * focus) but change sorting mode. After that, we place all rows as
  4253. * the first child.
  4254. */
  4255. List<TableRowElement> orderedBodyRows = new ArrayList<>(
  4256. visualRowOrder);
  4257. Map<Integer, SpacerContainer.SpacerImpl> spacers = body.spacerContainer
  4258. .getSpacers();
  4259. /*
  4260. * Start at -1 to include a spacer that is rendered above the
  4261. * viewport, but its parent row is still not shown
  4262. */
  4263. for (int i = -1; i < visualRowOrder.size(); i++) {
  4264. SpacerContainer.SpacerImpl spacer = spacers
  4265. .remove(Integer.valueOf(getTopRowLogicalIndex() + i));
  4266. if (spacer != null) {
  4267. orderedBodyRows.add(i + 1, spacer.getRootElement());
  4268. spacer.show();
  4269. }
  4270. }
  4271. /*
  4272. * At this point, invisible spacers aren't reordered, so their
  4273. * position in the DOM will remain undefined.
  4274. */
  4275. // If a spacer was not reordered, it means that it's out of visual
  4276. // range. This should never happen with default Grid implementations
  4277. // but it's possible on an extended Escalator.
  4278. for (SpacerContainer.SpacerImpl unmovedSpacer : spacers.values()) {
  4279. unmovedSpacer.hide();
  4280. }
  4281. /*
  4282. * If we have a focused row, start in the mode where we put
  4283. * everything underneath that row. Otherwise, all rows are placed as
  4284. * first child.
  4285. */
  4286. boolean insertFirst = (focusedRow == null);
  4287. final ListIterator<TableRowElement> i = orderedBodyRows
  4288. .listIterator(orderedBodyRows.size());
  4289. while (i.hasPrevious()) {
  4290. TableRowElement tr = i.previous();
  4291. if (tr == focusedRow) {
  4292. insertFirst = true;
  4293. } else if (insertFirst) {
  4294. // remove row explicitly to work around an IE11 bug (#9850)
  4295. if (BrowserInfo.get().isIE11()
  4296. && tr.equals(root.getFirstChildElement())) {
  4297. root.removeChild(tr);
  4298. }
  4299. root.insertFirst(tr);
  4300. } else {
  4301. root.insertAfter(tr, focusedRow);
  4302. }
  4303. }
  4304. Profiler.leave(profilingName);
  4305. }
  4306. /**
  4307. * Get the {@literal <tbody>} row that contains (or has) focus.
  4308. *
  4309. * @return The {@literal <tbody>} row that contains a focused DOM
  4310. * element, or <code>null</code> if focus is outside of a body
  4311. * row.
  4312. */
  4313. private TableRowElement getRowWithFocus() {
  4314. TableRowElement rowContainingFocus = null;
  4315. final Element focusedElement = WidgetUtil.getFocusedElement();
  4316. if (focusedElement != null && root.isOrHasChild(focusedElement)) {
  4317. Element e = focusedElement;
  4318. while (e != null && e != root) {
  4319. /*
  4320. * You never know if there's several tables embedded in a
  4321. * cell... We'll take the deepest one.
  4322. */
  4323. if (TableRowElement.is(e)) {
  4324. rowContainingFocus = TableRowElement.as(e);
  4325. }
  4326. e = e.getParentElement();
  4327. }
  4328. }
  4329. return rowContainingFocus;
  4330. }
  4331. /**
  4332. * Returns the cell object which contains information about the cell or
  4333. * spacer the element is in. As an implementation detail each spacer is
  4334. * a row with one cell, but they are stored in their own container and
  4335. * share the indexing with the regular rows.
  4336. *
  4337. * @param element
  4338. * The element to get the cell for. If element is not present
  4339. * in row or spacer container then <code>null</code> is
  4340. * returned.
  4341. *
  4342. * @return the cell reference of the element, or <code>null</code> if
  4343. * element is not present in the {@link RowContainer} or the
  4344. * {@link SpacerContainer}.
  4345. */
  4346. @Override
  4347. public Cell getCell(Element element) {
  4348. Cell cell = super.getCell(element);
  4349. if (cell == null) {
  4350. return null;
  4351. }
  4352. // Convert DOM coordinates to logical coordinates for rows
  4353. TableRowElement rowElement = (TableRowElement) cell.getElement()
  4354. .getParentElement();
  4355. if (!visualRowOrder.contains(rowElement)) {
  4356. for (Entry<Integer, SpacerContainer.SpacerImpl> entry : spacerContainer
  4357. .getSpacers().entrySet()) {
  4358. if (rowElement.equals(entry.getValue().getRootElement())) {
  4359. return new Cell(entry.getKey(), cell.getColumn(),
  4360. cell.getElement());
  4361. }
  4362. }
  4363. return null;
  4364. }
  4365. return new Cell(getLogicalRowIndex(rowElement), cell.getColumn(),
  4366. cell.getElement());
  4367. }
  4368. @Override
  4369. public void setSpacer(int rowIndex, double height)
  4370. throws IllegalArgumentException {
  4371. spacerContainer.setSpacer(rowIndex, height);
  4372. }
  4373. @Override
  4374. public boolean spacerExists(int rowIndex) {
  4375. return spacerContainer.spacerExists(rowIndex);
  4376. }
  4377. @Override
  4378. public void setSpacerUpdater(SpacerUpdater spacerUpdater)
  4379. throws IllegalArgumentException {
  4380. spacerContainer.setSpacerUpdater(spacerUpdater);
  4381. }
  4382. @Override
  4383. public SpacerUpdater getSpacerUpdater() {
  4384. return spacerContainer.getSpacerUpdater();
  4385. }
  4386. /**
  4387. * <em>Calculates</em> the expected top position of a row at a logical
  4388. * index, regardless if there is one there currently or not.
  4389. * <p>
  4390. * This method relies on fixed row height (by
  4391. * {@link #getDefaultRowHeight()}) and can only take into account
  4392. * spacers that are within visual range. Any scrolling might invalidate
  4393. * these results, so this method shouldn't be used to estimate scroll
  4394. * positions.
  4395. *
  4396. * @param logicalIndex
  4397. * the logical index of the row for which to calculate the
  4398. * top position
  4399. * @return the position where the row should currently be, were it to
  4400. * exist
  4401. * @see #getRowTop(TableRowElement)
  4402. */
  4403. private double getRowTop(int logicalIndex) {
  4404. double top = spacerContainer
  4405. .getSpacerHeightsSumUntilIndex(logicalIndex);
  4406. return top + (logicalIndex * getDefaultRowHeight());
  4407. }
  4408. public void shiftRowPositions(int row, double diff) {
  4409. for (TableRowElement tr : getVisibleRowsAfter(row)) {
  4410. setRowPosition(tr, 0, getRowTop(tr) + diff);
  4411. }
  4412. }
  4413. private List<TableRowElement> getVisibleRowsAfter(int logicalRow) {
  4414. Range visibleRowLogicalRange = getVisibleRowRange();
  4415. boolean allRowsAreInView = logicalRow < visibleRowLogicalRange
  4416. .getStart();
  4417. boolean noRowsAreInView = logicalRow >= visibleRowLogicalRange
  4418. .getEnd() - 1;
  4419. if (allRowsAreInView) {
  4420. return Collections.unmodifiableList(visualRowOrder);
  4421. } else if (noRowsAreInView) {
  4422. return Collections.emptyList();
  4423. } else {
  4424. int fromIndex = (logicalRow - visibleRowLogicalRange.getStart())
  4425. + 1;
  4426. int toIndex = visibleRowLogicalRange.length();
  4427. List<TableRowElement> sublist = visualRowOrder
  4428. .subList(fromIndex, toIndex);
  4429. return Collections.unmodifiableList(sublist);
  4430. }
  4431. }
  4432. @Override
  4433. public int getDomRowCount() {
  4434. return root.getChildCount()
  4435. - spacerContainer.getSpacersInDom().size();
  4436. }
  4437. @Override
  4438. protected boolean rowCanBeFrozen(TableRowElement tr) {
  4439. return visualRowOrder.contains(tr);
  4440. }
  4441. void reapplySpacerWidths() {
  4442. spacerContainer.reapplySpacerWidths();
  4443. }
  4444. void scrollToRowSpacerOrBoth(int targetRowIndex,
  4445. ScrollDestination destination, double padding,
  4446. ScrollType scrollType) {
  4447. if (!ensureScrollingAllowed()) {
  4448. return;
  4449. }
  4450. validateScrollDestination(destination, (int) padding);
  4451. // ignore the special case of -1 index spacer from the row index
  4452. // validation
  4453. if (!(targetRowIndex == -1 && !ScrollType.ROW.equals(scrollType))) {
  4454. // throws an IndexOutOfBoundsException if not valid
  4455. verifyValidRowIndex(targetRowIndex);
  4456. }
  4457. int oldTopRowLogicalIndex = getTopRowLogicalIndex();
  4458. int visualRangeLength = visualRowOrder.size();
  4459. int paddingInRows = 0;
  4460. if (!WidgetUtil.pixelValuesEqual(padding, 0d)) {
  4461. paddingInRows = (int) Math
  4462. .ceil(Double.valueOf(padding) / getDefaultRowHeight());
  4463. }
  4464. // calculate the largest index necessary to include at least
  4465. // partially below the top of the viewport and the smallest index
  4466. // necessary to include at least partially above the bottom of the
  4467. // viewport (target row itself might not be if padding is negative)
  4468. int firstVisibleIndexIfScrollingUp = targetRowIndex - paddingInRows;
  4469. int lastVisibleIndexIfScrollingDown = targetRowIndex
  4470. + paddingInRows;
  4471. int oldFirstBelowIndex = oldTopRowLogicalIndex + visualRangeLength;
  4472. int newTopRowLogicalIndex;
  4473. int logicalTargetIndex;
  4474. switch (destination) {
  4475. case ANY:
  4476. // scroll as little as possible, take into account that there
  4477. // needs to be a buffer row at both ends if there is room for
  4478. // one
  4479. boolean newRowsNeededAbove = (firstVisibleIndexIfScrollingUp < oldTopRowLogicalIndex)
  4480. || (firstVisibleIndexIfScrollingUp == oldTopRowLogicalIndex
  4481. && targetRowIndex > 0);
  4482. boolean rowsNeededBelow = (lastVisibleIndexIfScrollingDown >= oldFirstBelowIndex)
  4483. || ((lastVisibleIndexIfScrollingDown == oldFirstBelowIndex
  4484. - 1) && (oldFirstBelowIndex < getRowCount()));
  4485. if (newRowsNeededAbove) {
  4486. // scroll up, add buffer row if it fits
  4487. logicalTargetIndex = Math
  4488. .max(firstVisibleIndexIfScrollingUp - 1, 0);
  4489. newTopRowLogicalIndex = logicalTargetIndex;
  4490. } else if (rowsNeededBelow) {
  4491. // scroll down, add buffer row if it fits
  4492. newTopRowLogicalIndex = Math.min(
  4493. lastVisibleIndexIfScrollingDown + 1,
  4494. getRowCount() - 1) - visualRangeLength + 1;
  4495. if (newTopRowLogicalIndex
  4496. - oldTopRowLogicalIndex < visualRangeLength) {
  4497. // partial recycling, target index at the end of
  4498. // current range
  4499. logicalTargetIndex = oldFirstBelowIndex;
  4500. } else {
  4501. // full recycling, target index the same as the new
  4502. // top row index
  4503. logicalTargetIndex = newTopRowLogicalIndex;
  4504. }
  4505. } else {
  4506. // no need to recycle rows but viewport might need
  4507. // adjusting regardless
  4508. logicalTargetIndex = -1;
  4509. newTopRowLogicalIndex = oldTopRowLogicalIndex;
  4510. }
  4511. break;
  4512. case END:
  4513. // target row at the bottom of the viewport
  4514. newTopRowLogicalIndex = lastVisibleIndexIfScrollingDown + 1
  4515. - visualRangeLength + 1;
  4516. newTopRowLogicalIndex = ensureTopRowLogicalIndexSanity(
  4517. newTopRowLogicalIndex);
  4518. if ((newTopRowLogicalIndex > oldTopRowLogicalIndex)
  4519. && (newTopRowLogicalIndex
  4520. - oldTopRowLogicalIndex < visualRangeLength)) {
  4521. // partial recycling, target index at the end of
  4522. // current range
  4523. logicalTargetIndex = oldFirstBelowIndex;
  4524. } else {
  4525. // full recycling, target index the same as the new
  4526. // top row index
  4527. logicalTargetIndex = newTopRowLogicalIndex;
  4528. }
  4529. break;
  4530. case MIDDLE:
  4531. // target row at the middle of the viewport, padding has to be
  4532. // zero or we never would have reached this far
  4533. newTopRowLogicalIndex = targetRowIndex - visualRangeLength / 2;
  4534. newTopRowLogicalIndex = ensureTopRowLogicalIndexSanity(
  4535. newTopRowLogicalIndex);
  4536. if (newTopRowLogicalIndex < oldTopRowLogicalIndex) {
  4537. logicalTargetIndex = newTopRowLogicalIndex;
  4538. } else if (newTopRowLogicalIndex > oldTopRowLogicalIndex) {
  4539. if (newTopRowLogicalIndex
  4540. - oldTopRowLogicalIndex < visualRangeLength) {
  4541. // partial recycling, target index at the end of
  4542. // current range
  4543. logicalTargetIndex = oldFirstBelowIndex;
  4544. } else {
  4545. // full recycling, target index the same as the new
  4546. // top row index
  4547. logicalTargetIndex = newTopRowLogicalIndex;
  4548. }
  4549. } else {
  4550. logicalTargetIndex = -1;
  4551. }
  4552. break;
  4553. case START:
  4554. // target row at the top of the viewport, include buffer
  4555. // row if there is room for one
  4556. newTopRowLogicalIndex = firstVisibleIndexIfScrollingUp - 1;
  4557. newTopRowLogicalIndex = ensureTopRowLogicalIndexSanity(
  4558. newTopRowLogicalIndex);
  4559. if (getVisibleRowRange().contains(newTopRowLogicalIndex)) {
  4560. logicalTargetIndex = oldTopRowLogicalIndex
  4561. + visualRangeLength;
  4562. } else {
  4563. logicalTargetIndex = newTopRowLogicalIndex;
  4564. }
  4565. break;
  4566. default:
  4567. String msg = "Internal: Unsupported ScrollDestination: ";
  4568. throw new IllegalArgumentException(msg + destination.name());
  4569. }
  4570. // adjust visual range if necessary
  4571. if (newTopRowLogicalIndex < oldTopRowLogicalIndex) {
  4572. adjustVisualRangeUpForScrollToRowSpacerOrBoth(
  4573. oldTopRowLogicalIndex, visualRangeLength,
  4574. logicalTargetIndex);
  4575. } else if (newTopRowLogicalIndex > oldTopRowLogicalIndex) {
  4576. adjustVisualRangeDownForScrollToRowSpacerOrBoth(
  4577. oldTopRowLogicalIndex, visualRangeLength,
  4578. newTopRowLogicalIndex, logicalTargetIndex);
  4579. }
  4580. boolean rowsWereMoved = newTopRowLogicalIndex != oldTopRowLogicalIndex;
  4581. // update scroll position if necessary
  4582. adjustScrollPositionForScrollToRowSpacerOrBoth(targetRowIndex,
  4583. destination, padding, scrollType);
  4584. if (rowsWereMoved) {
  4585. fireRowVisibilityChangeEvent();
  4586. // schedule updating of the physical indexes
  4587. domSorter.reschedule();
  4588. }
  4589. }
  4590. /**
  4591. * Modifies the proposed top row logical index to fit within the logical
  4592. * range and to not leave gaps if it is avoidable.
  4593. *
  4594. * @param proposedTopRowLogicalIndex
  4595. * @return an adjusted index, or the original if no changes were
  4596. * necessary
  4597. */
  4598. private int ensureTopRowLogicalIndexSanity(
  4599. int proposedTopRowLogicalIndex) {
  4600. int newTopRowLogicalIndex = Math.max(proposedTopRowLogicalIndex, 0);
  4601. int visualRangeLength = visualRowOrder.size();
  4602. if (newTopRowLogicalIndex + visualRangeLength > getRowCount()) {
  4603. newTopRowLogicalIndex = getRowCount() - visualRangeLength;
  4604. }
  4605. return newTopRowLogicalIndex;
  4606. }
  4607. /**
  4608. * Checks that scrolling is allowed and resets the scroll position if
  4609. * it's not.
  4610. *
  4611. * @return {@code true} if scrolling is allowed, {@code false} otherwise
  4612. */
  4613. private boolean ensureScrollingAllowed() {
  4614. if (isScrollLocked(Direction.VERTICAL)) {
  4615. // no scrolling can happen
  4616. if (getScrollTop() != tBodyScrollTop) {
  4617. setBodyScrollPosition(tBodyScrollLeft, getScrollTop());
  4618. }
  4619. return false;
  4620. }
  4621. return true;
  4622. }
  4623. /**
  4624. * Adjusts visual range up for
  4625. * {@link #scrollToRowSpacerOrBoth(int, ScrollDestination, double, boolean, boolean)},
  4626. * reuse at your own peril.
  4627. *
  4628. * @param oldTopRowLogicalIndex
  4629. * @param visualRangeLength
  4630. * @param logicalTargetIndex
  4631. */
  4632. private void adjustVisualRangeUpForScrollToRowSpacerOrBoth(
  4633. int oldTopRowLogicalIndex, int visualRangeLength,
  4634. int logicalTargetIndex) {
  4635. // recycle at most the visual range's worth of rows to fill
  4636. // the gap between the new visualTargetIndex and the existing
  4637. // rows
  4638. int rowsToRecycle = Math.min(
  4639. oldTopRowLogicalIndex - logicalTargetIndex,
  4640. visualRangeLength);
  4641. // recycle from the end to the beginning
  4642. moveAndUpdateEscalatorRows(
  4643. Range.withLength(visualRangeLength - rowsToRecycle,
  4644. rowsToRecycle),
  4645. 0, logicalTargetIndex);
  4646. // update the index
  4647. setTopRowLogicalIndex(logicalTargetIndex);
  4648. }
  4649. /**
  4650. * Adjusts visual range down for
  4651. * {@link #scrollToRowSpacerOrBoth(int, ScrollDestination, double, boolean, boolean)},
  4652. * reuse at your own peril.
  4653. *
  4654. * @param oldTopRowLogicalIndex
  4655. * @param visualRangeLength
  4656. * @param newTopRowLogicalIndex
  4657. * @param logicalTargetIndex
  4658. */
  4659. private void adjustVisualRangeDownForScrollToRowSpacerOrBoth(
  4660. int oldTopRowLogicalIndex, int visualRangeLength,
  4661. int newTopRowLogicalIndex, int logicalTargetIndex) {
  4662. // recycle at most the visual range's worth of rows to fill
  4663. // the gap between the new visualTargetIndex and the existing
  4664. // rows
  4665. int rowsToRecycle;
  4666. if (newTopRowLogicalIndex
  4667. - oldTopRowLogicalIndex >= visualRangeLength) {
  4668. // full recycling
  4669. rowsToRecycle = visualRangeLength;
  4670. } else {
  4671. // partial recycling
  4672. rowsToRecycle = newTopRowLogicalIndex - oldTopRowLogicalIndex;
  4673. }
  4674. // recycle from the beginning to the end
  4675. moveAndUpdateEscalatorRows(Range.withLength(0, rowsToRecycle),
  4676. visualRangeLength, logicalTargetIndex);
  4677. // update the index
  4678. setTopRowLogicalIndex(newTopRowLogicalIndex);
  4679. }
  4680. /**
  4681. * Adjusts scroll position for
  4682. * {@link #scrollToRowSpacerOrBoth(int, ScrollDestination, double, boolean, boolean)},
  4683. * reuse at your own peril.
  4684. *
  4685. * @param targetRowIndex
  4686. * @param destination
  4687. * @param padding
  4688. * @param scrollType
  4689. */
  4690. private void adjustScrollPositionForScrollToRowSpacerOrBoth(
  4691. int targetRowIndex, ScrollDestination destination,
  4692. double padding, ScrollType scrollType) {
  4693. /*
  4694. * attempting to scroll above first row or below last row would get
  4695. * automatically corrected later but that causes unnecessary
  4696. * calculations, so try not to overshoot
  4697. */
  4698. double sectionHeight = getHeightOfSection();
  4699. double rowTop = getRowTop(targetRowIndex);
  4700. double spacerHeight = spacerContainer
  4701. .getSpacerHeight(targetRowIndex);
  4702. double scrollTop;
  4703. switch (destination) {
  4704. case ANY:
  4705. if (!ScrollType.SPACER.equals(scrollType)
  4706. && Math.max(rowTop - padding, 0) < getScrollTop()) {
  4707. // within visual range but row top above the viewport or not
  4708. // enough padding, shift a little
  4709. scrollTop = Math.max(rowTop - padding, 0);
  4710. } else if (ScrollType.SPACER.equals(scrollType)
  4711. && Math.max(rowTop + getDefaultRowHeight() - padding,
  4712. 0) < getScrollTop()) {
  4713. // within visual range but spacer top above the viewport or
  4714. // not enough padding, shift a little
  4715. scrollTop = Math
  4716. .max(rowTop + getDefaultRowHeight() - padding, 0);
  4717. } else if (ScrollType.ROW.equals(scrollType)
  4718. && rowTop + getDefaultRowHeight()
  4719. + padding > getScrollTop() + sectionHeight) {
  4720. // within visual range but end of row below the viewport
  4721. // or not enough padding, shift a little
  4722. scrollTop = rowTop + getDefaultRowHeight() - sectionHeight
  4723. + padding;
  4724. // ensure that we don't overshoot beyond bottom
  4725. scrollTop = Math.min(scrollTop,
  4726. getRowTop(getRowCount() - 1) + getDefaultRowHeight()
  4727. + spacerContainer
  4728. .getSpacerHeight(getRowCount() - 1)
  4729. - sectionHeight);
  4730. // if padding is set we want to overshoot or undershoot,
  4731. // otherwise make sure the top of the row is in view
  4732. if (padding == 0) {
  4733. scrollTop = Math.min(scrollTop, rowTop);
  4734. }
  4735. } else if (rowTop + getDefaultRowHeight() + spacerHeight
  4736. + padding > getScrollTop() + sectionHeight) {
  4737. // within visual range but end of spacer below the viewport
  4738. // or not enough padding, shift a little
  4739. scrollTop = rowTop + getDefaultRowHeight() + spacerHeight
  4740. - sectionHeight + padding;
  4741. // ensure that we don't overshoot beyond bottom
  4742. scrollTop = Math.min(scrollTop,
  4743. getRowTop(getRowCount()) - sectionHeight);
  4744. // if padding is set we want to overshoot or undershoot,
  4745. // otherwise make sure the top of the row or spacer is
  4746. // in view
  4747. if (padding == 0) {
  4748. if (ScrollType.SPACER.equals(scrollType)) {
  4749. scrollTop = Math.min(scrollTop,
  4750. rowTop + getDefaultRowHeight());
  4751. } else {
  4752. scrollTop = Math.min(scrollTop, rowTop);
  4753. }
  4754. }
  4755. } else {
  4756. // we are fine where we are
  4757. scrollTop = getScrollTop();
  4758. }
  4759. break;
  4760. case END:
  4761. if (ScrollType.ROW.equals(scrollType)
  4762. && rowTop + getDefaultRowHeight()
  4763. + padding != getScrollTop() + sectionHeight) {
  4764. // row should be at the bottom of the viewport
  4765. scrollTop = rowTop + getDefaultRowHeight() - sectionHeight
  4766. + padding;
  4767. } else if (rowTop + getDefaultRowHeight() + spacerHeight
  4768. + padding != getScrollTop() + sectionHeight) {
  4769. // spacer should be at the bottom of the viewport
  4770. scrollTop = rowTop + getDefaultRowHeight() + spacerHeight
  4771. - sectionHeight + padding;
  4772. } else {
  4773. // we are fine where we are
  4774. scrollTop = getScrollTop();
  4775. }
  4776. break;
  4777. case MIDDLE:
  4778. double center;
  4779. if (ScrollType.ROW.equals(scrollType)) {
  4780. // center the row itself
  4781. center = rowTop + (getDefaultRowHeight() / 2.0);
  4782. } else if (ScrollType.ROW_AND_SPACER.equals(scrollType)) {
  4783. // center both
  4784. center = rowTop
  4785. + ((getDefaultRowHeight() + spacerHeight) / 2.0);
  4786. } else {
  4787. // center the spacer
  4788. center = rowTop + getDefaultRowHeight()
  4789. + (spacerHeight / 2.0);
  4790. }
  4791. scrollTop = center - Math.ceil(sectionHeight / 2.0);
  4792. break;
  4793. case START:
  4794. if (!ScrollType.SPACER.equals(scrollType)
  4795. && Math.max(rowTop - padding, 0) != getScrollTop()) {
  4796. // row should be at the top of the viewport
  4797. scrollTop = Math.max(rowTop - padding, 0);
  4798. } else if (ScrollType.SPACER.equals(scrollType)
  4799. && Math.max(rowTop + getDefaultRowHeight() - padding,
  4800. 0) != getScrollTop()) {
  4801. // spacer should be at the top of the viewport
  4802. scrollTop = Math
  4803. .max(rowTop + getDefaultRowHeight() - padding, 0);
  4804. } else {
  4805. scrollTop = getScrollTop();
  4806. }
  4807. break;
  4808. default:
  4809. scrollTop = getScrollTop();
  4810. }
  4811. // ensure that we don't overshoot beyond bottom
  4812. scrollTop = Math.min(scrollTop,
  4813. getRowTop(getRowCount()) - sectionHeight);
  4814. // ensure that we don't overshoot beyond top
  4815. scrollTop = Math.max(0, scrollTop);
  4816. if (scrollTop != getScrollTop()) {
  4817. setScrollTop(scrollTop);
  4818. setBodyScrollPosition(tBodyScrollLeft, scrollTop);
  4819. }
  4820. }
  4821. @Override
  4822. public void setNewRowCallback(
  4823. Consumer<List<TableRowElement>> callback) {
  4824. newEscalatorRowCallback = callback;
  4825. }
  4826. }
  4827. private class ColumnConfigurationImpl implements ColumnConfiguration {
  4828. public class Column {
  4829. public static final double DEFAULT_COLUMN_WIDTH_PX = 100;
  4830. private double definedWidth = -1;
  4831. private double calculatedWidth = DEFAULT_COLUMN_WIDTH_PX;
  4832. private boolean measuringRequested = false;
  4833. public void setWidth(double px) {
  4834. Profiler.enter(
  4835. "Escalator.ColumnConfigurationImpl.Column.setWidth");
  4836. definedWidth = px;
  4837. if (px < 0) {
  4838. if (isAttached()) {
  4839. calculateWidth();
  4840. } else {
  4841. /*
  4842. * the column's width is calculated at Escalator.onLoad
  4843. * via measureAndSetWidthIfNeeded!
  4844. */
  4845. measuringRequested = true;
  4846. }
  4847. } else {
  4848. calculatedWidth = px;
  4849. }
  4850. Profiler.leave(
  4851. "Escalator.ColumnConfigurationImpl.Column.setWidth");
  4852. }
  4853. public double getDefinedWidth() {
  4854. return definedWidth;
  4855. }
  4856. /**
  4857. * Returns the actual width in the DOM.
  4858. *
  4859. * @return the width in pixels in the DOM. Returns -1 if the column
  4860. * needs measuring, but has not been yet measured
  4861. */
  4862. public double getCalculatedWidth() {
  4863. /*
  4864. * This might return an untrue value (e.g. during init/onload),
  4865. * since we haven't had a proper chance to actually calculate
  4866. * widths yet.
  4867. *
  4868. * This is fixed during Escalator.onLoad, by the call to
  4869. * "measureAndSetWidthIfNeeded", which fixes "everything".
  4870. */
  4871. if (!measuringRequested) {
  4872. return calculatedWidth;
  4873. } else {
  4874. return -1;
  4875. }
  4876. }
  4877. /**
  4878. * Checks if the column needs measuring, and then measures it.
  4879. * <p>
  4880. * Called by {@link Escalator#onLoad()}.
  4881. */
  4882. public boolean measureAndSetWidthIfNeeded() {
  4883. assert isAttached() : "Column.measureAndSetWidthIfNeeded() was called even though Escalator was not attached!";
  4884. if (measuringRequested) {
  4885. measuringRequested = false;
  4886. setWidth(definedWidth);
  4887. return true;
  4888. }
  4889. return false;
  4890. }
  4891. private void calculateWidth() {
  4892. calculatedWidth = getMaxCellWidth(columns.indexOf(this));
  4893. }
  4894. }
  4895. private final List<Column> columns = new ArrayList<>();
  4896. private int frozenColumns = 0;
  4897. /*
  4898. * TODO: this is a bit of a duplicate functionality with the
  4899. * Column.calculatedWidth caching. Probably should use one or the other,
  4900. * not both
  4901. */
  4902. /**
  4903. * A cached array of all the calculated column widths.
  4904. *
  4905. * @see #getCalculatedColumnWidths()
  4906. */
  4907. private double[] widthsArray = null;
  4908. /**
  4909. * {@inheritDoc}
  4910. * <p>
  4911. * <em>Implementation detail:</em> This method does no DOM modifications
  4912. * (i.e. is very cheap to call) if there are no rows in the DOM when
  4913. * this method is called.
  4914. *
  4915. * @see #hasSomethingInDom()
  4916. */
  4917. @Override
  4918. public void removeColumns(final int index, final int numberOfColumns) {
  4919. if (numberOfColumns == 0) {
  4920. return;
  4921. }
  4922. // Validate
  4923. assertArgumentsAreValidAndWithinRange(index, numberOfColumns);
  4924. // Move the horizontal scrollbar to the left, if removed columns are
  4925. // to the left of the viewport
  4926. removeColumnsAdjustScrollbar(index, numberOfColumns);
  4927. // Remove from DOM
  4928. header.paintRemoveColumns(index, numberOfColumns);
  4929. body.paintRemoveColumns(index, numberOfColumns);
  4930. footer.paintRemoveColumns(index, numberOfColumns);
  4931. // Remove from bookkeeping
  4932. flyweightRow.removeCells(index, numberOfColumns);
  4933. columns.subList(index, index + numberOfColumns).clear();
  4934. // Adjust frozen columns
  4935. if (index < getFrozenColumnCount()) {
  4936. if (index + numberOfColumns < frozenColumns) {
  4937. /*
  4938. * Last removed column was frozen, meaning that all removed
  4939. * columns were frozen. Just decrement the number of frozen
  4940. * columns accordingly.
  4941. */
  4942. frozenColumns -= numberOfColumns;
  4943. } else {
  4944. /*
  4945. * If last removed column was not frozen, we have removed
  4946. * columns beyond the frozen range, so all remaining frozen
  4947. * columns are to the left of the removed columns.
  4948. */
  4949. frozenColumns = index;
  4950. }
  4951. }
  4952. scroller.recalculateScrollbarsForVirtualViewport();
  4953. body.verifyEscalatorCount();
  4954. if (getColumnConfiguration().getColumnCount() > 0) {
  4955. reapplyRowWidths(header);
  4956. reapplyRowWidths(body);
  4957. reapplyRowWidths(footer);
  4958. }
  4959. /*
  4960. * Colspans make any kind of automatic clever content re-rendering
  4961. * impossible: As soon as anything has colspans, removing one might
  4962. * reveal further colspans, modifying the DOM structure once again,
  4963. * ending in a cascade of updates. Because we don't know how the
  4964. * data is updated.
  4965. *
  4966. * So, instead, we don't do anything. The client code is responsible
  4967. * for re-rendering the content (if so desired). Everything Just
  4968. * Works (TM) if colspans aren't used.
  4969. */
  4970. }
  4971. private void reapplyRowWidths(AbstractRowContainer container) {
  4972. if (container.getRowCount() > 0) {
  4973. container.reapplyRowWidths();
  4974. }
  4975. }
  4976. private void removeColumnsAdjustScrollbar(int index,
  4977. int numberOfColumns) {
  4978. if (horizontalScrollbar.getOffsetSize() >= horizontalScrollbar
  4979. .getScrollSize()) {
  4980. return;
  4981. }
  4982. double leftPosOfFirstColumnToRemove = getCalculatedColumnsWidth(
  4983. Range.between(0, index));
  4984. double widthOfColumnsToRemove = getCalculatedColumnsWidth(
  4985. Range.withLength(index, numberOfColumns));
  4986. double scrollLeft = horizontalScrollbar.getScrollPos();
  4987. if (scrollLeft <= leftPosOfFirstColumnToRemove) {
  4988. /*
  4989. * viewport is scrolled to the left of the first removed column,
  4990. * so there's no need to adjust anything
  4991. */
  4992. return;
  4993. }
  4994. double adjustedScrollLeft = Math.max(leftPosOfFirstColumnToRemove,
  4995. scrollLeft - widthOfColumnsToRemove);
  4996. horizontalScrollbar.setScrollPos(adjustedScrollLeft);
  4997. }
  4998. /**
  4999. * Calculate the width of a row, as the sum of columns' widths.
  5000. *
  5001. * @return the width of a row, in pixels
  5002. */
  5003. public double calculateRowWidth() {
  5004. return getCalculatedColumnsWidth(
  5005. Range.between(0, getColumnCount()));
  5006. }
  5007. private void assertArgumentsAreValidAndWithinRange(final int index,
  5008. final int numberOfColumns) {
  5009. if (numberOfColumns < 1) {
  5010. throw new IllegalArgumentException(
  5011. "Number of columns can't be less than 1 (was "
  5012. + numberOfColumns + ")");
  5013. }
  5014. if (index < 0 || index + numberOfColumns > getColumnCount()) {
  5015. throw new IndexOutOfBoundsException("The given "
  5016. + "column range (" + index + ".."
  5017. + (index + numberOfColumns)
  5018. + ") was outside of the current "
  5019. + "number of columns (" + getColumnCount() + ")");
  5020. }
  5021. }
  5022. /**
  5023. * {@inheritDoc}
  5024. * <p>
  5025. * <em>Implementation detail:</em> This method does no DOM modifications
  5026. * (i.e. is very cheap to call) if there is no data for rows when this
  5027. * method is called.
  5028. *
  5029. * @see #hasColumnAndRowData()
  5030. */
  5031. @Override
  5032. public void insertColumns(final int index, final int numberOfColumns) {
  5033. if (numberOfColumns == 0) {
  5034. return;
  5035. }
  5036. // Validate
  5037. if (index < 0 || index > getColumnCount()) {
  5038. throw new IndexOutOfBoundsException("The given index(" + index
  5039. + ") was outside of the current number of columns (0.."
  5040. + getColumnCount() + ")");
  5041. }
  5042. if (numberOfColumns < 1) {
  5043. throw new IllegalArgumentException(
  5044. "Number of columns must be 1 or greater (was "
  5045. + numberOfColumns);
  5046. }
  5047. // Add to bookkeeping
  5048. flyweightRow.addCells(index, numberOfColumns);
  5049. for (int i = 0; i < numberOfColumns; i++) {
  5050. columns.add(index, new Column());
  5051. }
  5052. // Adjust frozen columns
  5053. boolean frozen = index < frozenColumns;
  5054. if (frozen) {
  5055. frozenColumns += numberOfColumns;
  5056. }
  5057. // Add to DOM
  5058. header.paintInsertColumns(index, numberOfColumns, frozen);
  5059. body.paintInsertColumns(index, numberOfColumns, frozen);
  5060. footer.paintInsertColumns(index, numberOfColumns, frozen);
  5061. // this needs to be before the scrollbar adjustment.
  5062. boolean scrollbarWasNeeded = horizontalScrollbar
  5063. .getOffsetSize() < horizontalScrollbar.getScrollSize();
  5064. scroller.recalculateScrollbarsForVirtualViewport();
  5065. boolean scrollbarIsNowNeeded = horizontalScrollbar
  5066. .getOffsetSize() < horizontalScrollbar.getScrollSize();
  5067. if (!scrollbarWasNeeded && scrollbarIsNowNeeded) {
  5068. // This might as a side effect move rows around (when scrolled
  5069. // all the way down) and require the DOM to be up to date, i.e.
  5070. // the column to be added
  5071. body.verifyEscalatorCount();
  5072. }
  5073. // fix initial width
  5074. if (header.getRowCount() > 0 || body.getRowCount() > 0
  5075. || footer.getRowCount() > 0) {
  5076. Map<Integer, Double> colWidths = new HashMap<>();
  5077. Double width = Double.valueOf(Column.DEFAULT_COLUMN_WIDTH_PX);
  5078. for (int i = index; i < index + numberOfColumns; i++) {
  5079. Integer col = Integer.valueOf(i);
  5080. colWidths.put(col, width);
  5081. }
  5082. getColumnConfiguration().setColumnWidths(colWidths);
  5083. }
  5084. // Adjust scrollbar
  5085. double pixelsToInsertedColumn = columnConfiguration
  5086. .getCalculatedColumnsWidth(Range.withLength(0, index));
  5087. final boolean columnsWereAddedToTheLeftOfViewport = scroller.lastScrollLeft > pixelsToInsertedColumn;
  5088. if (columnsWereAddedToTheLeftOfViewport) {
  5089. double insertedColumnsWidth = columnConfiguration
  5090. .getCalculatedColumnsWidth(
  5091. Range.withLength(index, numberOfColumns));
  5092. horizontalScrollbar.setScrollPos(
  5093. scroller.lastScrollLeft + insertedColumnsWidth);
  5094. }
  5095. /*
  5096. * Colspans make any kind of automatic clever content re-rendering
  5097. * impossible: As soon as anything has colspans, adding one might
  5098. * affect surrounding colspans, modifying the DOM structure once
  5099. * again, ending in a cascade of updates. Because we don't know how
  5100. * the data is updated.
  5101. *
  5102. * So, instead, we don't do anything. The client code is responsible
  5103. * for re-rendering the content (if so desired). Everything Just
  5104. * Works (TM) if colspans aren't used.
  5105. */
  5106. }
  5107. @Override
  5108. public int getColumnCount() {
  5109. return columns.size();
  5110. }
  5111. @Override
  5112. public void setFrozenColumnCount(int count)
  5113. throws IllegalArgumentException {
  5114. if (count < 0 || count > getColumnCount()) {
  5115. throw new IllegalArgumentException(
  5116. "count must be between 0 and the current number of columns ("
  5117. + getColumnCount() + ")");
  5118. }
  5119. int oldCount = frozenColumns;
  5120. if (count == oldCount) {
  5121. return;
  5122. }
  5123. frozenColumns = count;
  5124. if (hasSomethingInDom()) {
  5125. // Are we freezing or unfreezing?
  5126. boolean frozen = count > oldCount;
  5127. int firstAffectedCol;
  5128. int firstUnaffectedCol;
  5129. if (frozen) {
  5130. firstAffectedCol = oldCount;
  5131. firstUnaffectedCol = count;
  5132. } else {
  5133. firstAffectedCol = count;
  5134. firstUnaffectedCol = oldCount;
  5135. }
  5136. if (oldCount > 0) {
  5137. header.setColumnLastFrozen(oldCount - 1, false);
  5138. body.setColumnLastFrozen(oldCount - 1, false);
  5139. footer.setColumnLastFrozen(oldCount - 1, false);
  5140. }
  5141. if (count > 0) {
  5142. header.setColumnLastFrozen(count - 1, true);
  5143. body.setColumnLastFrozen(count - 1, true);
  5144. footer.setColumnLastFrozen(count - 1, true);
  5145. }
  5146. for (int col = firstAffectedCol; col < firstUnaffectedCol; col++) {
  5147. header.setColumnFrozen(col, frozen);
  5148. body.setColumnFrozen(col, frozen);
  5149. footer.setColumnFrozen(col, frozen);
  5150. }
  5151. }
  5152. scroller.recalculateScrollbarsForVirtualViewport();
  5153. }
  5154. @Override
  5155. public int getFrozenColumnCount() {
  5156. return frozenColumns;
  5157. }
  5158. @Override
  5159. public void setColumnWidth(int index, double px)
  5160. throws IllegalArgumentException {
  5161. setColumnWidths(Collections.singletonMap(Integer.valueOf(index),
  5162. Double.valueOf(px)));
  5163. }
  5164. @Override
  5165. public void setColumnWidths(Map<Integer, Double> indexWidthMap)
  5166. throws IllegalArgumentException {
  5167. if (indexWidthMap == null) {
  5168. throw new IllegalArgumentException("indexWidthMap was null");
  5169. }
  5170. if (indexWidthMap.isEmpty()) {
  5171. return;
  5172. }
  5173. Profiler.enter("Escalator.ColumnConfigurationImpl.setColumnWidths");
  5174. try {
  5175. for (Entry<Integer, Double> entry : indexWidthMap.entrySet()) {
  5176. int index = entry.getKey().intValue();
  5177. double width = entry.getValue().doubleValue();
  5178. checkValidColumnIndex(index);
  5179. // Not all browsers will accept any fractional size..
  5180. width = WidgetUtil.roundSizeDown(width);
  5181. columns.get(index).setWidth(width);
  5182. }
  5183. widthsArray = null;
  5184. header.reapplyColumnWidths();
  5185. body.reapplyColumnWidths();
  5186. footer.reapplyColumnWidths();
  5187. recalculateElementSizes();
  5188. } finally {
  5189. Profiler.leave(
  5190. "Escalator.ColumnConfigurationImpl.setColumnWidths");
  5191. }
  5192. }
  5193. private void checkValidColumnIndex(int index)
  5194. throws IllegalArgumentException {
  5195. if (!Range.withLength(0, getColumnCount()).contains(index)) {
  5196. throw new IllegalArgumentException("The given column index ("
  5197. + index + ") does not exist");
  5198. }
  5199. }
  5200. @Override
  5201. public double getColumnWidth(int index)
  5202. throws IllegalArgumentException {
  5203. checkValidColumnIndex(index);
  5204. return columns.get(index).getDefinedWidth();
  5205. }
  5206. @Override
  5207. public double getColumnWidthActual(int index) {
  5208. return columns.get(index).getCalculatedWidth();
  5209. }
  5210. private double getMaxCellWidth(int colIndex)
  5211. throws IllegalArgumentException {
  5212. double headerWidth = header.measureMinCellWidth(colIndex, true);
  5213. double bodyWidth = body.measureMinCellWidth(colIndex, true);
  5214. double footerWidth = footer.measureMinCellWidth(colIndex, true);
  5215. double maxWidth = Math.max(headerWidth,
  5216. Math.max(bodyWidth, footerWidth));
  5217. if (maxWidth < 0 && header.getRowCount() == 0
  5218. && body.getRowCount() == 0 && footer.getRowCount() == 0) {
  5219. maxWidth = 0;
  5220. }
  5221. assert maxWidth >= 0 : "Got a negative max width for a column, which should be impossible.";
  5222. return maxWidth;
  5223. }
  5224. private double getMinCellWidth(int colIndex)
  5225. throws IllegalArgumentException {
  5226. double headerWidth = header.measureMinCellWidth(colIndex, false);
  5227. double bodyWidth = body.measureMinCellWidth(colIndex, false);
  5228. double footerWidth = footer.measureMinCellWidth(colIndex, false);
  5229. double minWidth = Math.max(headerWidth,
  5230. Math.max(bodyWidth, footerWidth));
  5231. if (minWidth < 0 && header.getRowCount() == 0
  5232. && body.getRowCount() == 0 && footer.getRowCount() == 0) {
  5233. minWidth = 0;
  5234. }
  5235. assert minWidth >= 0 : "Got a negative min width for a column, which should be impossible.";
  5236. return minWidth;
  5237. }
  5238. /**
  5239. * Calculates the width of the columns in a given range.
  5240. *
  5241. * @param columns
  5242. * the columns to calculate
  5243. * @return the total width of the columns in the given
  5244. * <code>columns</code>
  5245. */
  5246. double getCalculatedColumnsWidth(final Range columns) {
  5247. /*
  5248. * This is an assert instead of an exception, since this is an
  5249. * internal method.
  5250. */
  5251. assert columns
  5252. .isSubsetOf(Range.between(0, getColumnCount())) : "Range "
  5253. + "was outside of current column range (i.e.: "
  5254. + Range.between(0, getColumnCount())
  5255. + ", but was given :" + columns;
  5256. double sum = 0;
  5257. for (int i = columns.getStart(); i < columns.getEnd(); i++) {
  5258. double columnWidthActual = getColumnWidthActual(i);
  5259. sum += columnWidthActual;
  5260. }
  5261. return sum;
  5262. }
  5263. double[] getCalculatedColumnWidths() {
  5264. if (widthsArray == null || widthsArray.length != getColumnCount()) {
  5265. widthsArray = new double[getColumnCount()];
  5266. for (int i = 0; i < columns.size(); i++) {
  5267. widthsArray[i] = columns.get(i).getCalculatedWidth();
  5268. }
  5269. }
  5270. return widthsArray;
  5271. }
  5272. @Override
  5273. public void refreshColumns(int index, int numberOfColumns)
  5274. throws IndexOutOfBoundsException, IllegalArgumentException {
  5275. if (numberOfColumns < 1) {
  5276. throw new IllegalArgumentException(
  5277. "Number of columns must be 1 or greater (was "
  5278. + numberOfColumns + ")");
  5279. }
  5280. if (index < 0 || index + numberOfColumns > getColumnCount()) {
  5281. throw new IndexOutOfBoundsException("The given "
  5282. + "column range (" + index + ".."
  5283. + (index + numberOfColumns)
  5284. + ") was outside of the current number of columns ("
  5285. + getColumnCount() + ")");
  5286. }
  5287. header.refreshColumns(index, numberOfColumns);
  5288. body.refreshColumns(index, numberOfColumns);
  5289. footer.refreshColumns(index, numberOfColumns);
  5290. }
  5291. }
  5292. /**
  5293. * A decision on how to measure a spacer when it is partially within a
  5294. * designated range.
  5295. * <p>
  5296. * The meaning of each value may differ depending on the context it is being
  5297. * used in. Check that particular method's JavaDoc.
  5298. */
  5299. private enum SpacerInclusionStrategy {
  5300. /** A representation of "the entire spacer". */
  5301. COMPLETE,
  5302. /** A representation of "a partial spacer". */
  5303. PARTIAL,
  5304. /** A representation of "no spacer at all". */
  5305. NONE
  5306. }
  5307. private class SpacerContainer {
  5308. /** This is used mainly for testing purposes */
  5309. private static final String SPACER_LOGICAL_ROW_PROPERTY = "vLogicalRow";
  5310. private final class SpacerImpl implements Spacer {
  5311. private TableCellElement spacerElement;
  5312. private TableRowElement root;
  5313. private DivElement deco;
  5314. private int rowIndex;
  5315. private double height = -1;
  5316. private boolean domHasBeenSetup = false;
  5317. private double decoHeight;
  5318. private double defaultCellBorderBottomSize = -1;
  5319. public SpacerImpl(int rowIndex) {
  5320. this.rowIndex = rowIndex;
  5321. root = TableRowElement.as(DOM.createTR());
  5322. spacerElement = TableCellElement.as(DOM.createTD());
  5323. root.appendChild(spacerElement);
  5324. root.setPropertyInt(SPACER_LOGICAL_ROW_PROPERTY, rowIndex);
  5325. deco = DivElement.as(DOM.createDiv());
  5326. }
  5327. public void setPositionDiff(double x, double y) {
  5328. setPosition(getLeft() + x, getTop() + y);
  5329. }
  5330. public void setupDom(double height) {
  5331. assert !domHasBeenSetup : "DOM can't be set up twice.";
  5332. assert RootPanel.get().getElement().isOrHasChild(
  5333. root) : "Root element should've been attached to the DOM by now.";
  5334. domHasBeenSetup = true;
  5335. getRootElement().getStyle().setWidth(getInnerWidth(), Unit.PX);
  5336. setHeight(height);
  5337. spacerElement
  5338. .setColSpan(getColumnConfiguration().getColumnCount());
  5339. setStylePrimaryName(getStylePrimaryName());
  5340. }
  5341. public TableRowElement getRootElement() {
  5342. return root;
  5343. }
  5344. @Override
  5345. public Element getDecoElement() {
  5346. return deco;
  5347. }
  5348. public void setPosition(double x, double y) {
  5349. positions.set(getRootElement(), x, y);
  5350. positions.set(getDecoElement(), 0,
  5351. y - getSpacerDecoTopOffset());
  5352. }
  5353. private double getSpacerDecoTopOffset() {
  5354. return getBody().getDefaultRowHeight();
  5355. }
  5356. public void setStylePrimaryName(String style) {
  5357. UIObject.setStylePrimaryName(root, style + "-spacer");
  5358. UIObject.setStylePrimaryName(deco, style + "-spacer-deco");
  5359. }
  5360. /**
  5361. * Clear spacer height without moving other contents.
  5362. *
  5363. * @see #setHeight(double)
  5364. */
  5365. private void clearHeight() {
  5366. height = 0;
  5367. root.getStyle().setHeight(0, Unit.PX);
  5368. updateDecoratorGeometry(0);
  5369. }
  5370. public void setHeight(double height) {
  5371. assert height >= 0 : "Height must be more >= 0 (was " + height
  5372. + ")";
  5373. final double heightDiff = height - Math.max(0, this.height);
  5374. final double oldHeight = this.height;
  5375. this.height = height;
  5376. // since the spacer might be rendered on top of the previous
  5377. // rows border (done with css), need to increase height the
  5378. // amount of the border thickness
  5379. if (defaultCellBorderBottomSize < 0) {
  5380. defaultCellBorderBottomSize = WidgetUtil
  5381. .getBorderBottomThickness(body
  5382. .getRowElement(
  5383. getVisibleRowRange().getStart())
  5384. .getFirstChildElement());
  5385. }
  5386. root.getStyle().setHeight(height + defaultCellBorderBottomSize,
  5387. Unit.PX);
  5388. // move the visible spacers getRow row onwards.
  5389. shiftSpacerPositionsAfterRow(getRow(), heightDiff);
  5390. /*
  5391. * If we're growing, we'll adjust the scroll size first, then
  5392. * adjust scrolling. If we're shrinking, we do it after the
  5393. * second if-clause.
  5394. */
  5395. boolean spacerIsGrowing = heightDiff > 0;
  5396. if (spacerIsGrowing) {
  5397. verticalScrollbar.setScrollSize(
  5398. verticalScrollbar.getScrollSize() + heightDiff);
  5399. }
  5400. /*
  5401. * Don't modify the scrollbars if we're expanding the -1 spacer
  5402. * while we're scrolled to the top.
  5403. */
  5404. boolean minusOneSpacerException = spacerIsGrowing
  5405. && getRow() == -1 && body.getTopRowLogicalIndex() == 0;
  5406. boolean viewportNeedsScrolling = getRow() < body
  5407. .getTopRowLogicalIndex() && !minusOneSpacerException;
  5408. if (viewportNeedsScrolling) {
  5409. /*
  5410. * We can't use adjustScrollPos here, probably because of a
  5411. * bookkeeping-related race condition.
  5412. *
  5413. * This particular situation is easier, however, since we
  5414. * know exactly how many pixels we need to move (heightDiff)
  5415. * and all elements below the spacer always need to move
  5416. * that pixel amount.
  5417. */
  5418. for (TableRowElement row : body.visualRowOrder) {
  5419. body.setRowPosition(row, 0,
  5420. body.getRowTop(row) + heightDiff);
  5421. }
  5422. double top = getTop();
  5423. double bottom = top + oldHeight;
  5424. double scrollTop = verticalScrollbar.getScrollPos();
  5425. boolean viewportTopIsAtMidSpacer = top < scrollTop
  5426. && scrollTop < bottom;
  5427. final double moveDiff;
  5428. if (viewportTopIsAtMidSpacer && !spacerIsGrowing) {
  5429. /*
  5430. * If the scroll top is in the middle of the modified
  5431. * spacer, we want to scroll the viewport up as usual,
  5432. * but we don't want to scroll past the top of it.
  5433. *
  5434. * Math.max ensures this (remember: the result is going
  5435. * to be negative).
  5436. */
  5437. moveDiff = Math.max(heightDiff, top - scrollTop);
  5438. } else {
  5439. moveDiff = heightDiff;
  5440. }
  5441. body.setBodyScrollPosition(tBodyScrollLeft,
  5442. tBodyScrollTop + moveDiff);
  5443. verticalScrollbar.setScrollPosByDelta(moveDiff);
  5444. } else {
  5445. body.shiftRowPositions(getRow(), heightDiff);
  5446. }
  5447. if (!spacerIsGrowing) {
  5448. verticalScrollbar.setScrollSize(
  5449. verticalScrollbar.getScrollSize() + heightDiff);
  5450. }
  5451. updateDecoratorGeometry(height);
  5452. }
  5453. /** Resizes and places the decorator. */
  5454. private void updateDecoratorGeometry(double detailsHeight) {
  5455. Style style = deco.getStyle();
  5456. decoHeight = detailsHeight + getBody().getDefaultRowHeight();
  5457. style.setHeight(decoHeight, Unit.PX);
  5458. }
  5459. @Override
  5460. public Element getElement() {
  5461. return spacerElement;
  5462. }
  5463. @Override
  5464. public int getRow() {
  5465. return rowIndex;
  5466. }
  5467. public double getHeight() {
  5468. assert height >= 0 : "Height was not previously set by setHeight.";
  5469. return height;
  5470. }
  5471. public double getTop() {
  5472. return positions.getTop(getRootElement());
  5473. }
  5474. public double getLeft() {
  5475. return positions.getLeft(getRootElement());
  5476. }
  5477. /**
  5478. * Sets a new row index for this spacer. Also updates the
  5479. * bookkeeping at {@link SpacerContainer#rowIndexToSpacer}.
  5480. */
  5481. @SuppressWarnings("boxing")
  5482. public void setRowIndex(int rowIndex) {
  5483. SpacerImpl spacer = rowIndexToSpacer.remove(this.rowIndex);
  5484. assert this == spacer : "trying to move an unexpected spacer.";
  5485. int oldIndex = this.rowIndex;
  5486. this.rowIndex = rowIndex;
  5487. root.setPropertyInt(SPACER_LOGICAL_ROW_PROPERTY, rowIndex);
  5488. rowIndexToSpacer.put(this.rowIndex, this);
  5489. fireEvent(new SpacerIndexChangedEvent(oldIndex, this.rowIndex));
  5490. }
  5491. /**
  5492. * Updates the spacer's visibility parameters, based on whether it
  5493. * is being currently visible or not.
  5494. *
  5495. * @deprecated Escalator no longer uses this logic at initialisation
  5496. * as there can only be a limited number of spacers and
  5497. * hidden spacers within visual range interfere with
  5498. * position calculations.
  5499. */
  5500. @Deprecated
  5501. public void updateVisibility() {
  5502. if (isInViewport()) {
  5503. show();
  5504. } else {
  5505. hide();
  5506. }
  5507. }
  5508. private boolean isInViewport() {
  5509. int top = (int) Math.ceil(getTop());
  5510. int height = (int) Math.floor(getHeight());
  5511. Range location = Range.withLength(top, height);
  5512. return getViewportPixels().intersects(location);
  5513. }
  5514. public void show() {
  5515. getRootElement().getStyle().clearDisplay();
  5516. getDecoElement().getStyle().clearDisplay();
  5517. fireEvent(new SpacerVisibilityChangedEvent(getRow(), true));
  5518. }
  5519. public void hide() {
  5520. getRootElement().getStyle().setDisplay(Display.NONE);
  5521. getDecoElement().getStyle().setDisplay(Display.NONE);
  5522. fireEvent(new SpacerVisibilityChangedEvent(getRow(), false));
  5523. }
  5524. /**
  5525. * Crop the decorator element so that it doesn't overlap the header
  5526. * and footer sections.
  5527. *
  5528. * @param bodyTop
  5529. * the top cordinate of the escalator body
  5530. * @param bodyBottom
  5531. * the bottom cordinate of the escalator body
  5532. * @param decoWidth
  5533. * width of the deco
  5534. */
  5535. private void updateDecoClip(final double bodyTop,
  5536. final double bodyBottom, final double decoWidth) {
  5537. final int top = deco.getAbsoluteTop();
  5538. final int bottom = deco.getAbsoluteBottom();
  5539. /*
  5540. * FIXME
  5541. *
  5542. * Height and its use is a workaround for the issue where
  5543. * coordinates of the deco are not calculated yet. This will
  5544. * prevent a deco from being displayed when it's added to DOM
  5545. */
  5546. final int height = bottom - top;
  5547. if (top < bodyTop || bottom > bodyBottom) {
  5548. final double topClip = Math.max(0.0D, bodyTop - top);
  5549. final double bottomClip = height
  5550. - Math.max(0.0D, bottom - bodyBottom);
  5551. // TODO [optimize] not sure how GWT compiles this
  5552. final String clip = new StringBuilder("rect(")
  5553. .append(topClip).append("px,").append(decoWidth)
  5554. .append("px,").append(bottomClip).append("px,0)")
  5555. .toString();
  5556. deco.getStyle().setProperty("clip", clip);
  5557. } else {
  5558. deco.getStyle().setProperty("clip", "auto");
  5559. }
  5560. }
  5561. }
  5562. private final TreeMap<Integer, SpacerImpl> rowIndexToSpacer = new TreeMap<>();
  5563. private SpacerUpdater spacerUpdater = SpacerUpdater.NULL;
  5564. private final ScrollHandler spacerScroller = new ScrollHandler() {
  5565. private double prevScrollX = 0;
  5566. @Override
  5567. public void onScroll(ScrollEvent event) {
  5568. if (WidgetUtil.pixelValuesEqual(getScrollLeft(), prevScrollX)) {
  5569. return;
  5570. }
  5571. prevScrollX = getScrollLeft();
  5572. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  5573. spacer.setPosition(prevScrollX, spacer.getTop());
  5574. }
  5575. }
  5576. };
  5577. private HandlerRegistration spacerScrollerRegistration;
  5578. /** Width of the spacers' decos. Calculated once then cached. */
  5579. private double spacerDecoWidth = 0.0D;
  5580. public void setSpacer(int rowIndex, double height)
  5581. throws IllegalArgumentException {
  5582. if (rowIndex < -1 || rowIndex >= getBody().getRowCount()) {
  5583. throw new IllegalArgumentException("invalid row index: "
  5584. + rowIndex + ", while the body only has "
  5585. + getBody().getRowCount() + " rows.");
  5586. }
  5587. if (height >= 0) {
  5588. if (!spacerExists(rowIndex)) {
  5589. insertNewSpacer(rowIndex, height);
  5590. } else {
  5591. updateExistingSpacer(rowIndex, height);
  5592. }
  5593. } else if (spacerExists(rowIndex)) {
  5594. removeSpacer(rowIndex);
  5595. }
  5596. updateSpacerDecosVisibility();
  5597. }
  5598. /** Checks if a given element is a spacer element */
  5599. public boolean isSpacer(Element row) {
  5600. /*
  5601. * If this needs optimization, we could do a more heuristic check
  5602. * based on stylenames and stuff, instead of iterating through the
  5603. * map.
  5604. */
  5605. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  5606. if (spacer.getRootElement().equals(row)) {
  5607. return true;
  5608. }
  5609. }
  5610. return false;
  5611. }
  5612. @SuppressWarnings("boxing")
  5613. void scrollToSpacer(int spacerIndex, ScrollDestination destination,
  5614. int padding) {
  5615. assert !destination.equals(ScrollDestination.MIDDLE)
  5616. || padding != 0 : "destination/padding check should be done before this method";
  5617. body.scrollToRowSpacerOrBoth(spacerIndex, destination, padding,
  5618. ScrollType.SPACER);
  5619. }
  5620. public void reapplySpacerWidths() {
  5621. // FIXME #16266 , spacers get couple pixels too much because borders
  5622. final double width = getInnerWidth() - spacerDecoWidth;
  5623. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  5624. spacer.getRootElement().getStyle().setWidth(width, Unit.PX);
  5625. }
  5626. }
  5627. /**
  5628. * @deprecated This method is no longer used by Escalator and is likely
  5629. * to be removed soon.
  5630. *
  5631. * @param removedRowsRange
  5632. */
  5633. @Deprecated
  5634. public void paintRemoveSpacers(Range removedRowsRange) {
  5635. removeSpacers(removedRowsRange);
  5636. shiftSpacersByRows(removedRowsRange.getStart(),
  5637. -removedRowsRange.length());
  5638. }
  5639. /**
  5640. * Removes spacers of the given range without moving other contents.
  5641. * <p>
  5642. * NOTE: Changed functionality since 8.9. Previous incarnation of this
  5643. * method updated the positions of all the contents below the first
  5644. * removed spacer.
  5645. *
  5646. * @param removedRange
  5647. * logical range of spacers to remove
  5648. */
  5649. @SuppressWarnings("boxing")
  5650. public void removeSpacers(Range removedRange) {
  5651. Map<Integer, SpacerImpl> removedSpacers = rowIndexToSpacer.subMap(
  5652. removedRange.getStart(), true, removedRange.getEnd(),
  5653. false);
  5654. if (removedSpacers.isEmpty()) {
  5655. return;
  5656. }
  5657. double specialSpacerHeight = removedRange.contains(-1)
  5658. ? getSpacerHeight(-1)
  5659. : 0;
  5660. for (Entry<Integer, SpacerImpl> entry : removedSpacers.entrySet()) {
  5661. SpacerImpl spacer = entry.getValue();
  5662. rowIndexToSpacer.remove(entry.getKey());
  5663. destroySpacerContent(spacer);
  5664. spacer.clearHeight();
  5665. spacer.getRootElement().removeFromParent();
  5666. spacer.getDecoElement().removeFromParent();
  5667. }
  5668. removedSpacers.clear();
  5669. if (rowIndexToSpacer.isEmpty()) {
  5670. assert spacerScrollerRegistration != null : "Spacer scroller registration was null";
  5671. spacerScrollerRegistration.removeHandler();
  5672. spacerScrollerRegistration = null;
  5673. }
  5674. // if a rowless spacer at the top got removed, all rows and spacers
  5675. // need to be moved up accordingly
  5676. if (!WidgetUtil.pixelValuesEqual(specialSpacerHeight, 0)) {
  5677. double scrollDiff = Math.min(specialSpacerHeight,
  5678. getScrollTop());
  5679. body.moveViewportAndContent(null, -specialSpacerHeight,
  5680. -specialSpacerHeight, -scrollDiff);
  5681. }
  5682. }
  5683. public Map<Integer, SpacerImpl> getSpacers() {
  5684. return new HashMap<>(rowIndexToSpacer);
  5685. }
  5686. /**
  5687. * Calculates the sum of all spacers.
  5688. *
  5689. * @return sum of all spacers, or 0 if no spacers present
  5690. */
  5691. public double getSpacerHeightsSum() {
  5692. return getHeights(rowIndexToSpacer.values());
  5693. }
  5694. /**
  5695. * Calculates the sum of all spacers from one row index onwards.
  5696. *
  5697. * @param logicalRowIndex
  5698. * the spacer to include as the first calculated spacer
  5699. * @return the sum of all spacers from {@code logicalRowIndex} and
  5700. * onwards, or 0 if no suitable spacers were found
  5701. */
  5702. @SuppressWarnings("boxing")
  5703. public Collection<SpacerImpl> getSpacersForRowAndAfter(
  5704. int logicalRowIndex) {
  5705. return new ArrayList<>(
  5706. rowIndexToSpacer.tailMap(logicalRowIndex, true).values());
  5707. }
  5708. /**
  5709. * Get all spacers from one pixel point onwards.
  5710. * <p>
  5711. *
  5712. * In this method, the {@link SpacerInclusionStrategy} has the following
  5713. * meaning when a spacer lies in the middle of either pixel argument:
  5714. * <dl>
  5715. * <dt>{@link SpacerInclusionStrategy#COMPLETE COMPLETE}
  5716. * <dd>include the spacer
  5717. * <dt>{@link SpacerInclusionStrategy#PARTIAL PARTIAL}
  5718. * <dd>include the spacer
  5719. * <dt>{@link SpacerInclusionStrategy#NONE NONE}
  5720. * <dd>ignore the spacer
  5721. * </dl>
  5722. *
  5723. * @param px
  5724. * the pixel point after which to return all spacers
  5725. * @param strategy
  5726. * the inclusion strategy regarding the {@code px}
  5727. * @return a collection of the spacers that exist after {@code px}
  5728. */
  5729. public Collection<SpacerImpl> getSpacersAfterPx(final double px,
  5730. final SpacerInclusionStrategy strategy) {
  5731. List<SpacerImpl> spacers = new ArrayList<>(
  5732. rowIndexToSpacer.values());
  5733. for (int i = 0; i < spacers.size(); i++) {
  5734. SpacerImpl spacer = spacers.get(i);
  5735. double top = spacer.getTop();
  5736. double bottom = top + spacer.getHeight();
  5737. if (top > px) {
  5738. return spacers.subList(i, spacers.size());
  5739. } else if (bottom > px) {
  5740. if (strategy == SpacerInclusionStrategy.NONE) {
  5741. return spacers.subList(i + 1, spacers.size());
  5742. } else {
  5743. return spacers.subList(i, spacers.size());
  5744. }
  5745. }
  5746. }
  5747. return Collections.emptySet();
  5748. }
  5749. /**
  5750. * Gets the spacers currently rendered in the DOM.
  5751. *
  5752. * @return an unmodifiable (but live) collection of the spacers
  5753. * currently in the DOM
  5754. */
  5755. public Collection<SpacerImpl> getSpacersInDom() {
  5756. return Collections
  5757. .unmodifiableCollection(rowIndexToSpacer.values());
  5758. }
  5759. /**
  5760. * Gets the amount of pixels occupied by spacers between two pixel
  5761. * points.
  5762. * <p>
  5763. * In this method, the {@link SpacerInclusionStrategy} has the following
  5764. * meaning when a spacer lies in the middle of either pixel argument:
  5765. * <dl>
  5766. * <dt>{@link SpacerInclusionStrategy#COMPLETE COMPLETE}
  5767. * <dd>take the entire spacer into account
  5768. * <dt>{@link SpacerInclusionStrategy#PARTIAL PARTIAL}
  5769. * <dd>take only the visible area into account
  5770. * <dt>{@link SpacerInclusionStrategy#NONE NONE}
  5771. * <dd>ignore that spacer
  5772. * </dl>
  5773. *
  5774. * @param rangeTop
  5775. * the top pixel point
  5776. * @param topInclusion
  5777. * the inclusion strategy regarding {@code rangeTop}.
  5778. * @param rangeBottom
  5779. * the bottom pixel point
  5780. * @param bottomInclusion
  5781. * the inclusion strategy regarding {@code rangeBottom}.
  5782. * @return the pixels occupied by spacers between {@code rangeTop} and
  5783. * {@code rangeBottom}
  5784. */
  5785. public double getSpacerHeightsSumBetweenPx(double rangeTop,
  5786. SpacerInclusionStrategy topInclusion, double rangeBottom,
  5787. SpacerInclusionStrategy bottomInclusion) {
  5788. assert rangeTop <= rangeBottom : "rangeTop must be less than rangeBottom";
  5789. double heights = 0;
  5790. /*
  5791. * TODO [[optimize]]: this might be somewhat inefficient (due to
  5792. * iterator-based scanning, instead of using the treemap's search
  5793. * functionalities). But it should be easy to write, read, verify
  5794. * and maintain.
  5795. */
  5796. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  5797. double top = spacer.getTop();
  5798. double height = spacer.getHeight();
  5799. double bottom = top + height;
  5800. /*
  5801. * If we happen to implement a DoubleRange (in addition to the
  5802. * int-based Range) at some point, the following logic should
  5803. * probably be converted into using the
  5804. * Range.partitionWith-equivalent.
  5805. */
  5806. boolean topIsAboveRange = top < rangeTop;
  5807. boolean topIsInRange = rangeTop <= top && top <= rangeBottom;
  5808. boolean topIsBelowRange = rangeBottom < top;
  5809. boolean bottomIsAboveRange = bottom < rangeTop;
  5810. boolean bottomIsInRange = rangeTop <= bottom
  5811. && bottom <= rangeBottom;
  5812. boolean bottomIsBelowRange = rangeBottom < bottom;
  5813. assert topIsAboveRange ^ topIsBelowRange
  5814. ^ topIsInRange : "Bad top logic";
  5815. assert bottomIsAboveRange ^ bottomIsBelowRange
  5816. ^ bottomIsInRange : "Bad bottom logic";
  5817. if (bottomIsAboveRange) {
  5818. continue;
  5819. } else if (topIsBelowRange) {
  5820. return heights;
  5821. } else if (topIsAboveRange && bottomIsInRange) {
  5822. switch (topInclusion) {
  5823. case PARTIAL:
  5824. heights += bottom - rangeTop;
  5825. break;
  5826. case COMPLETE:
  5827. heights += height;
  5828. break;
  5829. default:
  5830. break;
  5831. }
  5832. } else if (topIsAboveRange && bottomIsBelowRange) {
  5833. /*
  5834. * Here we arbitrarily decide that the top inclusion will
  5835. * have the honor of overriding the bottom inclusion if
  5836. * happens to be a conflict of interests.
  5837. */
  5838. switch (topInclusion) {
  5839. case NONE:
  5840. return 0;
  5841. case COMPLETE:
  5842. return height;
  5843. case PARTIAL:
  5844. return rangeBottom - rangeTop;
  5845. default:
  5846. throw new IllegalArgumentException(
  5847. "Unexpected inclusion state :" + topInclusion);
  5848. }
  5849. } else if (topIsInRange && bottomIsInRange) {
  5850. heights += height;
  5851. } else if (topIsInRange && bottomIsBelowRange) {
  5852. switch (bottomInclusion) {
  5853. case PARTIAL:
  5854. heights += rangeBottom - top;
  5855. break;
  5856. case COMPLETE:
  5857. heights += height;
  5858. break;
  5859. default:
  5860. break;
  5861. }
  5862. return heights;
  5863. } else {
  5864. assert false : "Unnaccounted-for situation";
  5865. }
  5866. }
  5867. return heights;
  5868. }
  5869. /**
  5870. * Gets the amount of pixels occupied by spacers from the top until a
  5871. * certain spot from the top of the body.
  5872. *
  5873. * @param px
  5874. * pixels counted from the top
  5875. * @return the pixels occupied by spacers up until {@code px}
  5876. */
  5877. public double getSpacerHeightsSumUntilPx(double px) {
  5878. return getSpacerHeightsSumBetweenPx(0,
  5879. SpacerInclusionStrategy.PARTIAL, px,
  5880. SpacerInclusionStrategy.PARTIAL);
  5881. }
  5882. /**
  5883. * Gets the amount of pixels occupied by spacers until a logical row
  5884. * index. The spacer of the row corresponding with the given index isn't
  5885. * included.
  5886. *
  5887. * @param logicalIndex
  5888. * a logical row index
  5889. * @return the pixels occupied by spacers up until {@code logicalIndex}
  5890. */
  5891. @SuppressWarnings("boxing")
  5892. public double getSpacerHeightsSumUntilIndex(int logicalIndex) {
  5893. return getHeights(
  5894. rowIndexToSpacer.headMap(logicalIndex, false).values());
  5895. }
  5896. private double getHeights(Collection<SpacerImpl> spacers) {
  5897. double heights = 0;
  5898. for (SpacerImpl spacer : spacers) {
  5899. heights += spacer.getHeight();
  5900. }
  5901. return heights;
  5902. }
  5903. /**
  5904. * Gets the height of the spacer for a row index.
  5905. *
  5906. * @param rowIndex
  5907. * the index of the row where the spacer should be
  5908. * @return the height of the spacer at index {@code rowIndex}, or 0 if
  5909. * there is no spacer there
  5910. */
  5911. public double getSpacerHeight(int rowIndex) {
  5912. SpacerImpl spacer = getSpacer(rowIndex);
  5913. if (spacer != null) {
  5914. return spacer.getHeight();
  5915. } else {
  5916. return 0;
  5917. }
  5918. }
  5919. private boolean spacerExists(int rowIndex) {
  5920. return rowIndexToSpacer.containsKey(Integer.valueOf(rowIndex));
  5921. }
  5922. @SuppressWarnings("boxing")
  5923. private void insertNewSpacer(int rowIndex, double height) {
  5924. if (spacerScrollerRegistration == null) {
  5925. spacerScrollerRegistration = addScrollHandler(spacerScroller);
  5926. }
  5927. final SpacerImpl spacer = new SpacerImpl(rowIndex);
  5928. rowIndexToSpacer.put(rowIndex, spacer);
  5929. // set the position before adding it to DOM
  5930. positions.set(spacer.getRootElement(), getScrollLeft(),
  5931. calculateSpacerTop(rowIndex));
  5932. TableRowElement spacerRoot = spacer.getRootElement();
  5933. spacerRoot.getStyle()
  5934. .setWidth(columnConfiguration.calculateRowWidth(), Unit.PX);
  5935. body.getElement().appendChild(spacerRoot);
  5936. spacer.setupDom(height);
  5937. // set the deco position, requires that spacer is in the DOM
  5938. positions.set(spacer.getDecoElement(), 0,
  5939. spacer.getTop() - spacer.getSpacerDecoTopOffset());
  5940. spacerDecoContainer.appendChild(spacer.getDecoElement());
  5941. if (spacerDecoContainer.getParentElement() == null) {
  5942. getElement().appendChild(spacerDecoContainer);
  5943. // calculate the spacer deco width, it won't change
  5944. spacerDecoWidth = getBoundingWidth(spacer.getDecoElement());
  5945. }
  5946. initSpacerContent(spacer);
  5947. // schedule updating of the physical indexes
  5948. body.domSorter.reschedule();
  5949. }
  5950. private void updateExistingSpacer(int rowIndex, double newHeight) {
  5951. getSpacer(rowIndex).setHeight(newHeight);
  5952. }
  5953. public SpacerImpl getSpacer(int rowIndex) {
  5954. return rowIndexToSpacer.get(Integer.valueOf(rowIndex));
  5955. }
  5956. private void removeSpacer(int rowIndex) {
  5957. removeSpacers(Range.withOnly(rowIndex));
  5958. }
  5959. public void setStylePrimaryName(String style) {
  5960. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  5961. spacer.setStylePrimaryName(style);
  5962. }
  5963. }
  5964. public void setSpacerUpdater(SpacerUpdater spacerUpdater)
  5965. throws IllegalArgumentException {
  5966. if (spacerUpdater == null) {
  5967. throw new IllegalArgumentException(
  5968. "spacer updater cannot be null");
  5969. }
  5970. destroySpacerContent(rowIndexToSpacer.values());
  5971. this.spacerUpdater = spacerUpdater;
  5972. initSpacerContent(rowIndexToSpacer.values());
  5973. }
  5974. public SpacerUpdater getSpacerUpdater() {
  5975. return spacerUpdater;
  5976. }
  5977. private void destroySpacerContent(Iterable<SpacerImpl> spacers) {
  5978. for (SpacerImpl spacer : spacers) {
  5979. destroySpacerContent(spacer);
  5980. }
  5981. }
  5982. private void destroySpacerContent(SpacerImpl spacer) {
  5983. assert getElement().isOrHasChild(spacer
  5984. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before detaching";
  5985. assert getElement().isOrHasChild(spacer
  5986. .getElement()) : "Spacer element somehow got detached from Escalator before detaching";
  5987. spacerUpdater.destroy(spacer);
  5988. assert getElement().isOrHasChild(spacer
  5989. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before detaching";
  5990. assert getElement().isOrHasChild(spacer
  5991. .getElement()) : "Spacer element somehow got detached from Escalator before detaching";
  5992. }
  5993. private void initSpacerContent(Iterable<SpacerImpl> spacers) {
  5994. for (SpacerImpl spacer : spacers) {
  5995. initSpacerContent(spacer);
  5996. }
  5997. }
  5998. private void initSpacerContent(SpacerImpl spacer) {
  5999. assert getElement().isOrHasChild(spacer
  6000. .getRootElement()) : "Spacer's root element somehow got detached from Escalator before attaching";
  6001. assert getElement().isOrHasChild(spacer
  6002. .getElement()) : "Spacer element somehow got detached from Escalator before attaching";
  6003. spacerUpdater.init(spacer);
  6004. assert getElement().isOrHasChild(spacer
  6005. .getRootElement()) : "Spacer's root element somehow got detached from Escalator during attaching";
  6006. assert getElement().isOrHasChild(spacer
  6007. .getElement()) : "Spacer element somehow got detached from Escalator during attaching";
  6008. spacer.show();
  6009. }
  6010. public String getSubPartName(Element subElement) {
  6011. for (SpacerImpl spacer : rowIndexToSpacer.values()) {
  6012. if (spacer.getRootElement().isOrHasChild(subElement)) {
  6013. return "spacer[" + spacer.getRow() + "]";
  6014. }
  6015. }
  6016. return null;
  6017. }
  6018. public Element getSubPartElement(int index) {
  6019. SpacerImpl spacer = rowIndexToSpacer.get(Integer.valueOf(index));
  6020. if (spacer != null) {
  6021. return spacer.getElement();
  6022. } else {
  6023. return null;
  6024. }
  6025. }
  6026. private double calculateSpacerTop(int logicalIndex) {
  6027. return body.getRowTop(logicalIndex) + body.getDefaultRowHeight();
  6028. }
  6029. @SuppressWarnings("boxing")
  6030. private void shiftSpacerPositionsAfterRow(int changedRowIndex,
  6031. double diffPx) {
  6032. for (SpacerImpl spacer : rowIndexToSpacer
  6033. .tailMap(changedRowIndex, false).values()) {
  6034. spacer.setPositionDiff(0, diffPx);
  6035. }
  6036. }
  6037. /**
  6038. * Shifts spacers at and after a specific row by an amount of rows that
  6039. * don't contain spacers of their own.
  6040. * <p>
  6041. * This moves both their associated logical row index and also their
  6042. * visual placement.
  6043. * <p>
  6044. * <em>Note:</em> This method does not check for the validity of any
  6045. * arguments.
  6046. *
  6047. * @param index
  6048. * the index of first row to move
  6049. * @param numberOfRows
  6050. * the number of rows to shift the spacers with. A positive
  6051. * value is downwards, a negative value is upwards.
  6052. */
  6053. public void shiftSpacersByRows(int index, int numberOfRows) {
  6054. final double pxDiff = numberOfRows * body.getDefaultRowHeight();
  6055. List<SpacerContainer.SpacerImpl> spacers = new ArrayList<>(
  6056. getSpacersForRowAndAfter(index));
  6057. if (numberOfRows < 0) {
  6058. for (SpacerContainer.SpacerImpl spacer : spacers) {
  6059. spacer.setPositionDiff(0, pxDiff);
  6060. spacer.setRowIndex(spacer.getRow() + numberOfRows);
  6061. }
  6062. } else {
  6063. for (int i = spacers.size() - 1; i >= 0; --i) {
  6064. SpacerContainer.SpacerImpl spacer = spacers.get(i);
  6065. spacer.setPositionDiff(0, pxDiff);
  6066. spacer.setRowIndex(spacer.getRow() + numberOfRows);
  6067. }
  6068. }
  6069. }
  6070. /**
  6071. * Update the associated logical row indexes for spacers without moving
  6072. * their actual positions.
  6073. * <p>
  6074. * <em>Note:</em> This method does not check for the validity of any
  6075. * arguments.
  6076. *
  6077. * @param startIndex
  6078. * the previous logical index of first row to update
  6079. * @param endIndex
  6080. * the previous logical index of first row that doesn't need
  6081. * updating anymore
  6082. * @param numberOfRows
  6083. * the number of rows to shift the associated logical index
  6084. * with. A positive value is downwards, a negative value is
  6085. * upwards.
  6086. */
  6087. private void updateSpacerIndexesForRowAndAfter(int startIndex,
  6088. int endIndex, int numberOfRows) {
  6089. List<SpacerContainer.SpacerImpl> spacers = new ArrayList<>(
  6090. getSpacersForRowAndAfter(startIndex));
  6091. spacers.removeAll(getSpacersForRowAndAfter(endIndex));
  6092. if (numberOfRows < 0) {
  6093. for (SpacerContainer.SpacerImpl spacer : spacers) {
  6094. spacer.setRowIndex(spacer.getRow() + numberOfRows);
  6095. }
  6096. } else {
  6097. for (int i = spacers.size() - 1; i >= 0; --i) {
  6098. SpacerContainer.SpacerImpl spacer = spacers.get(i);
  6099. spacer.setRowIndex(spacer.getRow() + numberOfRows);
  6100. }
  6101. }
  6102. }
  6103. private void updateSpacerDecosVisibility() {
  6104. final Range visibleRowRange = getVisibleRowRange();
  6105. Collection<SpacerImpl> visibleSpacers = rowIndexToSpacer
  6106. .subMap(visibleRowRange.getStart() - 1,
  6107. visibleRowRange.getEnd() + 1)
  6108. .values();
  6109. if (!visibleSpacers.isEmpty()) {
  6110. final double top = tableWrapper.getAbsoluteTop()
  6111. + header.getHeightOfSection();
  6112. final double bottom = tableWrapper.getAbsoluteBottom()
  6113. - footer.getHeightOfSection();
  6114. for (SpacerImpl spacer : visibleSpacers) {
  6115. spacer.updateDecoClip(top, bottom, spacerDecoWidth);
  6116. }
  6117. }
  6118. }
  6119. }
  6120. private class ElementPositionBookkeeper {
  6121. /**
  6122. * A map containing cached values of an element's current top position.
  6123. */
  6124. private final Map<Element, Double> elementTopPositionMap = new HashMap<>();
  6125. private final Map<Element, Double> elementLeftPositionMap = new HashMap<>();
  6126. public void set(final Element e, final double x, final double y) {
  6127. assert e != null : "Element was null";
  6128. position.set(e, x, y);
  6129. elementTopPositionMap.put(e, Double.valueOf(y));
  6130. elementLeftPositionMap.put(e, Double.valueOf(x));
  6131. }
  6132. public double getTop(final Element e) {
  6133. Double top = elementTopPositionMap.get(e);
  6134. if (top == null) {
  6135. throw new IllegalArgumentException("Element " + e
  6136. + " was not found in the position bookkeeping");
  6137. }
  6138. return top.doubleValue();
  6139. }
  6140. public double getLeft(final Element e) {
  6141. Double left = elementLeftPositionMap.get(e);
  6142. if (left == null) {
  6143. throw new IllegalArgumentException("Element " + e
  6144. + " was not found in the position bookkeeping");
  6145. }
  6146. return left.doubleValue();
  6147. }
  6148. public void remove(Element e) {
  6149. elementTopPositionMap.remove(e);
  6150. elementLeftPositionMap.remove(e);
  6151. }
  6152. }
  6153. /**
  6154. * Utility class for parsing and storing SubPart request string attributes
  6155. * for Grid and Escalator.
  6156. *
  6157. * @since 7.5.0
  6158. */
  6159. public static class SubPartArguments {
  6160. private String type;
  6161. private int[] indices;
  6162. private SubPartArguments(String type, int[] indices) {
  6163. /*
  6164. * The constructor is private so that no third party would by
  6165. * mistake start using this parsing scheme, since it's not official
  6166. * by TestBench (yet?).
  6167. */
  6168. this.type = type;
  6169. this.indices = indices;
  6170. }
  6171. public String getType() {
  6172. return type;
  6173. }
  6174. public int getIndicesLength() {
  6175. return indices.length;
  6176. }
  6177. public int getIndex(int i) {
  6178. return indices[i];
  6179. }
  6180. public int[] getIndices() {
  6181. return Arrays.copyOf(indices, indices.length);
  6182. }
  6183. static SubPartArguments create(String subPart) {
  6184. String[] splitArgs = subPart.split("\\[");
  6185. String type = splitArgs[0];
  6186. int[] indices = new int[splitArgs.length - 1];
  6187. for (int i = 0; i < indices.length; ++i) {
  6188. String tmp = splitArgs[i + 1];
  6189. indices[i] = Integer
  6190. .parseInt(tmp.substring(0, tmp.indexOf("]", 1)));
  6191. }
  6192. return new SubPartArguments(type, indices);
  6193. }
  6194. }
  6195. enum ScrollType {
  6196. ROW, SPACER, ROW_AND_SPACER
  6197. }
  6198. // abs(atan(y/x))*(180/PI) = n deg, x = 1, solve y
  6199. /**
  6200. * The solution to
  6201. * <code>|tan<sup>-1</sup>(<i>x</i>)|&times;(180/&pi;)&nbsp;=&nbsp;30</code>
  6202. * .
  6203. * <p>
  6204. * This constant is placed in the Escalator class, instead of an inner
  6205. * class, since even mathematical expressions aren't allowed in non-static
  6206. * inner classes for constants.
  6207. */
  6208. private static final double RATIO_OF_30_DEGREES = 1 / Math.sqrt(3);
  6209. /**
  6210. * The solution to
  6211. * <code>|tan<sup>-1</sup>(<i>x</i>)|&times;(180/&pi;)&nbsp;=&nbsp;40</code>
  6212. * .
  6213. * <p>
  6214. * This constant is placed in the Escalator class, instead of an inner
  6215. * class, since even mathematical expressions aren't allowed in non-static
  6216. * inner classes for constants.
  6217. */
  6218. private static final double RATIO_OF_40_DEGREES = Math.tan(2 * Math.PI / 9);
  6219. private static final String DEFAULT_WIDTH = "500.0px";
  6220. private static final String DEFAULT_HEIGHT = "400.0px";
  6221. private FlyweightRow flyweightRow = new FlyweightRow();
  6222. /** The {@code <thead/>} tag. */
  6223. private final TableSectionElement headElem = TableSectionElement
  6224. .as(DOM.createTHead());
  6225. /** The {@code <tbody/>} tag. */
  6226. private final TableSectionElement bodyElem = TableSectionElement
  6227. .as(DOM.createTBody());
  6228. /** The {@code <tfoot/>} tag. */
  6229. private final TableSectionElement footElem = TableSectionElement
  6230. .as(DOM.createTFoot());
  6231. /**
  6232. * TODO: investigate whether this field is now unnecessary, as
  6233. * {@link ScrollbarBundle} now caches its values.
  6234. *
  6235. * @deprecated maybe...
  6236. */
  6237. @Deprecated
  6238. private double tBodyScrollTop = 0;
  6239. /**
  6240. * TODO: investigate whether this field is now unnecessary, as
  6241. * {@link ScrollbarBundle} now caches its values.
  6242. *
  6243. * @deprecated maybe...
  6244. */
  6245. @Deprecated
  6246. private double tBodyScrollLeft = 0;
  6247. private final VerticalScrollbarBundle verticalScrollbar = new VerticalScrollbarBundle();
  6248. private final HorizontalScrollbarBundle horizontalScrollbar = new HorizontalScrollbarBundle();
  6249. private final AriaGridHelper ariaGridHelper = new AriaGridHelper();
  6250. private final HeaderRowContainer header = new HeaderRowContainer(headElem);
  6251. private final BodyRowContainerImpl body = new BodyRowContainerImpl(
  6252. bodyElem);
  6253. private final FooterRowContainer footer = new FooterRowContainer(footElem);
  6254. /**
  6255. * Flag for keeping track of {@link RowHeightChangedEvent}s
  6256. */
  6257. private boolean rowHeightChangedEventFired = false;
  6258. private final Scroller scroller = new Scroller();
  6259. private final ColumnConfigurationImpl columnConfiguration = new ColumnConfigurationImpl();
  6260. private final DivElement tableWrapper;
  6261. private final Element table;
  6262. private final DivElement horizontalScrollbarDeco = DivElement
  6263. .as(DOM.createDiv());
  6264. private final DivElement headerDeco = DivElement.as(DOM.createDiv());
  6265. private final DivElement footerDeco = DivElement.as(DOM.createDiv());
  6266. private final DivElement spacerDecoContainer = DivElement
  6267. .as(DOM.createDiv());
  6268. private PositionFunction position;
  6269. /** The cached width of the escalator, in pixels. */
  6270. private double widthOfEscalator = 0;
  6271. /** The cached height of the escalator, in pixels. */
  6272. private double heightOfEscalator = 0;
  6273. /** The height of Escalator in terms of body rows. */
  6274. private double heightByRows = 10.0d;
  6275. /** The height of Escalator, as defined by {@link #setHeight(String)} */
  6276. private String heightByCss = "";
  6277. private HeightMode heightMode = HeightMode.CSS;
  6278. private double delayToCancelTouchScroll = -1;
  6279. private boolean layoutIsScheduled = false;
  6280. private ScheduledCommand layoutCommand = () -> {
  6281. // ensure that row heights have been set or auto-detected if
  6282. // auto-detection is already possible, because visibility changes might
  6283. // not trigger the default check that happens in onLoad()
  6284. header.autodetectRowHeightLater();
  6285. body.autodetectRowHeightLater();
  6286. footer.autodetectRowHeightLater();
  6287. recalculateElementSizes();
  6288. layoutIsScheduled = false;
  6289. };
  6290. private final ElementPositionBookkeeper positions = new ElementPositionBookkeeper();
  6291. /**
  6292. * Creates a new Escalator widget instance.
  6293. */
  6294. public Escalator() {
  6295. detectAndApplyPositionFunction();
  6296. getLogger().info("Using " + position.getClass().getSimpleName()
  6297. + " for position");
  6298. final Element root = DOM.createDiv();
  6299. setElement(root);
  6300. setupScrollbars(root);
  6301. tableWrapper = DivElement.as(DOM.createDiv());
  6302. Event.sinkEvents(tableWrapper, Event.ONSCROLL | Event.KEYEVENTS);
  6303. Event.setEventListener(tableWrapper, event -> {
  6304. if (event.getKeyCode() != KeyCodes.KEY_TAB) {
  6305. return;
  6306. }
  6307. boolean browserScroll = tableWrapper.getScrollLeft() != 0
  6308. || tableWrapper.getScrollTop() != 0;
  6309. boolean keyEvent = event.getType().startsWith("key");
  6310. if (browserScroll || keyEvent) {
  6311. // Browser is scrolling our div automatically, reset
  6312. tableWrapper.setScrollLeft(0);
  6313. tableWrapper.setScrollTop(0);
  6314. Element focused = WidgetUtil.getFocusedElement();
  6315. Stream.of(header, body, footer).forEach(container -> {
  6316. Cell cell = container.getCell(focused);
  6317. if (cell == null) {
  6318. return;
  6319. }
  6320. scrollToColumn(cell.getColumn(), ScrollDestination.ANY, 0);
  6321. if (container == body) {
  6322. scrollToRow(cell.getRow(), ScrollDestination.ANY, 0);
  6323. }
  6324. });
  6325. }
  6326. });
  6327. root.appendChild(tableWrapper);
  6328. table = DOM.createTable();
  6329. tableWrapper.appendChild(table);
  6330. table.appendChild(headElem);
  6331. table.appendChild(bodyElem);
  6332. table.appendChild(footElem);
  6333. Style hCornerStyle = headerDeco.getStyle();
  6334. hCornerStyle.setWidth(verticalScrollbar.getScrollbarThickness(),
  6335. Unit.PX);
  6336. hCornerStyle.setDisplay(Display.NONE);
  6337. root.appendChild(headerDeco);
  6338. Style fCornerStyle = footerDeco.getStyle();
  6339. fCornerStyle.setWidth(verticalScrollbar.getScrollbarThickness(),
  6340. Unit.PX);
  6341. fCornerStyle.setDisplay(Display.NONE);
  6342. root.appendChild(footerDeco);
  6343. Style hWrapperStyle = horizontalScrollbarDeco.getStyle();
  6344. hWrapperStyle.setDisplay(Display.NONE);
  6345. hWrapperStyle.setHeight(horizontalScrollbar.getScrollbarThickness(),
  6346. Unit.PX);
  6347. root.appendChild(horizontalScrollbarDeco);
  6348. setStylePrimaryName("v-escalator");
  6349. spacerDecoContainer.setAttribute("aria-hidden", "true");
  6350. // init default dimensions
  6351. setHeight(null);
  6352. setWidth(null);
  6353. publishJSHelpers(root);
  6354. }
  6355. private double getBoundingWidth(Element element) {
  6356. // Gets the current width, including border and padding, for the element
  6357. // while ignoring any transforms applied to the element (e.g. scale)
  6358. return new ComputedStyle(element).getWidthIncludingBorderPadding();
  6359. }
  6360. private double getBoundingHeight(Element element) {
  6361. // Gets the current height, including border and padding, for the
  6362. // element while ignoring any transforms applied to the element (e.g.
  6363. // scale)
  6364. return new ComputedStyle(element).getHeightIncludingBorderPadding();
  6365. }
  6366. private int getBodyRowCount() {
  6367. return getBody().getRowCount();
  6368. }
  6369. private native void publishJSHelpers(Element root)
  6370. /*-{
  6371. var self = this;
  6372. root.getBodyRowCount = $entry(function () {
  6373. return self.@Escalator::getBodyRowCount()();
  6374. });
  6375. }-*/;
  6376. private void setupScrollbars(final Element root) {
  6377. ScrollHandler scrollHandler = event -> {
  6378. scroller.onScroll();
  6379. fireEvent(new ScrollEvent());
  6380. };
  6381. int scrollbarThickness = WidgetUtil.getNativeScrollbarSize();
  6382. if (BrowserInfo.get().isIE()) {
  6383. /*
  6384. * IE refuses to scroll properly if the DIV isn't at least one pixel
  6385. * larger than the scrollbar controls themselves.
  6386. */
  6387. scrollbarThickness += 1;
  6388. }
  6389. root.appendChild(verticalScrollbar.getElement());
  6390. verticalScrollbar.addScrollHandler(scrollHandler);
  6391. verticalScrollbar.setScrollbarThickness(scrollbarThickness);
  6392. root.appendChild(horizontalScrollbar.getElement());
  6393. horizontalScrollbar.addScrollHandler(scrollHandler);
  6394. horizontalScrollbar.setScrollbarThickness(scrollbarThickness);
  6395. horizontalScrollbar
  6396. .addVisibilityHandler(new ScrollbarBundle.VisibilityHandler() {
  6397. private boolean queued = false;
  6398. @Override
  6399. public void visibilityChanged(
  6400. ScrollbarBundle.VisibilityChangeEvent event) {
  6401. if (queued) {
  6402. return;
  6403. }
  6404. queued = true;
  6405. /*
  6406. * We either lost or gained a scrollbar. In any case, we
  6407. * need to change the height, if it's defined by rows.
  6408. */
  6409. Scheduler.get().scheduleFinally(() -> {
  6410. applyHeightByRows();
  6411. queued = false;
  6412. });
  6413. }
  6414. });
  6415. /*
  6416. * Because of all the IE hacks we've done above, we now have scrollbars
  6417. * hiding underneath a lot of DOM elements.
  6418. *
  6419. * This leads to problems with OSX (and many touch-only devices) when
  6420. * scrollbars are only shown when scrolling, as the scrollbar elements
  6421. * are hidden underneath everything. We trust that the scrollbars behave
  6422. * properly in these situations and simply pop them out with a bit of
  6423. * z-indexing.
  6424. */
  6425. if (WidgetUtil.getNativeScrollbarSize() == 0) {
  6426. verticalScrollbar.getElement().getStyle().setZIndex(90);
  6427. horizontalScrollbar.getElement().getStyle().setZIndex(90);
  6428. }
  6429. }
  6430. @Override
  6431. protected void onLoad() {
  6432. super.onLoad();
  6433. // ensure that row heights have been set or auto-detected if
  6434. // auto-detection is already possible, if not the check will be
  6435. // performed again in layoutCommand
  6436. header.autodetectRowHeightLater();
  6437. body.autodetectRowHeightLater();
  6438. footer.autodetectRowHeightLater();
  6439. header.paintInsertRows(0, header.getRowCount());
  6440. footer.paintInsertRows(0, footer.getRowCount());
  6441. boolean columnsChanged = false;
  6442. for (ColumnConfigurationImpl.Column column : columnConfiguration.columns) {
  6443. boolean columnChanged = column.measureAndSetWidthIfNeeded();
  6444. if (columnChanged) {
  6445. columnsChanged = true;
  6446. }
  6447. }
  6448. if (columnsChanged) {
  6449. header.reapplyColumnWidths();
  6450. body.reapplyColumnWidths();
  6451. footer.reapplyColumnWidths();
  6452. }
  6453. verticalScrollbar.onLoad();
  6454. horizontalScrollbar.onLoad();
  6455. scroller.attachScrollListener(verticalScrollbar.getElement());
  6456. scroller.attachScrollListener(horizontalScrollbar.getElement());
  6457. scroller.attachMousewheelListener(getElement());
  6458. if (isCurrentBrowserIE11OrEdge()) {
  6459. // Touch listeners doesn't work for IE11 and Edge (#18737)
  6460. scroller.attachPointerEventListeners(getElement());
  6461. } else {
  6462. scroller.attachTouchListeners(getElement());
  6463. }
  6464. /*
  6465. * Note: There's no need to explicitly insert rows into the body.
  6466. *
  6467. * recalculateElementSizes will recalculate the height of the body. This
  6468. * has the side-effect that as the body's size grows bigger (i.e. from 0
  6469. * to its actual height), more escalator rows are populated. Those
  6470. * escalator rows are then immediately rendered. This, in effect, is the
  6471. * same thing as inserting those rows.
  6472. *
  6473. * In fact, having an extra paintInsertRows here would lead to duplicate
  6474. * rows.
  6475. */
  6476. recalculateElementSizes();
  6477. }
  6478. @Override
  6479. protected void onUnload() {
  6480. scroller.detachScrollListener(verticalScrollbar.getElement());
  6481. scroller.detachScrollListener(horizontalScrollbar.getElement());
  6482. scroller.detachMousewheelListener(getElement());
  6483. if (isCurrentBrowserIE11OrEdge()) {
  6484. // Touch listeners doesn't work for IE11 and Edge (#18737)
  6485. scroller.detachPointerEventListeners(getElement());
  6486. } else {
  6487. scroller.detachTouchListeners(getElement());
  6488. }
  6489. /*
  6490. * We can call paintRemoveRows here, because static ranges are simple to
  6491. * remove.
  6492. */
  6493. header.paintRemoveRows(0, header.getRowCount());
  6494. footer.paintRemoveRows(0, footer.getRowCount());
  6495. /*
  6496. * We can't call body.paintRemoveRows since it relies on rowCount to be
  6497. * updated correctly. Since it isn't, we'll simply and brutally rip out
  6498. * the DOM elements (in an elegant way, of course).
  6499. */
  6500. int rowsToRemove = body.getDomRowCount();
  6501. for (int i = 0; i < rowsToRemove; i++) {
  6502. int index = rowsToRemove - i - 1;
  6503. TableRowElement tr = bodyElem.getRows().getItem(index);
  6504. body.paintRemoveRow(tr, index);
  6505. positions.remove(tr);
  6506. }
  6507. body.visualRowOrder.clear();
  6508. body.setTopRowLogicalIndex(0);
  6509. super.onUnload();
  6510. }
  6511. private void detectAndApplyPositionFunction() {
  6512. final Style docStyle = Document.get().getBody().getStyle();
  6513. if (hasProperty(docStyle, "transform")) {
  6514. if (hasProperty(docStyle, "transformStyle")) {
  6515. position = new Translate3DPosition();
  6516. } else {
  6517. position = new TranslatePosition();
  6518. }
  6519. } else if (hasProperty(docStyle, "webkitTransform")) {
  6520. position = new WebkitTranslate3DPosition();
  6521. }
  6522. }
  6523. private Logger getLogger() {
  6524. return Logger.getLogger(getClass().getName());
  6525. }
  6526. private static native boolean hasProperty(Style style, String name)
  6527. /*-{
  6528. return style[name] !== undefined;
  6529. }-*/;
  6530. /**
  6531. * Check whether there are both columns and any row data (for either
  6532. * headers, body or footer).
  6533. *
  6534. * @return <code>true</code> if header, body or footer has rows and there
  6535. * are columns
  6536. */
  6537. private boolean hasColumnAndRowData() {
  6538. return (header.getRowCount() > 0 || body.getRowCount() > 0
  6539. || footer.getRowCount() > 0)
  6540. && columnConfiguration.getColumnCount() > 0;
  6541. }
  6542. /**
  6543. * Check whether there are any cells in the DOM.
  6544. *
  6545. * @return <code>true</code> if header, body or footer has any child
  6546. * elements
  6547. */
  6548. private boolean hasSomethingInDom() {
  6549. return headElem.hasChildNodes() || bodyElem.hasChildNodes()
  6550. || footElem.hasChildNodes();
  6551. }
  6552. /**
  6553. * Returns the row container for the header in this Escalator.
  6554. *
  6555. * @return the header. Never <code>null</code>
  6556. */
  6557. public RowContainer getHeader() {
  6558. return header;
  6559. }
  6560. /**
  6561. * Returns the row container for the body in this Escalator.
  6562. *
  6563. * @return the body. Never <code>null</code>
  6564. */
  6565. public BodyRowContainer getBody() {
  6566. return body;
  6567. }
  6568. /**
  6569. * Returns the row container for the footer in this Escalator.
  6570. *
  6571. * @return the footer. Never <code>null</code>
  6572. */
  6573. public RowContainer getFooter() {
  6574. return footer;
  6575. }
  6576. /**
  6577. * Returns the configuration object for the columns in this Escalator.
  6578. *
  6579. * @return the configuration object for the columns in this Escalator. Never
  6580. * <code>null</code>
  6581. */
  6582. public ColumnConfiguration getColumnConfiguration() {
  6583. return columnConfiguration;
  6584. }
  6585. @Override
  6586. public void setWidth(final String width) {
  6587. if (width != null && !width.isEmpty()) {
  6588. super.setWidth(width);
  6589. } else {
  6590. super.setWidth(DEFAULT_WIDTH);
  6591. }
  6592. recalculateElementSizes();
  6593. }
  6594. /**
  6595. * {@inheritDoc}
  6596. * <p>
  6597. * If Escalator is currently not in {@link HeightMode#CSS}, the given value
  6598. * is remembered, and applied once the mode is applied.
  6599. *
  6600. * @see #setHeightMode(HeightMode)
  6601. */
  6602. @Override
  6603. public void setHeight(String height) {
  6604. /*
  6605. * TODO remove method once RequiresResize and the Vaadin layoutmanager
  6606. * listening mechanisms are implemented
  6607. */
  6608. if (height != null && !height.isEmpty()) {
  6609. heightByCss = height;
  6610. } else {
  6611. if (getHeightMode() == HeightMode.UNDEFINED) {
  6612. heightByRows = body.getRowCount();
  6613. applyHeightByRows();
  6614. return;
  6615. } else {
  6616. heightByCss = DEFAULT_HEIGHT;
  6617. }
  6618. }
  6619. if (getHeightMode() == HeightMode.CSS) {
  6620. setHeightInternal(height);
  6621. }
  6622. }
  6623. private void setHeightInternal(final String height) {
  6624. final int escalatorRowsBefore = body.visualRowOrder.size();
  6625. if (height != null && !height.isEmpty()) {
  6626. super.setHeight(height);
  6627. } else {
  6628. if (getHeightMode() == HeightMode.UNDEFINED) {
  6629. int newHeightByRows = body.getRowCount();
  6630. if (heightByRows != newHeightByRows) {
  6631. heightByRows = newHeightByRows;
  6632. applyHeightByRows();
  6633. }
  6634. return;
  6635. } else {
  6636. super.setHeight(DEFAULT_HEIGHT);
  6637. }
  6638. }
  6639. recalculateElementSizes();
  6640. if (escalatorRowsBefore != body.visualRowOrder.size()) {
  6641. fireRowVisibilityChangeEvent();
  6642. }
  6643. }
  6644. /**
  6645. * Returns the vertical scroll offset. Note that this is not necessarily the
  6646. * same as the {@code scrollTop} attribute in the DOM.
  6647. *
  6648. * @return the logical vertical scroll offset
  6649. */
  6650. public double getScrollTop() {
  6651. return verticalScrollbar.getScrollPos();
  6652. }
  6653. /**
  6654. * Sets the vertical scroll offset. Note that this will not necessarily
  6655. * become the same as the {@code scrollTop} attribute in the DOM.
  6656. *
  6657. * @param scrollTop
  6658. * the number of pixels to scroll vertically
  6659. */
  6660. public void setScrollTop(final double scrollTop) {
  6661. verticalScrollbar.setScrollPos(scrollTop);
  6662. }
  6663. /**
  6664. * Returns the logical horizontal scroll offset. Note that this is not
  6665. * necessarily the same as the {@code scrollLeft} attribute in the DOM.
  6666. *
  6667. * @return the logical horizontal scroll offset
  6668. */
  6669. public double getScrollLeft() {
  6670. return horizontalScrollbar.getScrollPos();
  6671. }
  6672. /**
  6673. * Sets the logical horizontal scroll offset. Note that will not necessarily
  6674. * become the same as the {@code scrollLeft} attribute in the DOM.
  6675. *
  6676. * @param scrollLeft
  6677. * the number of pixels to scroll horizontally
  6678. */
  6679. public void setScrollLeft(final double scrollLeft) {
  6680. horizontalScrollbar.setScrollPos(scrollLeft);
  6681. }
  6682. /**
  6683. * Returns the scroll width for the escalator. Note that this is not
  6684. * necessary the same as {@code Element.scrollWidth} in the DOM.
  6685. *
  6686. * @since 7.5.0
  6687. * @return the scroll width in pixels
  6688. */
  6689. public double getScrollWidth() {
  6690. return horizontalScrollbar.getScrollSize();
  6691. }
  6692. /**
  6693. * Returns the scroll height for the escalator. Note that this is not
  6694. * necessary the same as {@code Element.scrollHeight} in the DOM.
  6695. *
  6696. * @since 7.5.0
  6697. * @return the scroll height in pixels
  6698. */
  6699. public double getScrollHeight() {
  6700. return verticalScrollbar.getScrollSize();
  6701. }
  6702. /**
  6703. * Scrolls the body horizontally so that the column at the given index is
  6704. * visible and there is at least {@code padding} pixels in the direction of
  6705. * the given scroll destination.
  6706. *
  6707. * @param columnIndex
  6708. * the index of the column to scroll to
  6709. * @param destination
  6710. * where the column should be aligned visually after scrolling
  6711. * @param padding
  6712. * the number pixels to place between the scrolled-to column and
  6713. * the viewport edge.
  6714. * @throws IndexOutOfBoundsException
  6715. * if {@code columnIndex} is not a valid index for an existing
  6716. * column
  6717. * @throws IllegalArgumentException
  6718. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6719. * and padding is nonzero; or if the indicated column is frozen;
  6720. * or if {@code destination == null}
  6721. */
  6722. public void scrollToColumn(final int columnIndex,
  6723. final ScrollDestination destination, final int padding)
  6724. throws IndexOutOfBoundsException, IllegalArgumentException {
  6725. validateScrollDestination(destination, padding);
  6726. verifyValidColumnIndex(columnIndex);
  6727. if (columnIndex < columnConfiguration.frozenColumns) {
  6728. throw new IllegalArgumentException(
  6729. "The given column index " + columnIndex + " is frozen.");
  6730. }
  6731. scroller.scrollToColumn(columnIndex, destination, padding);
  6732. }
  6733. private void verifyValidColumnIndex(final int columnIndex)
  6734. throws IndexOutOfBoundsException {
  6735. if (columnIndex < 0
  6736. || columnIndex >= columnConfiguration.getColumnCount()) {
  6737. throw new IndexOutOfBoundsException("The given column index "
  6738. + columnIndex + " does not exist.");
  6739. }
  6740. }
  6741. /**
  6742. * Scrolls the body vertically so that the row at the given index is visible
  6743. * and there is at least {@literal padding} pixels to the given scroll
  6744. * destination.
  6745. *
  6746. * @param rowIndex
  6747. * the index of the logical row to scroll to
  6748. * @param destination
  6749. * where the row should be aligned visually after scrolling
  6750. * @param padding
  6751. * the number pixels to place between the scrolled-to row and the
  6752. * viewport edge.
  6753. * @throws IndexOutOfBoundsException
  6754. * if {@code rowIndex} is not a valid index for an existing row
  6755. * @throws IllegalArgumentException
  6756. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6757. * and padding is nonzero; or if {@code destination == null}
  6758. * @see #scrollToRowAndSpacer(int, ScrollDestination, int)
  6759. * @see #scrollToSpacer(int, ScrollDestination, int)
  6760. */
  6761. public void scrollToRow(final int rowIndex,
  6762. final ScrollDestination destination, final int padding)
  6763. throws IndexOutOfBoundsException, IllegalArgumentException {
  6764. verifyValidRowIndex(rowIndex);
  6765. body.scrollToRowSpacerOrBoth(rowIndex, destination, padding,
  6766. ScrollType.ROW);
  6767. }
  6768. private void verifyValidRowIndex(final int rowIndex) {
  6769. if (rowIndex < 0 || rowIndex >= body.getRowCount()) {
  6770. throw new IndexOutOfBoundsException(
  6771. "The given row index " + rowIndex + " does not exist.");
  6772. }
  6773. }
  6774. /**
  6775. * Scrolls the body vertically so that the spacer at the given row index is
  6776. * visible and there is at least {@literal padding} pixels to the given
  6777. * scroll destination.
  6778. *
  6779. * @since 7.5.0
  6780. * @param spacerIndex
  6781. * the row index of the spacer to scroll to
  6782. * @param destination
  6783. * where the spacer should be aligned visually after scrolling
  6784. * @param padding
  6785. * the number of pixels to place between the scrolled-to spacer
  6786. * and the viewport edge
  6787. * @throws IllegalArgumentException
  6788. * if {@code spacerIndex} is not an opened spacer; or if
  6789. * {@code destination} is {@link ScrollDestination#MIDDLE} and
  6790. * padding is nonzero; or if {@code destination == null}
  6791. * @see #scrollToRow(int, ScrollDestination, int)
  6792. * @see #scrollToRowAndSpacer(int, ScrollDestination, int)
  6793. */
  6794. public void scrollToSpacer(final int spacerIndex,
  6795. ScrollDestination destination, final int padding)
  6796. throws IllegalArgumentException {
  6797. body.scrollToRowSpacerOrBoth(spacerIndex, destination, padding,
  6798. ScrollType.SPACER);
  6799. }
  6800. /**
  6801. * Scrolls vertically to a row and the spacer below it.
  6802. * <p>
  6803. * If a spacer is not open at that index, this method behaves like
  6804. * {@link #scrollToRow(int, ScrollDestination, int)}
  6805. *
  6806. * @since 7.5.0
  6807. * @param rowIndex
  6808. * the index of the logical row to scroll to. -1 takes the
  6809. * topmost spacer into account as well.
  6810. * @param destination
  6811. * where the row should be aligned visually after scrolling
  6812. * @param padding
  6813. * the number pixels to place between the scrolled-to row and the
  6814. * viewport edge.
  6815. * @see #scrollToRow(int, ScrollDestination, int)
  6816. * @see #scrollToSpacer(int, ScrollDestination, int)
  6817. * @throws IllegalArgumentException
  6818. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6819. * and {@code padding} is not zero; or if {@code rowIndex} is
  6820. * not a valid row index, or -1; or if
  6821. * {@code destination == null}; or if {@code rowIndex == -1} and
  6822. * there is no spacer open at that index.
  6823. */
  6824. public void scrollToRowAndSpacer(final int rowIndex,
  6825. final ScrollDestination destination, final int padding)
  6826. throws IllegalArgumentException {
  6827. if (rowIndex != -1) {
  6828. verifyValidRowIndex(rowIndex);
  6829. }
  6830. body.scrollToRowSpacerOrBoth(rowIndex, destination, padding,
  6831. ScrollType.ROW_AND_SPACER);
  6832. }
  6833. private static void validateScrollDestination(
  6834. final ScrollDestination destination, final int padding) {
  6835. if (destination == null) {
  6836. throw new IllegalArgumentException("Destination cannot be null");
  6837. }
  6838. if (destination == ScrollDestination.MIDDLE && padding != 0) {
  6839. throw new IllegalArgumentException(
  6840. "You cannot have a padding with a MIDDLE destination");
  6841. }
  6842. }
  6843. /**
  6844. * Recalculates the dimensions for all elements that require manual
  6845. * calculations. Also updates the dimension caches.
  6846. * <p>
  6847. * <em>Note:</em> This method has the <strong>side-effect</strong>
  6848. * automatically makes sure that an appropriate amount of escalator rows are
  6849. * present. So, if the body area grows, more <strong>escalator rows might be
  6850. * inserted</strong>. Conversely, if the body area shrinks,
  6851. * <strong>escalator rows might be removed</strong>.
  6852. */
  6853. private void recalculateElementSizes() {
  6854. if (!isAttached()) {
  6855. return;
  6856. }
  6857. Profiler.enter("Escalator.recalculateElementSizes");
  6858. widthOfEscalator = Math.max(0, getBoundingWidth(getElement()));
  6859. heightOfEscalator = Math.max(0, getBoundingHeight(getElement()));
  6860. header.recalculateSectionHeight();
  6861. body.recalculateSectionHeight();
  6862. footer.recalculateSectionHeight();
  6863. scroller.recalculateScrollbarsForVirtualViewport();
  6864. body.verifyEscalatorCount();
  6865. body.reapplySpacerWidths();
  6866. Profiler.leave("Escalator.recalculateElementSizes");
  6867. }
  6868. /**
  6869. * Snap deltas of x and y to the major four axes (up, down, left, right)
  6870. * with a threshold of a number of degrees from those axes.
  6871. *
  6872. * @param deltaX
  6873. * the delta in the x axis
  6874. * @param deltaY
  6875. * the delta in the y axis
  6876. * @param thresholdRatio
  6877. * the threshold in ratio (0..1) between x and y for when to snap
  6878. * @return a two-element array: <code>[snappedX, snappedY]</code>
  6879. */
  6880. private static double[] snapDeltas(final double deltaX, final double deltaY,
  6881. final double thresholdRatio) {
  6882. final double[] array = new double[2];
  6883. if (deltaX != 0 && deltaY != 0) {
  6884. final double aDeltaX = Math.abs(deltaX);
  6885. final double aDeltaY = Math.abs(deltaY);
  6886. final double yRatio = aDeltaY / aDeltaX;
  6887. final double xRatio = aDeltaX / aDeltaY;
  6888. array[0] = (xRatio < thresholdRatio) ? 0 : deltaX;
  6889. array[1] = (yRatio < thresholdRatio) ? 0 : deltaY;
  6890. } else {
  6891. array[0] = deltaX;
  6892. array[1] = deltaY;
  6893. }
  6894. return array;
  6895. }
  6896. /**
  6897. * Adds an event handler that gets notified when the range of visible rows
  6898. * changes e.g. because of scrolling, row resizing or spacers
  6899. * appearing/disappearing.
  6900. *
  6901. * @param rowVisibilityChangeHandler
  6902. * the event handler
  6903. * @return a handler registration for the added handler
  6904. */
  6905. public HandlerRegistration addRowVisibilityChangeHandler(
  6906. RowVisibilityChangeHandler rowVisibilityChangeHandler) {
  6907. return addHandler(rowVisibilityChangeHandler,
  6908. RowVisibilityChangeEvent.TYPE);
  6909. }
  6910. private void fireRowVisibilityChangeEvent() {
  6911. if (!body.visualRowOrder.isEmpty()) {
  6912. int visibleRangeStart = body.getTopRowLogicalIndex();
  6913. int visibleRowCount = body.visualRowOrder.size();
  6914. fireEvent(new RowVisibilityChangeEvent(visibleRangeStart,
  6915. visibleRowCount));
  6916. } else {
  6917. fireEvent(new RowVisibilityChangeEvent(0, 0));
  6918. }
  6919. }
  6920. /**
  6921. * Gets the logical index range of currently visible rows.
  6922. *
  6923. * @return logical index range of visible rows
  6924. */
  6925. public Range getVisibleRowRange() {
  6926. if (!body.visualRowOrder.isEmpty()) {
  6927. return Range.withLength(body.getTopRowLogicalIndex(),
  6928. body.visualRowOrder.size());
  6929. } else {
  6930. return Range.withLength(0, 0);
  6931. }
  6932. }
  6933. /**
  6934. * Returns the widget from a cell node or <code>null</code> if there is no
  6935. * widget in the cell
  6936. *
  6937. * @param cellNode
  6938. * The cell node
  6939. */
  6940. static Widget getWidgetFromCell(Node cellNode) {
  6941. Node possibleWidgetNode = cellNode.getFirstChild();
  6942. if (possibleWidgetNode != null
  6943. && possibleWidgetNode.getNodeType() == Node.ELEMENT_NODE) {
  6944. @SuppressWarnings("deprecation")
  6945. com.google.gwt.user.client.Element castElement = (com.google.gwt.user.client.Element) possibleWidgetNode
  6946. .cast();
  6947. Widget w = WidgetUtil.findWidget(castElement);
  6948. // Ensure findWidget did not traverse past the cell element in the
  6949. // DOM hierarchy
  6950. if (cellNode.isOrHasChild(w.getElement())) {
  6951. return w;
  6952. }
  6953. }
  6954. return null;
  6955. }
  6956. @Override
  6957. public void setStylePrimaryName(String style) {
  6958. super.setStylePrimaryName(style);
  6959. verticalScrollbar.setStylePrimaryName(style);
  6960. horizontalScrollbar.setStylePrimaryName(style);
  6961. UIObject.setStylePrimaryName(tableWrapper, style + "-tablewrapper");
  6962. UIObject.setStylePrimaryName(headerDeco, style + "-header-deco");
  6963. UIObject.setStylePrimaryName(footerDeco, style + "-footer-deco");
  6964. UIObject.setStylePrimaryName(horizontalScrollbarDeco,
  6965. style + "-horizontal-scrollbar-deco");
  6966. UIObject.setStylePrimaryName(spacerDecoContainer,
  6967. style + "-spacer-deco-container");
  6968. header.setStylePrimaryName(style);
  6969. body.setStylePrimaryName(style);
  6970. footer.setStylePrimaryName(style);
  6971. }
  6972. /**
  6973. * Sets the number of rows that should be visible in Escalator's body, while
  6974. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6975. * <p>
  6976. * If Escalator is currently not in {@link HeightMode#ROW}, the given value
  6977. * is remembered, and applied once the mode is applied.
  6978. *
  6979. * @param rows
  6980. * the number of rows that should be visible in Escalator's body
  6981. * @throws IllegalArgumentException
  6982. * if {@code rows} is &leq; 0, {@link Double#isInfinite(double)
  6983. * infinite} or {@link Double#isNaN(double) NaN}.
  6984. * @see #setHeightMode(HeightMode)
  6985. */
  6986. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6987. if (heightMode == HeightMode.UNDEFINED && body.insertingOrRemoving) {
  6988. // this will be called again once the operation is finished, ignore
  6989. // for now
  6990. return;
  6991. }
  6992. if (rows < 0) {
  6993. throw new IllegalArgumentException(
  6994. "The number of rows must be a positive number.");
  6995. } else if (Double.isInfinite(rows)) {
  6996. throw new IllegalArgumentException(
  6997. "The number of rows must be finite.");
  6998. } else if (Double.isNaN(rows)) {
  6999. throw new IllegalArgumentException("The number must not be NaN.");
  7000. }
  7001. heightByRows = rows;
  7002. applyHeightByRows();
  7003. }
  7004. /**
  7005. * Gets the amount of rows in Escalator's body that are shown, while
  7006. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  7007. * <p>
  7008. * By default, it is 10.
  7009. *
  7010. * @return the amount of rows that are being shown in Escalator's body
  7011. * @see #setHeightByRows(double)
  7012. */
  7013. public double getHeightByRows() {
  7014. return heightByRows;
  7015. }
  7016. /**
  7017. * Reapplies the row-based height of the Grid, if Grid currently should
  7018. * define its height that way.
  7019. */
  7020. private void applyHeightByRows() {
  7021. if (heightMode != HeightMode.ROW
  7022. && heightMode != HeightMode.UNDEFINED) {
  7023. return;
  7024. }
  7025. double headerHeight = header.getHeightOfSection();
  7026. double footerHeight = footer.getHeightOfSection();
  7027. double bodyHeight = body.getDefaultRowHeight() * heightByRows;
  7028. double scrollbar = horizontalScrollbar.showsScrollHandle()
  7029. ? horizontalScrollbar.getScrollbarThickness()
  7030. : 0;
  7031. double spacerHeight = 0; // ignored if HeightMode.ROW
  7032. if (heightMode == HeightMode.UNDEFINED) {
  7033. spacerHeight = body.spacerContainer.getSpacerHeightsSum();
  7034. }
  7035. double totalHeight = headerHeight + bodyHeight + spacerHeight
  7036. + scrollbar + footerHeight;
  7037. setHeightInternal(totalHeight + "px");
  7038. }
  7039. /**
  7040. * Defines the mode in which the Escalator widget's height is calculated.
  7041. * <p>
  7042. * If {@link HeightMode#CSS} is given, Escalator will respect the values
  7043. * given via {@link #setHeight(String)}, and behave as a traditional Widget.
  7044. * <p>
  7045. * If {@link HeightMode#ROW} is given, Escalator will make sure that the
  7046. * {@link #getBody() body} will display as many rows as
  7047. * {@link #getHeightByRows()} defines. <em>Note:</em> If headers/footers are
  7048. * inserted or removed, the widget will resize itself to still display the
  7049. * required amount of rows in its body. It also takes the horizontal
  7050. * scrollbar into account.
  7051. *
  7052. * @param heightMode
  7053. * the mode in to which Escalator should be set
  7054. */
  7055. public void setHeightMode(HeightMode heightMode) {
  7056. /*
  7057. * This method is a workaround for the fact that Vaadin re-applies
  7058. * widget dimensions (height/width) on each state change event. The
  7059. * original design was to have setHeight an setHeightByRow be equals,
  7060. * and whichever was called the latest was considered in effect.
  7061. *
  7062. * But, because of Vaadin always calling setHeight on the widget, this
  7063. * approach doesn't work.
  7064. */
  7065. if (heightMode != this.heightMode) {
  7066. this.heightMode = heightMode;
  7067. switch (this.heightMode) {
  7068. case CSS:
  7069. setHeight(heightByCss);
  7070. break;
  7071. case ROW:
  7072. setHeightByRows(heightByRows);
  7073. break;
  7074. case UNDEFINED:
  7075. setHeightByRows(body.getRowCount());
  7076. break;
  7077. default:
  7078. throw new IllegalStateException("Unimplemented feature "
  7079. + "- unknown HeightMode: " + this.heightMode);
  7080. }
  7081. }
  7082. }
  7083. /**
  7084. * Returns the current {@link HeightMode} the Escalator is in.
  7085. * <p>
  7086. * Defaults to {@link HeightMode#CSS}.
  7087. *
  7088. * @return the current HeightMode
  7089. */
  7090. public HeightMode getHeightMode() {
  7091. return heightMode;
  7092. }
  7093. /**
  7094. * Returns the {@link RowContainer} which contains the element.
  7095. *
  7096. * @param element
  7097. * the element to check for
  7098. * @return the container the element is in or <code>null</code> if element
  7099. * is not present in any container.
  7100. */
  7101. public RowContainer findRowContainer(Element element) {
  7102. if (getHeader().getElement() != element
  7103. && getHeader().getElement().isOrHasChild(element)) {
  7104. return getHeader();
  7105. } else if (getBody().getElement() != element
  7106. && getBody().getElement().isOrHasChild(element)) {
  7107. return getBody();
  7108. } else if (getFooter().getElement() != element
  7109. && getFooter().getElement().isOrHasChild(element)) {
  7110. return getFooter();
  7111. }
  7112. return null;
  7113. }
  7114. /**
  7115. * Sets whether a scroll direction is locked or not.
  7116. * <p>
  7117. * If a direction is locked, the escalator will refuse to scroll in that
  7118. * direction.
  7119. *
  7120. * @param direction
  7121. * the orientation of the scroll to set the lock status
  7122. * @param locked
  7123. * <code>true</code> to lock, <code>false</code> to unlock
  7124. */
  7125. public void setScrollLocked(ScrollbarBundle.Direction direction,
  7126. boolean locked) {
  7127. switch (direction) {
  7128. case HORIZONTAL:
  7129. horizontalScrollbar.setLocked(locked);
  7130. break;
  7131. case VERTICAL:
  7132. verticalScrollbar.setLocked(locked);
  7133. break;
  7134. default:
  7135. throw new UnsupportedOperationException(
  7136. "Unexpected value: " + direction);
  7137. }
  7138. }
  7139. /**
  7140. * Checks whether or not an direction is locked for scrolling.
  7141. *
  7142. * @param direction
  7143. * the direction of the scroll of which to check the lock status
  7144. * @return <code>true</code> if the direction is locked
  7145. */
  7146. public boolean isScrollLocked(ScrollbarBundle.Direction direction) {
  7147. switch (direction) {
  7148. case HORIZONTAL:
  7149. return horizontalScrollbar.isLocked();
  7150. case VERTICAL:
  7151. return verticalScrollbar.isLocked();
  7152. default:
  7153. throw new UnsupportedOperationException(
  7154. "Unexpected value: " + direction);
  7155. }
  7156. }
  7157. /**
  7158. * Adds a scroll handler to this escalator.
  7159. *
  7160. * @param handler
  7161. * the scroll handler to add
  7162. * @return a handler registration for the registered scroll handler
  7163. */
  7164. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7165. return addHandler(handler, ScrollEvent.TYPE);
  7166. }
  7167. /**
  7168. * Returns true if the Escalator is currently scrolling by touch, or has not
  7169. * made the decision yet whether to accept touch actions as scrolling or
  7170. * not.
  7171. *
  7172. * @see #setDelayToCancelTouchScroll(double)
  7173. *
  7174. * @return true when the component is touch scrolling at the moment
  7175. * @since 8.1
  7176. */
  7177. public boolean isTouchScrolling() {
  7178. return scroller.touchHandlerBundle.touching;
  7179. }
  7180. /**
  7181. * Returns the time after which to not consider a touch event a scroll event
  7182. * if the user has not moved the touch. This can be used to differentiate
  7183. * between quick touch move (scrolling) and long tap (e.g. context menu or
  7184. * drag and drop operation).
  7185. *
  7186. * @return delay in milliseconds after which to cancel touch scrolling if
  7187. * there is no movement, -1 means scrolling is always allowed
  7188. * @since 8.1
  7189. */
  7190. public double getDelayToCancelTouchScroll() {
  7191. return delayToCancelTouchScroll;
  7192. }
  7193. /**
  7194. * Sets the time after which to not consider a touch event a scroll event if
  7195. * the user has not moved the touch. This can be used to differentiate
  7196. * between quick touch move (scrolling) and long tap (e.g. context menu or
  7197. * drag and drop operation).
  7198. *
  7199. * @param delayToCancelTouchScroll
  7200. * delay in milliseconds after which to cancel touch scrolling if
  7201. * there is no movement, -1 to always allow scrolling
  7202. * @since 8.1
  7203. */
  7204. public void setDelayToCancelTouchScroll(double delayToCancelTouchScroll) {
  7205. this.delayToCancelTouchScroll = delayToCancelTouchScroll;
  7206. }
  7207. @Override
  7208. public boolean isWorkPending() {
  7209. return body.domSorter.waiting || verticalScrollbar.isWorkPending()
  7210. || horizontalScrollbar.isWorkPending() || layoutIsScheduled;
  7211. }
  7212. @Override
  7213. public void onResize() {
  7214. if (isAttached() && !layoutIsScheduled) {
  7215. layoutIsScheduled = true;
  7216. Scheduler.get().scheduleFinally(layoutCommand);
  7217. }
  7218. }
  7219. /**
  7220. * Gets the maximum number of body rows that can be visible on the screen at
  7221. * once.
  7222. *
  7223. * @return the maximum capacity
  7224. */
  7225. public int getMaxVisibleRowCount() {
  7226. return body.getMaxVisibleRowCount();
  7227. }
  7228. /**
  7229. * Gets the escalator's inner width. This is the entire width in pixels,
  7230. * without the vertical scrollbar.
  7231. *
  7232. * @return escalator's inner width
  7233. */
  7234. public double getInnerWidth() {
  7235. return getBoundingWidth(tableWrapper);
  7236. }
  7237. /**
  7238. * Resets all cached pixel sizes and reads new values from the DOM. This
  7239. * methods should be used e.g. when styles affecting the dimensions of
  7240. * elements in this escalator have been changed.
  7241. */
  7242. public void resetSizesFromDom() {
  7243. header.autodetectRowHeightNow();
  7244. body.autodetectRowHeightNow();
  7245. footer.autodetectRowHeightNow();
  7246. for (int i = 0; i < columnConfiguration.getColumnCount(); i++) {
  7247. columnConfiguration.setColumnWidth(i,
  7248. columnConfiguration.getColumnWidth(i));
  7249. }
  7250. }
  7251. private Range getViewportPixels() {
  7252. int from = (int) Math.floor(verticalScrollbar.getScrollPos());
  7253. int to = (int) body.getHeightOfSection();
  7254. return Range.withLength(from, to);
  7255. }
  7256. @Override
  7257. @SuppressWarnings("deprecation")
  7258. public com.google.gwt.user.client.Element getSubPartElement(
  7259. String subPart) {
  7260. SubPartArguments args = SubPartArguments.create(subPart);
  7261. Element tableStructureElement = getSubPartElementTableStructure(args);
  7262. if (tableStructureElement != null) {
  7263. return DOM.asOld(tableStructureElement);
  7264. }
  7265. Element spacerElement = getSubPartElementSpacer(args);
  7266. if (spacerElement != null) {
  7267. return DOM.asOld(spacerElement);
  7268. }
  7269. return null;
  7270. }
  7271. /**
  7272. * Returns the {@code <div class="{primary-stylename}-tablewrapper" />}
  7273. * element which has the table inside it. {primary-stylename} is .e.g
  7274. * {@code v-grid}.
  7275. * <p>
  7276. * <em>NOTE: you should not do any modifications to the returned element.
  7277. * This API is only available for querying data from the element.</em>
  7278. *
  7279. * @return the table wrapper element
  7280. * @since 8.1
  7281. */
  7282. public Element getTableWrapper() {
  7283. return tableWrapper;
  7284. }
  7285. /**
  7286. * Returns the <code>&lt;table&gt;</code> element of the grid.
  7287. *
  7288. * @return the table element
  7289. * @since 8.2
  7290. */
  7291. public Element getTable() {
  7292. return table;
  7293. }
  7294. private Element getSubPartElementTableStructure(SubPartArguments args) {
  7295. String type = args.getType();
  7296. int[] indices = args.getIndices();
  7297. // Get correct RowContainer for type from Escalator
  7298. RowContainer container = null;
  7299. if (type.equalsIgnoreCase("header")) {
  7300. container = getHeader();
  7301. } else if (type.equalsIgnoreCase("cell")) {
  7302. if (indices.length > 0) {
  7303. // If wanted row is not visible, we need to scroll there.
  7304. // Scrolling might be a no-op if row is already in the viewport.
  7305. scrollToRow(indices[0], ScrollDestination.ANY, 0);
  7306. }
  7307. container = getBody();
  7308. } else if (type.equalsIgnoreCase("footer")) {
  7309. container = getFooter();
  7310. }
  7311. if (null != container) {
  7312. if (indices.length == 0) {
  7313. // No indexing. Just return the wanted container element
  7314. return container.getElement();
  7315. } else {
  7316. try {
  7317. return getSubPart(container, indices);
  7318. } catch (Exception e) {
  7319. getLogger().log(Level.SEVERE, e.getMessage());
  7320. }
  7321. }
  7322. }
  7323. return null;
  7324. }
  7325. private Element getSubPart(RowContainer container, int[] indices) {
  7326. Element targetElement = container.getRowElement(indices[0]);
  7327. // Scroll wanted column to view if able
  7328. if (indices.length > 1 && targetElement != null) {
  7329. if (getColumnConfiguration().getFrozenColumnCount() <= indices[1]) {
  7330. scrollToColumn(indices[1], ScrollDestination.ANY, 0);
  7331. }
  7332. targetElement = getCellFromRow(TableRowElement.as(targetElement),
  7333. indices[1]);
  7334. for (int i = 2; i < indices.length && targetElement != null; ++i) {
  7335. targetElement = (Element) targetElement.getChild(indices[i]);
  7336. }
  7337. }
  7338. return targetElement;
  7339. }
  7340. private static Element getCellFromRow(TableRowElement rowElement,
  7341. int index) {
  7342. int childCount = rowElement.getCells().getLength();
  7343. if (index < 0 || index >= childCount) {
  7344. return null;
  7345. }
  7346. TableCellElement currentCell = null;
  7347. boolean indexInColspan = false;
  7348. int i = 0;
  7349. while (!indexInColspan) {
  7350. currentCell = rowElement.getCells().getItem(i);
  7351. // Calculate if this is the cell we are looking for
  7352. int colSpan = currentCell.getColSpan();
  7353. indexInColspan = index < colSpan + i;
  7354. // Increment by colspan to skip over hidden cells
  7355. i += colSpan;
  7356. }
  7357. return currentCell;
  7358. }
  7359. private Element getSubPartElementSpacer(SubPartArguments args) {
  7360. if ("spacer".equals(args.getType()) && args.getIndicesLength() == 1) {
  7361. // If spacer's row is not visible, we need to scroll there.
  7362. // Scrolling might be a no-op if row is already in the viewport.
  7363. scrollToSpacer(args.getIndex(0), ScrollDestination.ANY, 0);
  7364. return body.spacerContainer.getSubPartElement(args.getIndex(0));
  7365. } else {
  7366. return null;
  7367. }
  7368. }
  7369. @Override
  7370. @SuppressWarnings("deprecation")
  7371. public String getSubPartName(
  7372. com.google.gwt.user.client.Element subElement) {
  7373. /*
  7374. * The spacer check needs to be before table structure check, because
  7375. * (for now) the table structure will take spacer elements into account
  7376. * as well, when it shouldn't.
  7377. */
  7378. String spacer = getSubPartNameSpacer(subElement);
  7379. if (spacer != null) {
  7380. return spacer;
  7381. }
  7382. String tableStructure = getSubPartNameTableStructure(subElement);
  7383. if (tableStructure != null) {
  7384. return tableStructure;
  7385. }
  7386. return null;
  7387. }
  7388. private String getSubPartNameTableStructure(Element subElement) {
  7389. List<RowContainer> containers = Arrays.asList(getHeader(), getBody(),
  7390. getFooter());
  7391. List<String> containerType = Arrays.asList("header", "cell", "footer");
  7392. for (int i = 0; i < containers.size(); ++i) {
  7393. RowContainer container = containers.get(i);
  7394. boolean containerRow = (subElement.getTagName()
  7395. .equalsIgnoreCase("tr")
  7396. && subElement.getParentElement() == container.getElement());
  7397. if (containerRow) {
  7398. /*
  7399. * Wanted SubPart is row that is a child of containers root to
  7400. * get indices, we use a cell that is a child of this row
  7401. */
  7402. subElement = subElement.getFirstChildElement();
  7403. }
  7404. Cell cell = container.getCell(subElement);
  7405. if (cell != null) {
  7406. // Skip the column index if subElement was a child of root
  7407. return containerType.get(i) + "[" + cell.getRow()
  7408. + (containerRow ? "]" : "][" + cell.getColumn() + "]");
  7409. }
  7410. }
  7411. return null;
  7412. }
  7413. private String getSubPartNameSpacer(Element subElement) {
  7414. return body.spacerContainer.getSubPartName(subElement);
  7415. }
  7416. private void logWarning(String message) {
  7417. getLogger().warning(message);
  7418. }
  7419. /**
  7420. * This is an internal method for calculating minimum width for Column
  7421. * resize.
  7422. *
  7423. * @return minimum width for column
  7424. */
  7425. double getMinCellWidth(int colIndex) {
  7426. return columnConfiguration.getMinCellWidth(colIndex);
  7427. }
  7428. /**
  7429. * Internal method for checking whether the browser is IE11 or Edge
  7430. *
  7431. * @return true only if the current browser is IE11, or Edge
  7432. */
  7433. private static boolean isCurrentBrowserIE11OrEdge() {
  7434. return BrowserInfo.get().isIE11() || BrowserInfo.get().isEdge();
  7435. }
  7436. }