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

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