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

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