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

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