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

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