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

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