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

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