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

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