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

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