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

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