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

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