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.

Grid.java 349KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828
  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.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.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Map.Entry;
  28. import java.util.Objects;
  29. import java.util.Optional;
  30. import java.util.Set;
  31. import java.util.TreeMap;
  32. import java.util.concurrent.atomic.AtomicInteger;
  33. import java.util.logging.Level;
  34. import java.util.logging.Logger;
  35. import java.util.stream.Stream;
  36. import com.google.gwt.core.client.Scheduler;
  37. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  38. import com.google.gwt.core.shared.GWT;
  39. import com.google.gwt.dom.client.BrowserEvents;
  40. import com.google.gwt.dom.client.DivElement;
  41. import com.google.gwt.dom.client.Document;
  42. import com.google.gwt.dom.client.Element;
  43. import com.google.gwt.dom.client.EventTarget;
  44. import com.google.gwt.dom.client.NativeEvent;
  45. import com.google.gwt.dom.client.Node;
  46. import com.google.gwt.dom.client.Style;
  47. import com.google.gwt.dom.client.Style.Display;
  48. import com.google.gwt.dom.client.Style.Unit;
  49. import com.google.gwt.dom.client.TableCellElement;
  50. import com.google.gwt.dom.client.TableRowElement;
  51. import com.google.gwt.dom.client.TableSectionElement;
  52. import com.google.gwt.dom.client.Touch;
  53. import com.google.gwt.event.dom.client.ClickHandler;
  54. import com.google.gwt.event.dom.client.KeyCodes;
  55. import com.google.gwt.event.dom.client.KeyDownEvent;
  56. import com.google.gwt.event.dom.client.KeyDownHandler;
  57. import com.google.gwt.event.dom.client.KeyEvent;
  58. import com.google.gwt.event.dom.client.MouseEvent;
  59. import com.google.gwt.event.logical.shared.CloseEvent;
  60. import com.google.gwt.event.logical.shared.CloseHandler;
  61. import com.google.gwt.event.shared.HandlerRegistration;
  62. import com.google.gwt.touch.client.Point;
  63. import com.google.gwt.user.client.DOM;
  64. import com.google.gwt.user.client.Event;
  65. import com.google.gwt.user.client.Timer;
  66. import com.google.gwt.user.client.ui.Button;
  67. import com.google.gwt.user.client.ui.CheckBox;
  68. import com.google.gwt.user.client.ui.Composite;
  69. import com.google.gwt.user.client.ui.FlowPanel;
  70. import com.google.gwt.user.client.ui.HasEnabled;
  71. import com.google.gwt.user.client.ui.HasWidgets;
  72. import com.google.gwt.user.client.ui.MenuBar;
  73. import com.google.gwt.user.client.ui.MenuItem;
  74. import com.google.gwt.user.client.ui.PopupPanel;
  75. import com.google.gwt.user.client.ui.ResizeComposite;
  76. import com.google.gwt.user.client.ui.Widget;
  77. import com.vaadin.client.BrowserInfo;
  78. import com.vaadin.client.DeferredWorker;
  79. import com.vaadin.client.Focusable;
  80. import com.vaadin.client.WidgetUtil;
  81. import com.vaadin.client.WidgetUtil.Reference;
  82. import com.vaadin.client.data.DataChangeHandler;
  83. import com.vaadin.client.data.DataSource;
  84. import com.vaadin.client.data.DataSource.RowHandle;
  85. import com.vaadin.client.renderers.ComplexRenderer;
  86. import com.vaadin.client.renderers.Renderer;
  87. import com.vaadin.client.renderers.WidgetRenderer;
  88. import com.vaadin.client.ui.FocusUtil;
  89. import com.vaadin.client.ui.SubPartAware;
  90. import com.vaadin.client.ui.dd.DragAndDropHandler;
  91. import com.vaadin.client.ui.dd.DragAndDropHandler.DragAndDropCallback;
  92. import com.vaadin.client.ui.dd.DragHandle;
  93. import com.vaadin.client.ui.dd.DragHandle.DragHandleCallback;
  94. import com.vaadin.client.widget.escalator.Cell;
  95. import com.vaadin.client.widget.escalator.ColumnConfiguration;
  96. import com.vaadin.client.widget.escalator.EscalatorUpdater;
  97. import com.vaadin.client.widget.escalator.FlyweightCell;
  98. import com.vaadin.client.widget.escalator.Row;
  99. import com.vaadin.client.widget.escalator.RowContainer;
  100. import com.vaadin.client.widget.escalator.RowVisibilityChangeHandler;
  101. import com.vaadin.client.widget.escalator.ScrollbarBundle.Direction;
  102. import com.vaadin.client.widget.escalator.Spacer;
  103. import com.vaadin.client.widget.escalator.SpacerUpdater;
  104. import com.vaadin.client.widget.escalator.events.RowHeightChangedEvent;
  105. import com.vaadin.client.widget.escalator.events.RowHeightChangedHandler;
  106. import com.vaadin.client.widget.escalator.events.SpacerIndexChangedEvent;
  107. import com.vaadin.client.widget.escalator.events.SpacerIndexChangedHandler;
  108. import com.vaadin.client.widget.escalator.events.SpacerVisibilityChangedEvent;
  109. import com.vaadin.client.widget.escalator.events.SpacerVisibilityChangedHandler;
  110. import com.vaadin.client.widget.grid.AutoScroller;
  111. import com.vaadin.client.widget.grid.AutoScroller.AutoScrollerCallback;
  112. import com.vaadin.client.widget.grid.AutoScroller.ScrollAxis;
  113. import com.vaadin.client.widget.grid.CellReference;
  114. import com.vaadin.client.widget.grid.CellStyleGenerator;
  115. import com.vaadin.client.widget.grid.DataAvailableEvent;
  116. import com.vaadin.client.widget.grid.DataAvailableHandler;
  117. import com.vaadin.client.widget.grid.DefaultEditorEventHandler;
  118. import com.vaadin.client.widget.grid.DetailsGenerator;
  119. import com.vaadin.client.widget.grid.EditorHandler;
  120. import com.vaadin.client.widget.grid.EditorHandler.EditorRequest;
  121. import com.vaadin.client.widget.grid.EventCellReference;
  122. import com.vaadin.client.widget.grid.GridEventHandler;
  123. import com.vaadin.client.widget.grid.HeightAwareDetailsGenerator;
  124. import com.vaadin.client.widget.grid.RendererCellReference;
  125. import com.vaadin.client.widget.grid.RowReference;
  126. import com.vaadin.client.widget.grid.RowStyleGenerator;
  127. import com.vaadin.client.widget.grid.events.AbstractGridKeyEventHandler;
  128. import com.vaadin.client.widget.grid.events.AbstractGridMouseEventHandler;
  129. import com.vaadin.client.widget.grid.events.BodyClickHandler;
  130. import com.vaadin.client.widget.grid.events.BodyDoubleClickHandler;
  131. import com.vaadin.client.widget.grid.events.BodyKeyDownHandler;
  132. import com.vaadin.client.widget.grid.events.BodyKeyPressHandler;
  133. import com.vaadin.client.widget.grid.events.BodyKeyUpHandler;
  134. import com.vaadin.client.widget.grid.events.ColumnReorderEvent;
  135. import com.vaadin.client.widget.grid.events.ColumnReorderHandler;
  136. import com.vaadin.client.widget.grid.events.ColumnResizeEvent;
  137. import com.vaadin.client.widget.grid.events.ColumnResizeHandler;
  138. import com.vaadin.client.widget.grid.events.ColumnVisibilityChangeEvent;
  139. import com.vaadin.client.widget.grid.events.ColumnVisibilityChangeHandler;
  140. import com.vaadin.client.widget.grid.events.FooterClickHandler;
  141. import com.vaadin.client.widget.grid.events.FooterDoubleClickHandler;
  142. import com.vaadin.client.widget.grid.events.FooterKeyDownHandler;
  143. import com.vaadin.client.widget.grid.events.FooterKeyPressHandler;
  144. import com.vaadin.client.widget.grid.events.FooterKeyUpHandler;
  145. import com.vaadin.client.widget.grid.events.GridClickEvent;
  146. import com.vaadin.client.widget.grid.events.GridDoubleClickEvent;
  147. import com.vaadin.client.widget.grid.events.GridEnabledEvent;
  148. import com.vaadin.client.widget.grid.events.GridEnabledHandler;
  149. import com.vaadin.client.widget.grid.events.GridKeyDownEvent;
  150. import com.vaadin.client.widget.grid.events.GridKeyPressEvent;
  151. import com.vaadin.client.widget.grid.events.GridKeyUpEvent;
  152. import com.vaadin.client.widget.grid.events.GridSelectionAllowedEvent;
  153. import com.vaadin.client.widget.grid.events.GridSelectionAllowedHandler;
  154. import com.vaadin.client.widget.grid.events.HeaderClickHandler;
  155. import com.vaadin.client.widget.grid.events.HeaderDoubleClickHandler;
  156. import com.vaadin.client.widget.grid.events.HeaderKeyDownHandler;
  157. import com.vaadin.client.widget.grid.events.HeaderKeyPressHandler;
  158. import com.vaadin.client.widget.grid.events.HeaderKeyUpHandler;
  159. import com.vaadin.client.widget.grid.events.ScrollEvent;
  160. import com.vaadin.client.widget.grid.events.ScrollHandler;
  161. import com.vaadin.client.widget.grid.events.SelectAllEvent;
  162. import com.vaadin.client.widget.grid.events.SelectAllHandler;
  163. import com.vaadin.client.widget.grid.selection.HasSelectionHandlers;
  164. import com.vaadin.client.widget.grid.selection.MultiSelectionRenderer;
  165. import com.vaadin.client.widget.grid.selection.SelectionEvent;
  166. import com.vaadin.client.widget.grid.selection.SelectionHandler;
  167. import com.vaadin.client.widget.grid.selection.SelectionModel;
  168. import com.vaadin.client.widget.grid.selection.SelectionModelWithSelectionColumn;
  169. import com.vaadin.client.widget.grid.sort.Sort;
  170. import com.vaadin.client.widget.grid.sort.SortEvent;
  171. import com.vaadin.client.widget.grid.sort.SortHandler;
  172. import com.vaadin.client.widget.grid.sort.SortOrder;
  173. import com.vaadin.client.widgets.Escalator.AbstractRowContainer;
  174. import com.vaadin.client.widgets.Escalator.SubPartArguments;
  175. import com.vaadin.client.widgets.Grid.Editor.State;
  176. import com.vaadin.client.widgets.Grid.StaticSection.StaticCell;
  177. import com.vaadin.client.widgets.Grid.StaticSection.StaticRow;
  178. import com.vaadin.shared.Range;
  179. import com.vaadin.shared.Registration;
  180. import com.vaadin.shared.data.sort.SortDirection;
  181. import com.vaadin.shared.ui.ContentMode;
  182. import com.vaadin.shared.ui.grid.ColumnResizeMode;
  183. import com.vaadin.shared.ui.grid.GridConstants;
  184. import com.vaadin.shared.ui.grid.GridConstants.Section;
  185. import com.vaadin.shared.ui.grid.GridStaticCellType;
  186. import com.vaadin.shared.ui.grid.HeightMode;
  187. import com.vaadin.shared.ui.grid.ScrollDestination;
  188. import com.vaadin.shared.util.SharedUtil;
  189. /**
  190. * A data grid view that supports columns and lazy loading of data rows from a
  191. * data source.
  192. *
  193. * <h1>Columns</h1>
  194. * <p>
  195. * Each column in Grid is represented by a {@link Column}. Each
  196. * {@code GridColumn} has a custom implementation for
  197. * {@link Column#getValue(Object)} that gets the row object as an argument, and
  198. * returns the value for that particular column, extracted from the row object.
  199. * <p>
  200. * Each column also has a Renderer. Its function is to take the value that is
  201. * given by the {@code GridColumn} and display it to the user. A simple column
  202. * might have a {@link com.vaadin.client.renderers.TextRenderer TextRenderer}
  203. * that simply takes in a {@code String} and displays it as the cell's content.
  204. * A more complex renderer might be
  205. * {@link com.vaadin.client.renderers.ProgressBarRenderer ProgressBarRenderer}
  206. * that takes in a floating point number, and displays a progress bar instead,
  207. * based on the given number.
  208. * <p>
  209. * <em>See:</em> {@link #addColumn(Column)}, {@link #addColumn(Column, int)} and
  210. * {@link #addColumns(Column...)}. <em>Also</em>
  211. * {@link Column#setRenderer(Renderer)}.
  212. *
  213. * <h1>Data Sources</h1>
  214. * <p>
  215. * Grid gets its data from a {@link DataSource}, providing row objects to Grid
  216. * from a user-defined endpoint. It can be either a local in-memory data source
  217. * (e.g. {@link com.vaadin.client.widget.grid.datasources.ListDataSource
  218. * ListDataSource}) or even a remote one, retrieving data from e.g. a REST API
  219. * (see {@link com.vaadin.client.data.AbstractRemoteDataSource
  220. * AbstractRemoteDataSource}).
  221. *
  222. *
  223. * @param <T>
  224. * The row type of the grid. The row type is the POJO type from where
  225. * the data is retrieved into the column cells.
  226. * @since 7.4
  227. * @author Vaadin Ltd
  228. */
  229. public class Grid<T> extends ResizeComposite implements HasSelectionHandlers<T>,
  230. SubPartAware, DeferredWorker, Focusable,
  231. com.google.gwt.user.client.ui.Focusable, HasWidgets, HasEnabled {
  232. private static final String STYLE_NAME = "v-grid";
  233. private static final String SELECT_ALL_CHECKBOX_CLASSNAME = "-select-all-checkbox";
  234. /**
  235. * Abstract base class for Grid header and footer sections.
  236. *
  237. * @since 7.5.0
  238. *
  239. * @param <ROWTYPE>
  240. * the type of the rows in the section
  241. */
  242. public abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>> {
  243. /**
  244. * A header or footer cell. Has a simple textual caption.
  245. *
  246. */
  247. public static class StaticCell {
  248. private Object content = null;
  249. private int colspan = 1;
  250. private StaticSection<?> section;
  251. private GridStaticCellType type = GridStaticCellType.TEXT;
  252. private String styleName = null;
  253. private String description = null;
  254. private ContentMode descriptionContentMode = ContentMode.TEXT;
  255. /**
  256. * Sets the text displayed in this cell.
  257. *
  258. * @param text
  259. * a plain text caption
  260. */
  261. public void setText(String text) {
  262. detach();
  263. this.content = text;
  264. this.type = GridStaticCellType.TEXT;
  265. section.requestSectionRefresh();
  266. }
  267. /**
  268. * Returns the text displayed in this cell.
  269. *
  270. * @return the plain text caption
  271. */
  272. public String getText() {
  273. if (type != GridStaticCellType.TEXT) {
  274. throw new IllegalStateException(
  275. "Cannot fetch Text from a cell with type " + type);
  276. }
  277. return (String) content;
  278. }
  279. protected StaticSection<?> getSection() {
  280. assert section != null;
  281. return section;
  282. }
  283. protected void setSection(StaticSection<?> section) {
  284. this.section = section;
  285. }
  286. /**
  287. * Returns the amount of columns the cell spans. By default is 1.
  288. *
  289. * @return The amount of columns the cell spans.
  290. */
  291. public int getColspan() {
  292. return colspan;
  293. }
  294. /**
  295. * Sets the amount of columns the cell spans. Must be more or equal
  296. * to 1. By default is 1.
  297. *
  298. * @param colspan
  299. * the colspan to set
  300. */
  301. public void setColspan(int colspan) {
  302. if (colspan < 1) {
  303. throw new IllegalArgumentException(
  304. "Colspan cannot be less than 1");
  305. }
  306. this.colspan = colspan;
  307. section.requestSectionRefresh();
  308. }
  309. /**
  310. * Returns the html inside the cell.
  311. *
  312. * @throws IllegalStateException
  313. * if trying to retrive HTML from a cell with a type
  314. * other than {@link GridStaticCellType#HTML}.
  315. * @return the html content of the cell.
  316. */
  317. public String getHtml() {
  318. if (type != GridStaticCellType.HTML) {
  319. throw new IllegalStateException(
  320. "Cannot fetch HTML from a cell with type " + type);
  321. }
  322. return (String) content;
  323. }
  324. /**
  325. * Sets the content of the cell to the provided html. All previous
  326. * content is discarded and the cell type is set to
  327. * {@link GridStaticCellType#HTML}.
  328. *
  329. * @param html
  330. * The html content of the cell
  331. */
  332. public void setHtml(String html) {
  333. detach();
  334. this.content = html;
  335. this.type = GridStaticCellType.HTML;
  336. section.requestSectionRefresh();
  337. }
  338. /**
  339. * Returns the widget in the cell.
  340. *
  341. * @throws IllegalStateException
  342. * if the cell is not {@link GridStaticCellType#WIDGET}
  343. *
  344. * @return the widget in the cell
  345. */
  346. public Widget getWidget() {
  347. if (type != GridStaticCellType.WIDGET) {
  348. throw new IllegalStateException(
  349. "Cannot fetch Widget from a cell with type "
  350. + type);
  351. }
  352. return (Widget) content;
  353. }
  354. /**
  355. * Set widget as the content of the cell. The type of the cell
  356. * becomes {@link GridStaticCellType#WIDGET}. All previous content
  357. * is discarded.
  358. *
  359. * @param widget
  360. * The widget to add to the cell. Should not be
  361. * previously attached anywhere (widget.getParent ==
  362. * null).
  363. */
  364. public void setWidget(Widget widget) {
  365. if (this.content == widget) {
  366. return;
  367. }
  368. detach();
  369. this.content = widget;
  370. this.type = GridStaticCellType.WIDGET;
  371. section.requestSectionRefresh();
  372. }
  373. /**
  374. * Returns the type of the cell.
  375. *
  376. * @return the type of content the cell contains.
  377. */
  378. public GridStaticCellType getType() {
  379. return type;
  380. }
  381. /**
  382. * Returns the custom style name for this cell.
  383. *
  384. * @return the style name or null if no style name has been set
  385. */
  386. public String getStyleName() {
  387. return styleName;
  388. }
  389. /**
  390. * Sets a custom style name for this cell.
  391. *
  392. * @param styleName
  393. * the style name to set or null to not use any style
  394. * name
  395. */
  396. public void setStyleName(String styleName) {
  397. this.styleName = styleName;
  398. section.requestSectionRefresh();
  399. }
  400. /**
  401. * Called when the cell is detached from the row
  402. *
  403. * @since 7.6.3
  404. */
  405. void detach() {
  406. if (content instanceof Widget) {
  407. // Widget in the cell, detach it
  408. section.getGrid().detachWidget((Widget) content);
  409. }
  410. }
  411. /**
  412. * Gets the tooltip for the cell.
  413. * <p>
  414. * The tooltip is shown in the mode returned by
  415. * {@link #getDescriptionContentMode()}.
  416. *
  417. * @return the tooltip text for this cell
  418. * @since 8.4
  419. */
  420. public String getDescription() {
  421. return description;
  422. }
  423. /**
  424. * Sets the tooltip for the cell.
  425. * <p>
  426. * By default, tooltips are shown as plain text. For HTML tooltips,
  427. * see {@link #setDescription(String, ContentMode)} or
  428. * {@link #setDescriptionContentMode(ContentMode)}.
  429. *
  430. * @param description
  431. * the tooltip to show when hovering the cell
  432. * @since 8.4
  433. */
  434. public void setDescription(String description) {
  435. this.description = description;
  436. }
  437. /**
  438. * Sets the tooltip for the cell to be shown with the given content
  439. * mode.
  440. *
  441. * @see ContentMode
  442. * @param description
  443. * the tooltip to show when hovering the cell
  444. * @param descriptionContentMode
  445. * the content mode to use for the tooltip (HTML or plain
  446. * text)
  447. * @since 8.4
  448. */
  449. public void setDescription(String description,
  450. ContentMode descriptionContentMode) {
  451. setDescription(description);
  452. setDescriptionContentMode(descriptionContentMode);
  453. }
  454. /**
  455. * Gets the content mode for the tooltip.
  456. * <p>
  457. * The content mode determines how the tooltip is shown.
  458. *
  459. * @see ContentMode
  460. * @return the content mode for the tooltip
  461. * @since 8.4
  462. */
  463. public ContentMode getDescriptionContentMode() {
  464. return descriptionContentMode;
  465. }
  466. /**
  467. * Sets the content mode for the tooltip.
  468. *
  469. * @see ContentMode
  470. * @param descriptionContentMode
  471. * the content mode for the tooltip
  472. * @since 8.4
  473. */
  474. public void setDescriptionContentMode(
  475. ContentMode descriptionContentMode) {
  476. this.descriptionContentMode = descriptionContentMode;
  477. }
  478. }
  479. /**
  480. * Abstract base class for Grid header and footer rows.
  481. *
  482. * @param <CELLTYPE>
  483. * the type of the cells in the row
  484. */
  485. public abstract static class StaticRow<CELLTYPE extends StaticCell> {
  486. private Map<Column<?, ?>, CELLTYPE> cells = new HashMap<>();
  487. private StaticSection<?> section;
  488. /**
  489. * Map from cell meta data to sets of spanned columns .
  490. */
  491. private Map<CELLTYPE, Set<Column<?, ?>>> cellGroups = new HashMap<>();
  492. /**
  493. * A custom style name for the row or null if none is set.
  494. */
  495. private String styleName = null;
  496. /**
  497. * Returns the cell on given GridColumn. If the column is merged
  498. * returned cell is the cell for the whole group.
  499. *
  500. * @param column
  501. * the column in grid
  502. * @return the cell on given column, merged cell for merged columns,
  503. * null if not found
  504. */
  505. public CELLTYPE getCell(Column<?, ?> column) {
  506. CELLTYPE cell = getMergedCellForColumn(column);
  507. if (cell != null) {
  508. return cell;
  509. }
  510. return cells.get(column);
  511. }
  512. /**
  513. * Returns <code>true</code> if this row contains spanned cells.
  514. *
  515. * @since 7.5.0
  516. * @return does this row contain spanned cells
  517. */
  518. public boolean hasSpannedCells() {
  519. return !cellGroups.isEmpty();
  520. }
  521. /**
  522. * Merges columns cells in a row.
  523. *
  524. * @param columns
  525. * the columns which header should be merged
  526. * @return the remaining visible cell after the merge, or the cell
  527. * on first column if all are hidden
  528. */
  529. public CELLTYPE join(Column<?, ?>... columns) {
  530. if (columns.length <= 1) {
  531. throw new IllegalArgumentException(
  532. "You can't merge less than 2 columns together.");
  533. }
  534. HashSet<Column<?, ?>> columnGroup = new HashSet<>();
  535. // NOTE: this doesn't care about hidden columns, those are
  536. // filtered in calculateColspans()
  537. for (Column<?, ?> column : columns) {
  538. if (!cells.containsKey(column)) {
  539. throw new IllegalArgumentException(
  540. "Given column does not exists on row "
  541. + column);
  542. } else if (getMergedCellForColumn(column) != null) {
  543. throw new IllegalStateException(
  544. "Column is already in a group.");
  545. }
  546. columnGroup.add(column);
  547. }
  548. CELLTYPE joinedCell = createCell();
  549. cellGroups.put(joinedCell, columnGroup);
  550. joinedCell.setSection(getSection());
  551. calculateColspans();
  552. return joinedCell;
  553. }
  554. /**
  555. * Merges columns cells in a row.
  556. *
  557. * @param cells
  558. * The cells to merge. Must be from the same row.
  559. * @return The remaining visible cell after the merge, or the first
  560. * cell if all columns are hidden
  561. */
  562. public CELLTYPE join(CELLTYPE... cells) {
  563. if (cells.length <= 1) {
  564. throw new IllegalArgumentException(
  565. "You can't merge less than 2 cells together.");
  566. }
  567. Column<?, ?>[] columns = new Column<?, ?>[cells.length];
  568. int j = 0;
  569. for (Column<?, ?> column : this.cells.keySet()) {
  570. CELLTYPE cell = this.cells.get(column);
  571. if (!this.cells.containsValue(cells[j])) {
  572. throw new IllegalArgumentException(
  573. "Given cell does not exists on row");
  574. } else if (cell.equals(cells[j])) {
  575. columns[j++] = column;
  576. if (j == cells.length) {
  577. break;
  578. }
  579. }
  580. }
  581. return join(columns);
  582. }
  583. private CELLTYPE getMergedCellForColumn(Column<?, ?> column) {
  584. for (Entry<CELLTYPE, Set<Column<?, ?>>> entry : cellGroups
  585. .entrySet()) {
  586. if (entry.getValue().contains(column)) {
  587. return entry.getKey();
  588. }
  589. }
  590. return null;
  591. }
  592. protected int getSizeOfCellGroup(Column<?, ?> column) {
  593. for (Entry<CELLTYPE, Set<Column<?, ?>>> entry : cellGroups
  594. .entrySet()) {
  595. if (entry.getValue().contains(column)) {
  596. return entry.getValue().size();
  597. }
  598. }
  599. return 0;
  600. }
  601. void calculateColspans() {
  602. // Reset all cells
  603. for (CELLTYPE cell : this.cells.values()) {
  604. cell.setColspan(1);
  605. }
  606. // Set colspan for grouped cells
  607. for (Entry<CELLTYPE, Set<Column<?, ?>>> entry : cellGroups
  608. .entrySet()) {
  609. CELLTYPE mergedCell = entry.getKey();
  610. if (!checkMergedCellIsContinuous(entry.getValue())) {
  611. // on error simply break the merged cell
  612. mergedCell.setColspan(1);
  613. } else {
  614. int colSpan = 0;
  615. for (Column<?, ?> column : entry.getValue()) {
  616. if (!column.isHidden()) {
  617. colSpan++;
  618. }
  619. }
  620. // colspan can't be 0
  621. mergedCell.setColspan(Math.max(1, colSpan));
  622. }
  623. }
  624. }
  625. private boolean checkMergedCellIsContinuous(
  626. Set<Column<?, ?>> mergedCell) {
  627. // no matter if hidden or not, just check for continuous order
  628. final List<Column<?, ?>> columnOrder = new ArrayList<>(
  629. section.grid.getColumns());
  630. if (!columnOrder.containsAll(mergedCell)) {
  631. return false;
  632. }
  633. for (int i = 0; i < columnOrder.size(); ++i) {
  634. if (!mergedCell.contains(columnOrder.get(i))) {
  635. continue;
  636. }
  637. for (int j = 1; j < mergedCell.size(); ++j) {
  638. if (!mergedCell.contains(columnOrder.get(i + j))) {
  639. return false;
  640. }
  641. }
  642. return true;
  643. }
  644. return false;
  645. }
  646. protected void addCell(Column<?, ?> column) {
  647. CELLTYPE cell = createCell();
  648. cell.setSection(getSection());
  649. cells.put(column, cell);
  650. }
  651. protected void removeCell(Column<?, ?> column) {
  652. cells.remove(column);
  653. }
  654. protected abstract CELLTYPE createCell();
  655. protected StaticSection<?> getSection() {
  656. return section;
  657. }
  658. protected void setSection(StaticSection<?> section) {
  659. this.section = section;
  660. }
  661. /**
  662. * Returns the custom style name for this row.
  663. *
  664. * @return the style name or null if no style name has been set
  665. */
  666. public String getStyleName() {
  667. return styleName;
  668. }
  669. /**
  670. * Sets a custom style name for this row.
  671. *
  672. * @param styleName
  673. * the style name to set or null to not use any style
  674. * name
  675. */
  676. public void setStyleName(String styleName) {
  677. this.styleName = styleName;
  678. section.requestSectionRefresh();
  679. }
  680. /**
  681. * Called when the row is detached from the grid
  682. *
  683. * @since 7.6.3
  684. */
  685. void detach() {
  686. // Avoid calling detach twice for a merged cell
  687. HashSet<CELLTYPE> cells = new HashSet<>();
  688. for (Column<?, ?> column : getSection().grid.getColumns()) {
  689. cells.add(getCell(column));
  690. }
  691. for (CELLTYPE cell : cells) {
  692. cell.detach();
  693. }
  694. }
  695. }
  696. private Grid<?> grid;
  697. private List<ROWTYPE> rows = new ArrayList<>();
  698. private boolean visible = true;
  699. /**
  700. * Creates and returns a new instance of the row type.
  701. *
  702. * @return the created row
  703. */
  704. protected abstract ROWTYPE createRow();
  705. /**
  706. * Informs the grid that this section should be re-rendered.
  707. * <p>
  708. * <b>Note</b> that re-render means calling update() on each cell,
  709. * preAttach()/postAttach()/preDetach()/postDetach() is not called as
  710. * the cells are not removed from the DOM.
  711. */
  712. protected abstract void requestSectionRefresh();
  713. /**
  714. * Sets the visibility of the whole section.
  715. *
  716. * @param visible
  717. * true to show this section, false to hide
  718. */
  719. public void setVisible(boolean visible) {
  720. if (this.visible != visible) {
  721. this.visible = visible;
  722. requestSectionRefresh();
  723. }
  724. }
  725. /**
  726. * Returns the visibility of this section.
  727. *
  728. * @return true if visible, false otherwise.
  729. */
  730. public boolean isVisible() {
  731. return visible;
  732. }
  733. /**
  734. * Inserts a new row at the given position. Shifts the row currently at
  735. * that position and any subsequent rows down (adds one to their
  736. * indices).
  737. *
  738. * @param index
  739. * the position at which to insert the row
  740. * @return the new row
  741. *
  742. * @throws IndexOutOfBoundsException
  743. * if the index is out of bounds
  744. * @see #appendRow()
  745. * @see #prependRow()
  746. * @see #removeRow(int)
  747. * @see #removeRow(StaticRow)
  748. */
  749. public ROWTYPE addRowAt(int index) {
  750. ROWTYPE row = createRow();
  751. row.setSection(this);
  752. for (int i = 0; i < getGrid().getColumnCount(); ++i) {
  753. row.addCell(grid.getColumn(i));
  754. }
  755. rows.add(index, row);
  756. requestSectionRefresh();
  757. return row;
  758. }
  759. /**
  760. * Adds a new row at the top of this section.
  761. *
  762. * @return the new row
  763. * @see #appendRow()
  764. * @see #addRowAt(int)
  765. * @see #removeRow(int)
  766. * @see #removeRow(StaticRow)
  767. */
  768. public ROWTYPE prependRow() {
  769. return addRowAt(0);
  770. }
  771. /**
  772. * Adds a new row at the bottom of this section.
  773. *
  774. * @return the new row
  775. * @see #prependRow()
  776. * @see #addRowAt(int)
  777. * @see #removeRow(int)
  778. * @see #removeRow(StaticRow)
  779. */
  780. public ROWTYPE appendRow() {
  781. return addRowAt(rows.size());
  782. }
  783. /**
  784. * Removes the row at the given position.
  785. *
  786. * @param index
  787. * the position of the row
  788. *
  789. * @throws IndexOutOfBoundsException
  790. * if the index is out of bounds
  791. * @see #addRowAt(int)
  792. * @see #appendRow()
  793. * @see #prependRow()
  794. * @see #removeRow(StaticRow)
  795. */
  796. public void removeRow(int index) {
  797. ROWTYPE row = rows.remove(index);
  798. row.detach();
  799. requestSectionRefresh();
  800. }
  801. /**
  802. * Removes the given row from the section.
  803. *
  804. * @param row
  805. * the row to be removed
  806. *
  807. * @throws IllegalArgumentException
  808. * if the row does not exist in this section
  809. * @see #addRowAt(int)
  810. * @see #appendRow()
  811. * @see #prependRow()
  812. * @see #removeRow(int)
  813. */
  814. public void removeRow(ROWTYPE row) {
  815. try {
  816. removeRow(rows.indexOf(row));
  817. } catch (IndexOutOfBoundsException e) {
  818. throw new IllegalArgumentException(
  819. "Section does not contain the given row");
  820. }
  821. }
  822. /**
  823. * Returns the row at the given position.
  824. *
  825. * @param index
  826. * the position of the row
  827. * @return the row with the given index
  828. *
  829. * @throws IndexOutOfBoundsException
  830. * if the index is out of bounds
  831. */
  832. public ROWTYPE getRow(int index) {
  833. try {
  834. return rows.get(index);
  835. } catch (IndexOutOfBoundsException e) {
  836. throw new IllegalArgumentException(
  837. "Row with index " + index + " does not exist");
  838. }
  839. }
  840. /**
  841. * Returns the number of rows in this section.
  842. *
  843. * @return the number of rows
  844. */
  845. public int getRowCount() {
  846. return rows.size();
  847. }
  848. protected List<ROWTYPE> getRows() {
  849. return rows;
  850. }
  851. protected int getVisibleRowCount() {
  852. return isVisible() ? getRowCount() : 0;
  853. }
  854. protected void addColumn(Column<?, ?> column) {
  855. for (ROWTYPE row : rows) {
  856. row.addCell(column);
  857. }
  858. }
  859. protected void removeColumn(Column<?, ?> column) {
  860. for (ROWTYPE row : rows) {
  861. row.removeCell(column);
  862. }
  863. }
  864. protected void setGrid(Grid<?> grid) {
  865. this.grid = grid;
  866. }
  867. protected Grid<?> getGrid() {
  868. assert grid != null;
  869. return grid;
  870. }
  871. protected void updateColSpans() {
  872. for (ROWTYPE row : rows) {
  873. if (row.hasSpannedCells()) {
  874. row.calculateColspans();
  875. }
  876. }
  877. }
  878. }
  879. /**
  880. * Represents the header section of a Grid. A header consists of a single
  881. * header row containing a header cell for each column. Each cell has a
  882. * simple textual caption.
  883. */
  884. protected static class Header extends StaticSection<HeaderRow> {
  885. private HeaderRow defaultRow;
  886. private boolean markAsDirty = false;
  887. @Override
  888. public void removeRow(int index) {
  889. HeaderRow removedRow = getRow(index);
  890. super.removeRow(index);
  891. if (removedRow == defaultRow) {
  892. setDefaultRow(null);
  893. }
  894. }
  895. /**
  896. * Sets the default row of this header. The default row is a special
  897. * header row providing a user interface for sorting columns.
  898. *
  899. * @param row
  900. * the new default row, or null for no default row
  901. *
  902. * @throws IllegalArgumentException
  903. * this header does not contain the row
  904. */
  905. public void setDefaultRow(HeaderRow row) {
  906. if (row == defaultRow) {
  907. return;
  908. }
  909. if (row != null && !getRows().contains(row)) {
  910. throw new IllegalArgumentException(
  911. "Cannot set a default row that does not exist in the container");
  912. }
  913. if (defaultRow != null) {
  914. defaultRow.setDefault(false);
  915. }
  916. if (row != null) {
  917. row.setDefault(true);
  918. }
  919. defaultRow = row;
  920. requestSectionRefresh();
  921. }
  922. /**
  923. * Returns the current default row of this header. The default row is a
  924. * special header row providing a user interface for sorting columns.
  925. *
  926. * @return the default row or null if no default row set
  927. */
  928. public HeaderRow getDefaultRow() {
  929. return defaultRow;
  930. }
  931. @Override
  932. protected HeaderRow createRow() {
  933. return new HeaderRow();
  934. }
  935. @Override
  936. protected void requestSectionRefresh() {
  937. markAsDirty = true;
  938. /*
  939. * Defer the refresh so if we multiple times call refreshSection()
  940. * (for example when updating cell values) we only get one actual
  941. * refresh in the end.
  942. */
  943. Scheduler.get().scheduleFinally(() -> {
  944. if (markAsDirty) {
  945. markAsDirty = false;
  946. getGrid().refreshHeader();
  947. }
  948. });
  949. }
  950. /**
  951. * Returns the events consumed by the header.
  952. *
  953. * @return a collection of BrowserEvents
  954. */
  955. public Collection<String> getConsumedEvents() {
  956. return Arrays.asList(BrowserEvents.TOUCHSTART,
  957. BrowserEvents.TOUCHMOVE, BrowserEvents.TOUCHEND,
  958. BrowserEvents.TOUCHCANCEL, BrowserEvents.CLICK);
  959. }
  960. @Override
  961. protected void addColumn(Column<?, ?> column) {
  962. super.addColumn(column);
  963. // Add default content for new columns.
  964. if (defaultRow != null) {
  965. column.setDefaultHeaderContent(defaultRow.getCell(column));
  966. }
  967. }
  968. }
  969. /**
  970. * A single row in a grid header section.
  971. *
  972. */
  973. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  974. private boolean isDefault = false;
  975. protected void setDefault(boolean isDefault) {
  976. this.isDefault = isDefault;
  977. if (isDefault) {
  978. for (Column<?, ?> column : getSection().grid.getColumns()) {
  979. column.setDefaultHeaderContent(getCell(column));
  980. }
  981. }
  982. }
  983. public boolean isDefault() {
  984. return isDefault;
  985. }
  986. @Override
  987. protected HeaderCell createCell() {
  988. return new HeaderCell();
  989. }
  990. }
  991. /**
  992. * A single cell in a grid header row. Has a caption and, if it's in a
  993. * default row, a drag handle.
  994. */
  995. public static class HeaderCell extends StaticSection.StaticCell {
  996. }
  997. /**
  998. * Represents the footer section of a Grid. The footer is always empty.
  999. */
  1000. protected static class Footer extends StaticSection<FooterRow> {
  1001. private boolean markAsDirty = false;
  1002. @Override
  1003. protected FooterRow createRow() {
  1004. return new FooterRow();
  1005. }
  1006. @Override
  1007. protected void requestSectionRefresh() {
  1008. markAsDirty = true;
  1009. /*
  1010. * Defer the refresh so if we multiple times call refreshSection()
  1011. * (for example when updating cell values) we only get one actual
  1012. * refresh in the end.
  1013. */
  1014. Scheduler.get().scheduleFinally(() -> {
  1015. if (markAsDirty) {
  1016. markAsDirty = false;
  1017. getGrid().refreshFooter();
  1018. }
  1019. });
  1020. }
  1021. }
  1022. /**
  1023. * A single cell in a grid Footer row. Has a textual caption.
  1024. *
  1025. */
  1026. public static class FooterCell extends StaticSection.StaticCell {
  1027. }
  1028. /**
  1029. * A single row in a grid Footer section.
  1030. *
  1031. */
  1032. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  1033. @Override
  1034. protected FooterCell createCell() {
  1035. return new FooterCell();
  1036. }
  1037. }
  1038. private static class EditorRequestImpl<T> implements EditorRequest<T> {
  1039. /**
  1040. * A callback interface used to notify the invoker of the editor handler
  1041. * of completed editor requests.
  1042. *
  1043. * @param <T>
  1044. * the row data type
  1045. */
  1046. public static interface RequestCallback<T> {
  1047. /**
  1048. * The method that must be called when the request has been
  1049. * processed correctly.
  1050. *
  1051. * @param request
  1052. * the original request object
  1053. */
  1054. public void onSuccess(EditorRequest<T> request);
  1055. /**
  1056. * The method that must be called when processing the request has
  1057. * produced an aborting error.
  1058. *
  1059. * @param request
  1060. * the original request object
  1061. */
  1062. public void onError(EditorRequest<T> request);
  1063. }
  1064. private Grid<T> grid;
  1065. private final int rowIndex;
  1066. private final int columnIndexDOM;
  1067. private RequestCallback<T> callback;
  1068. private boolean completed = false;
  1069. public EditorRequestImpl(Grid<T> grid, int rowIndex, int columnIndexDOM,
  1070. RequestCallback<T> callback) {
  1071. this.grid = grid;
  1072. this.rowIndex = rowIndex;
  1073. this.columnIndexDOM = columnIndexDOM;
  1074. this.callback = callback;
  1075. }
  1076. @Override
  1077. public int getRowIndex() {
  1078. return rowIndex;
  1079. }
  1080. @Override
  1081. public int getColumnIndex() {
  1082. return columnIndexDOM;
  1083. }
  1084. @Override
  1085. public T getRow() {
  1086. return grid.getDataSource().getRow(rowIndex);
  1087. }
  1088. @Override
  1089. public Grid<T> getGrid() {
  1090. return grid;
  1091. }
  1092. @Override
  1093. public Widget getWidget(Grid.Column<?, T> column) {
  1094. Widget w = grid.getEditorWidget(column);
  1095. assert w != null;
  1096. return w;
  1097. }
  1098. private void complete(String errorMessage,
  1099. Collection<Column<?, T>> errorColumns) {
  1100. if (completed) {
  1101. throw new IllegalStateException(
  1102. "An EditorRequest must be completed exactly once");
  1103. }
  1104. completed = true;
  1105. if (errorColumns == null) {
  1106. errorColumns = Collections.emptySet();
  1107. }
  1108. grid.getEditor().setEditorError(errorMessage, errorColumns);
  1109. }
  1110. @Override
  1111. public void success() {
  1112. complete(null, null);
  1113. if (callback != null) {
  1114. callback.onSuccess(this);
  1115. }
  1116. }
  1117. @Override
  1118. public void failure() {
  1119. complete("", null);
  1120. if (callback != null) {
  1121. callback.onError(this);
  1122. }
  1123. }
  1124. @Override
  1125. public boolean isCompleted() {
  1126. return completed;
  1127. }
  1128. }
  1129. /**
  1130. * A wrapper for native DOM events originating from Grid. In addition to the
  1131. * native event, contains a {@link CellReference} instance specifying which
  1132. * cell the event originated from.
  1133. *
  1134. * @since 7.6
  1135. * @param <T>
  1136. * The row type of the grid
  1137. */
  1138. public static class GridEvent<T> {
  1139. private Event event;
  1140. private EventCellReference<T> cell;
  1141. private boolean handled = false;
  1142. protected GridEvent(Event event, EventCellReference<T> cell) {
  1143. this.event = event;
  1144. this.cell = cell;
  1145. }
  1146. /**
  1147. * Returns the wrapped DOM event.
  1148. *
  1149. * @return the DOM event
  1150. */
  1151. public Event getDomEvent() {
  1152. return event;
  1153. }
  1154. /**
  1155. * Returns the Grid cell this event originated from.
  1156. *
  1157. * @return the event cell
  1158. */
  1159. public EventCellReference<T> getCell() {
  1160. return cell;
  1161. }
  1162. /**
  1163. * Returns the Grid instance this event originated from.
  1164. *
  1165. * @return the grid
  1166. */
  1167. public Grid<T> getGrid() {
  1168. return cell.getGrid();
  1169. }
  1170. /**
  1171. * Check whether this event has already been marked as handled.
  1172. *
  1173. * @return whether this event has already been marked as handled
  1174. */
  1175. public boolean isHandled() {
  1176. return handled;
  1177. }
  1178. /**
  1179. * Set the status of this event. Setting to {@code true} effectively
  1180. * marks this event as having already been handled.
  1181. *
  1182. * @param handled
  1183. */
  1184. public void setHandled(boolean handled) {
  1185. this.handled = handled;
  1186. }
  1187. }
  1188. /**
  1189. * A wrapper for native DOM events related to the {@link Editor Grid editor}
  1190. * .
  1191. *
  1192. * @since 7.6
  1193. * @param <T>
  1194. * the row type of the grid
  1195. */
  1196. public static class EditorDomEvent<T> extends GridEvent<T> {
  1197. private final Widget editorWidget;
  1198. protected EditorDomEvent(Event event, EventCellReference<T> cell,
  1199. Widget editorWidget) {
  1200. super(event, cell);
  1201. this.editorWidget = editorWidget;
  1202. }
  1203. /**
  1204. * Returns the editor of the Grid this event originated from.
  1205. *
  1206. * @return the related editor instance
  1207. */
  1208. public Editor<T> getEditor() {
  1209. return getGrid().getEditor();
  1210. }
  1211. /**
  1212. * Returns the currently focused editor widget.
  1213. *
  1214. * @return the focused editor widget or {@code null} if not editable
  1215. */
  1216. public Widget getEditorWidget() {
  1217. return editorWidget;
  1218. }
  1219. /**
  1220. * Returns the row index the editor is open at. If the editor is not
  1221. * open, returns -1.
  1222. *
  1223. * @return the index of the edited row or -1 if editor is not open
  1224. */
  1225. public int getRowIndex() {
  1226. return getEditor().rowIndex;
  1227. }
  1228. /**
  1229. * Returns the DOM column index (excluding hidden columns) the editor
  1230. * was opened at. If the editor is not open, returns -1.
  1231. *
  1232. * @return the column index or -1 if editor is not open
  1233. */
  1234. public int getFocusedColumnIndex() {
  1235. return getEditor().focusedColumnIndexDOM;
  1236. }
  1237. }
  1238. /**
  1239. * An editor UI for Grid rows. A single Grid row at a time can be opened for
  1240. * editing.
  1241. *
  1242. * @since 7.6
  1243. * @param <T>
  1244. * the row type of the grid
  1245. */
  1246. public static class Editor<T> implements DeferredWorker {
  1247. public static final int KEYCODE_SHOW = KeyCodes.KEY_ENTER;
  1248. public static final int KEYCODE_HIDE = KeyCodes.KEY_ESCAPE;
  1249. private static final String ERROR_CLASS_NAME = "error";
  1250. private static final String NOT_EDITABLE_CLASS_NAME = "not-editable";
  1251. /**
  1252. * A handler for events related to the Grid editor. Responsible for
  1253. * opening, moving or closing the editor based on the received event.
  1254. *
  1255. * @since 7.6
  1256. * @author Vaadin Ltd
  1257. * @param <T>
  1258. * the row type of the grid
  1259. */
  1260. public interface EventHandler<T> {
  1261. /**
  1262. * Handles editor-related events in an appropriate way. Opens,
  1263. * moves, or closes the editor based on the given event.
  1264. *
  1265. * @param event
  1266. * the received event
  1267. * @return true if the event was handled and nothing else should be
  1268. * done, false otherwise
  1269. */
  1270. boolean handleEvent(EditorDomEvent<T> event);
  1271. }
  1272. protected enum State {
  1273. INACTIVE, ACTIVATING, BINDING, ACTIVE, SAVING
  1274. }
  1275. private Grid<T> grid;
  1276. private EditorHandler<T> handler;
  1277. private EventHandler<T> eventHandler = GWT
  1278. .create(DefaultEditorEventHandler.class);
  1279. private DivElement editorOverlay = DivElement.as(DOM.createDiv());
  1280. private DivElement cellWrapper = DivElement.as(DOM.createDiv());
  1281. private DivElement frozenCellWrapper = DivElement.as(DOM.createDiv());
  1282. private DivElement messageAndButtonsWrapper = DivElement
  1283. .as(DOM.createDiv());
  1284. private DivElement messageWrapper = DivElement.as(DOM.createDiv());
  1285. private DivElement buttonsWrapper = DivElement.as(DOM.createDiv());
  1286. // Element which contains the error message for the editor
  1287. // Should only be added to the DOM when there's a message to show
  1288. private DivElement message = DivElement.as(DOM.createDiv());
  1289. private Map<Column<?, T>, Widget> columnToWidget = new HashMap<>();
  1290. private List<HandlerRegistration> focusHandlers = new ArrayList<>();
  1291. private boolean enabled = false;
  1292. private State state = State.INACTIVE;
  1293. private int rowIndex = -1;
  1294. private int focusedColumnIndexDOM = -1;
  1295. private String styleName = null;
  1296. private HandlerRegistration hScrollHandler;
  1297. private final Button saveButton;
  1298. private final Button cancelButton;
  1299. private static final int SAVE_TIMEOUT_MS = 5000;
  1300. private final Timer saveTimeout = new Timer() {
  1301. @Override
  1302. public void run() {
  1303. getLogger().warning(
  1304. "Editor save action is taking longer than expected ("
  1305. + SAVE_TIMEOUT_MS + "ms). Does your "
  1306. + EditorHandler.class.getSimpleName()
  1307. + " remember to call success() or fail()?");
  1308. }
  1309. };
  1310. private final EditorRequestImpl.RequestCallback<T> saveRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  1311. @Override
  1312. public void onSuccess(EditorRequest<T> request) {
  1313. if (state == State.SAVING) {
  1314. cleanup();
  1315. cancel(true);
  1316. grid.clearSortOrder();
  1317. }
  1318. }
  1319. @Override
  1320. public void onError(EditorRequest<T> request) {
  1321. if (state == State.SAVING) {
  1322. cleanup();
  1323. }
  1324. }
  1325. private void cleanup() {
  1326. state = State.ACTIVE;
  1327. setButtonsEnabled(true);
  1328. saveTimeout.cancel();
  1329. }
  1330. };
  1331. private static final int BIND_TIMEOUT_MS = 5000;
  1332. private final Timer bindTimeout = new Timer() {
  1333. @Override
  1334. public void run() {
  1335. getLogger().warning(
  1336. "Editor bind action is taking longer than expected ("
  1337. + BIND_TIMEOUT_MS + "ms). Does your "
  1338. + EditorHandler.class.getSimpleName()
  1339. + " remember to call success() or fail()?");
  1340. }
  1341. };
  1342. private final EditorRequestImpl.RequestCallback<T> bindRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  1343. @Override
  1344. public void onSuccess(EditorRequest<T> request) {
  1345. if (state == State.BINDING) {
  1346. state = State.ACTIVE;
  1347. bindTimeout.cancel();
  1348. rowIndex = request.getRowIndex();
  1349. focusedColumnIndexDOM = request.getColumnIndex();
  1350. if (focusedColumnIndexDOM >= 0) {
  1351. // Update internal focus of Grid
  1352. grid.focusCell(rowIndex, focusedColumnIndexDOM);
  1353. }
  1354. showOverlay();
  1355. }
  1356. }
  1357. @Override
  1358. public void onError(EditorRequest<T> request) {
  1359. if (state == State.BINDING) {
  1360. if (rowIndex == -1) {
  1361. doCancel();
  1362. } else {
  1363. state = State.ACTIVE;
  1364. // TODO: Maybe restore focus?
  1365. }
  1366. bindTimeout.cancel();
  1367. }
  1368. }
  1369. };
  1370. /** A set of all the columns that display an error flag. */
  1371. private final Set<Column<?, T>> columnErrors = new HashSet<>();
  1372. private boolean buffered = true;
  1373. /** Original position of editor */
  1374. private double originalTop;
  1375. /** Original scroll position of grid when editor was opened */
  1376. private double originalScrollTop;
  1377. private RowHandle<T> pinnedRowHandle;
  1378. public Editor() {
  1379. saveButton = new Button();
  1380. saveButton.setText(GridConstants.DEFAULT_SAVE_CAPTION);
  1381. saveButton.addClickHandler(event -> {
  1382. save();
  1383. FocusUtil.setFocus(grid, true);
  1384. });
  1385. cancelButton = new Button();
  1386. cancelButton.setText(GridConstants.DEFAULT_CANCEL_CAPTION);
  1387. cancelButton.addClickHandler(event -> {
  1388. cancel();
  1389. FocusUtil.setFocus(grid, true);
  1390. });
  1391. }
  1392. public void setEditorError(String errorMessage,
  1393. Collection<Column<?, T>> errorColumns) {
  1394. if (errorMessage == null) {
  1395. message.removeFromParent();
  1396. } else {
  1397. message.setInnerText(errorMessage);
  1398. if (message.getParentElement() == null) {
  1399. messageWrapper.appendChild(message);
  1400. }
  1401. }
  1402. // In unbuffered mode only show message wrapper if there is an error
  1403. if (!isBuffered()) {
  1404. setMessageAndButtonsWrapperVisible(errorMessage != null);
  1405. }
  1406. if (state == State.ACTIVE || state == State.SAVING) {
  1407. for (Column<?, T> c : grid.getColumns()) {
  1408. grid.getEditor().setEditorColumnError(c,
  1409. errorColumns.contains(c));
  1410. }
  1411. }
  1412. }
  1413. public int getRow() {
  1414. return rowIndex;
  1415. }
  1416. /**
  1417. * If a cell of this Grid had focus once this editRow call was
  1418. * triggered, the editor component at the previously focused column
  1419. * index will be focused.
  1420. *
  1421. * If a Grid cell was not focused prior to calling this method, it will
  1422. * be equivalent to {@code editRow(rowIndex, -1)}.
  1423. *
  1424. * @see #editRow(int, int)
  1425. */
  1426. public void editRow(int rowIndex) {
  1427. // Focus the last focused column in the editor if grid or its child
  1428. // was focused before the edit request
  1429. Cell focusedCell = grid.cellFocusHandler.getFocusedCell();
  1430. Element focusedElement = WidgetUtil.getFocusedElement();
  1431. if (focusedCell != null && focusedElement != null
  1432. && grid.getElement().isOrHasChild(focusedElement)) {
  1433. editRow(rowIndex, focusedCell.getColumn());
  1434. } else {
  1435. editRow(rowIndex, -1);
  1436. }
  1437. }
  1438. /**
  1439. * Opens the editor over the row with the given index and attempts to
  1440. * focus the editor widget in the given column index. Does not move
  1441. * focus if the widget is not focusable or if the column index is -1.
  1442. *
  1443. * @param rowIndex
  1444. * the index of the row to be edited
  1445. * @param columnIndexDOM
  1446. * the column index (excluding hidden columns) of the editor
  1447. * widget that should be initially focused or -1 to not set
  1448. * focus
  1449. *
  1450. * @throws IllegalStateException
  1451. * if this editor is not enabled
  1452. * @throws IllegalStateException
  1453. * if this editor is already in edit mode and in buffered
  1454. * mode
  1455. *
  1456. * @since 7.5
  1457. */
  1458. public void editRow(final int rowIndex, final int columnIndexDOM) {
  1459. if (!enabled) {
  1460. throw new IllegalStateException(
  1461. "Cannot edit row: editor is not enabled");
  1462. }
  1463. if (isWorkPending()) {
  1464. // Request pending a response, don't move try to start another
  1465. // request.
  1466. return;
  1467. }
  1468. if (state != State.INACTIVE && this.rowIndex != rowIndex) {
  1469. if (isBuffered()) {
  1470. throw new IllegalStateException(
  1471. "Cannot edit row: editor already in edit mode");
  1472. } else if (!columnErrors.isEmpty()) {
  1473. // Don't move row if errors are present
  1474. // FIXME: Should attempt bind if error field values have
  1475. // changed.
  1476. return;
  1477. }
  1478. }
  1479. if (columnIndexDOM >= grid.getVisibleColumns().size()) {
  1480. throw new IllegalArgumentException(
  1481. "Edited column index " + columnIndexDOM
  1482. + " was bigger than visible column count.");
  1483. }
  1484. if (this.rowIndex == rowIndex
  1485. && focusedColumnIndexDOM == columnIndexDOM) {
  1486. // NO-OP
  1487. return;
  1488. }
  1489. if (this.rowIndex == rowIndex) {
  1490. if (focusedColumnIndexDOM != columnIndexDOM) {
  1491. if (columnIndexDOM >= grid.getFrozenColumnCount()) {
  1492. // Scroll to new focused column.
  1493. grid.getEscalator().scrollToColumn(columnIndexDOM,
  1494. ScrollDestination.ANY, 0);
  1495. }
  1496. focusedColumnIndexDOM = columnIndexDOM;
  1497. }
  1498. updateHorizontalScrollPosition();
  1499. // Update Grid internal focus and focus widget if possible
  1500. if (focusedColumnIndexDOM >= 0) {
  1501. grid.focusCell(rowIndex, focusedColumnIndexDOM);
  1502. focusColumn(focusedColumnIndexDOM);
  1503. }
  1504. // No need to request anything from the editor handler.
  1505. return;
  1506. }
  1507. state = State.ACTIVATING;
  1508. grid.scrollToRow(rowIndex, ScrollDestination.ANY,
  1509. () -> show(rowIndex, columnIndexDOM));
  1510. }
  1511. /**
  1512. * Cancels the currently active edit and hides the editor. Any changes
  1513. * that are not {@link #save() saved} are lost.
  1514. *
  1515. * @throws IllegalStateException
  1516. * if this editor is not enabled
  1517. * @throws IllegalStateException
  1518. * if this editor is not in edit mode
  1519. */
  1520. public void cancel() {
  1521. cancel(false);
  1522. }
  1523. private void cancel(boolean afterSave) {
  1524. if (!enabled) {
  1525. throw new IllegalStateException(
  1526. "Cannot cancel edit: editor is not enabled");
  1527. }
  1528. if (state == State.INACTIVE) {
  1529. throw new IllegalStateException(
  1530. "Cannot cancel edit: editor is not in edit mode");
  1531. }
  1532. handler.cancel(new EditorRequestImpl<>(grid, rowIndex,
  1533. focusedColumnIndexDOM, null), afterSave);
  1534. doCancel();
  1535. }
  1536. private void doCancel() {
  1537. hideOverlay();
  1538. state = State.INACTIVE;
  1539. rowIndex = -1;
  1540. focusedColumnIndexDOM = -1;
  1541. grid.getEscalator().setScrollLocked(Direction.VERTICAL, false);
  1542. updateSelectionCheckboxesAsNeeded(true);
  1543. }
  1544. private void updateSelectionCheckboxesAsNeeded(boolean isEnabled) {
  1545. // FIXME: This is too much guessing. Define a better way to do this.
  1546. if (grid.selectionColumn != null && grid.selectionColumn
  1547. .getRenderer() instanceof MultiSelectionRenderer) {
  1548. grid.refreshBody();
  1549. HeaderCell cell = grid.getDefaultHeaderRow()
  1550. .getCell(grid.selectionColumn);
  1551. // if lazy provider, then no checkbox
  1552. if (cell.getType() == GridStaticCellType.WIDGET) {
  1553. CheckBox checkBox = (CheckBox) grid.getDefaultHeaderRow()
  1554. .getCell(grid.selectionColumn).getWidget();
  1555. checkBox.setEnabled(isEnabled);
  1556. }
  1557. }
  1558. }
  1559. /**
  1560. * Saves any unsaved changes to the data source and hides the editor.
  1561. *
  1562. * @throws IllegalStateException
  1563. * if this editor is not enabled
  1564. * @throws IllegalStateException
  1565. * if this editor is not in edit mode
  1566. */
  1567. public void save() {
  1568. if (!enabled) {
  1569. throw new IllegalStateException(
  1570. "Cannot save: editor is not enabled");
  1571. }
  1572. if (state != State.ACTIVE) {
  1573. throw new IllegalStateException(
  1574. "Cannot save: editor is not in edit mode");
  1575. }
  1576. state = State.SAVING;
  1577. setButtonsEnabled(false);
  1578. saveTimeout.schedule(SAVE_TIMEOUT_MS);
  1579. EditorRequest<T> request = new EditorRequestImpl<>(grid, rowIndex,
  1580. focusedColumnIndexDOM, saveRequestCallback);
  1581. handler.save(request);
  1582. updateSelectionCheckboxesAsNeeded(true);
  1583. }
  1584. /**
  1585. * Returns the handler responsible for binding data and editor widgets
  1586. * to this editor.
  1587. *
  1588. * @return the editor handler or null if not set
  1589. */
  1590. public EditorHandler<T> getHandler() {
  1591. return handler;
  1592. }
  1593. /**
  1594. * Sets the handler responsible for binding data and editor widgets to
  1595. * this editor.
  1596. *
  1597. * @param rowHandler
  1598. * the new editor handler
  1599. *
  1600. * @throws IllegalStateException
  1601. * if this editor is currently in edit mode
  1602. */
  1603. public void setHandler(EditorHandler<T> rowHandler) {
  1604. if (state != State.INACTIVE) {
  1605. throw new IllegalStateException(
  1606. "Cannot set EditorHandler: editor is currently in edit mode");
  1607. }
  1608. handler = rowHandler;
  1609. }
  1610. public boolean isEnabled() {
  1611. return enabled;
  1612. }
  1613. /**
  1614. * Sets the enabled state of this editor.
  1615. *
  1616. * @param enabled
  1617. * true if enabled, false otherwise
  1618. *
  1619. * @throws IllegalStateException
  1620. * if in edit mode and trying to disable
  1621. * @throws IllegalStateException
  1622. * if the editor handler is not set
  1623. */
  1624. public void setEnabled(boolean enabled) {
  1625. if (!enabled && state != State.INACTIVE) {
  1626. throw new IllegalStateException(
  1627. "Cannot disable: editor is in edit mode");
  1628. } else if (enabled && getHandler() == null) {
  1629. throw new IllegalStateException(
  1630. "Cannot enable: EditorHandler not set");
  1631. }
  1632. this.enabled = enabled;
  1633. }
  1634. protected void show(int rowIndex, int columnIndex) {
  1635. if (state == State.ACTIVATING) {
  1636. state = State.BINDING;
  1637. bindTimeout.schedule(BIND_TIMEOUT_MS);
  1638. EditorRequest<T> request = new EditorRequestImpl<>(grid,
  1639. rowIndex, columnIndex, bindRequestCallback);
  1640. handler.bind(request);
  1641. grid.getEscalator().setScrollLocked(Direction.VERTICAL,
  1642. isBuffered());
  1643. updateSelectionCheckboxesAsNeeded(false);
  1644. }
  1645. }
  1646. protected void setGrid(final Grid<T> grid) {
  1647. assert grid != null : "Grid cannot be null";
  1648. assert this.grid == null : "Can only attach editor to Grid once";
  1649. this.grid = grid;
  1650. }
  1651. protected State getState() {
  1652. return state;
  1653. }
  1654. protected void setState(State state) {
  1655. this.state = state;
  1656. }
  1657. /**
  1658. * Returns the editor widget associated with the given column. If the
  1659. * editor is not active or the column is not
  1660. * {@link Grid.Column#isEditable() editable}, returns null.
  1661. *
  1662. * @param column
  1663. * the column
  1664. * @return the widget if the editor is open and the column is editable,
  1665. * null otherwise
  1666. */
  1667. protected Widget getWidget(Column<?, T> column) {
  1668. return columnToWidget.get(column);
  1669. }
  1670. /**
  1671. * Equivalent to {@code showOverlay()}. The argument is ignored.
  1672. *
  1673. * @param unused
  1674. * ignored argument
  1675. *
  1676. * @deprecated As of 7.5, use {@link #showOverlay()} instead.
  1677. */
  1678. @Deprecated
  1679. protected void showOverlay(TableRowElement unused) {
  1680. showOverlay();
  1681. }
  1682. /**
  1683. * Opens the editor overlay over the table row indicated by
  1684. * {@link #getRow()}.
  1685. *
  1686. * @since 7.5
  1687. */
  1688. protected void showOverlay() {
  1689. // Ensure overlay is hidden initially
  1690. hideOverlay();
  1691. DivElement gridElement = DivElement.as(grid.getElement());
  1692. TableRowElement tr = grid.getEscalator().getBody()
  1693. .getRowElement(rowIndex);
  1694. hScrollHandler = grid.addScrollHandler(event -> {
  1695. updateHorizontalScrollPosition();
  1696. updateVerticalScrollPosition();
  1697. });
  1698. gridElement.appendChild(editorOverlay);
  1699. editorOverlay.appendChild(frozenCellWrapper);
  1700. editorOverlay.appendChild(cellWrapper);
  1701. editorOverlay.appendChild(messageAndButtonsWrapper);
  1702. updateBufferedStyleName();
  1703. // Add class name with selected modifier if the editor is being
  1704. // opened on selected row, see #11634
  1705. String selectedStylename = styleName + "-selected";
  1706. if (grid.isSelected(grid.getDataSource().getRow(getRow()))) {
  1707. cellWrapper.addClassName(selectedStylename);
  1708. } else {
  1709. cellWrapper.removeClassName(selectedStylename);
  1710. }
  1711. int frozenColumns = grid.getVisibleFrozenColumnCount();
  1712. double frozenColumnsWidth = 0;
  1713. double cellHeight = 0;
  1714. for (int i = 0; i < tr.getCells().getLength(); i++) {
  1715. Element cell = createCell(tr.getCells().getItem(i));
  1716. cellHeight = Math.max(cellHeight,
  1717. WidgetUtil.getRequiredHeightBoundingClientRectDouble(
  1718. tr.getCells().getItem(i)));
  1719. Column<?, T> column = grid.getVisibleColumn(i);
  1720. if (i < frozenColumns) {
  1721. frozenCellWrapper.appendChild(cell);
  1722. frozenColumnsWidth += WidgetUtil
  1723. .getRequiredWidthBoundingClientRectDouble(
  1724. tr.getCells().getItem(i));
  1725. } else {
  1726. cellWrapper.appendChild(cell);
  1727. }
  1728. if (column.isEditable()) {
  1729. Widget editor = getHandler().getWidget(column);
  1730. if (editor != null) {
  1731. columnToWidget.put(column, editor);
  1732. grid.attachWidget(editor, cell);
  1733. }
  1734. if (i == focusedColumnIndexDOM) {
  1735. focusColumn(focusedColumnIndexDOM);
  1736. }
  1737. } else {
  1738. cell.addClassName(NOT_EDITABLE_CLASS_NAME);
  1739. cell.addClassName(tr.getCells().getItem(i).getClassName());
  1740. // If the focused or frozen stylename is present it should
  1741. // not be inherited by the editor cell as it is not useful
  1742. // in the editor and would look broken without additional
  1743. // style rules. This is a bit of a hack.
  1744. cell.removeClassName(grid.cellFocusStyleName);
  1745. cell.removeClassName("frozen");
  1746. if (column == grid.selectionColumn) {
  1747. // Duplicate selection column CheckBox
  1748. pinnedRowHandle = grid.getDataSource().getHandle(
  1749. grid.getDataSource().getRow(rowIndex));
  1750. pinnedRowHandle.pin();
  1751. // We need to duplicate the selection CheckBox for the
  1752. // editor overlay since the original one is hidden by
  1753. // the overlay
  1754. final CheckBox checkBox = GWT.create(CheckBox.class);
  1755. checkBox.setStylePrimaryName(grid.getStylePrimaryName()
  1756. + "-selection-checkbox");
  1757. // label of checkbox should only be visible for
  1758. // assistive devices
  1759. checkBox.addStyleName("v-assistive-device-only-label");
  1760. checkBox.setValue(
  1761. grid.isSelected(pinnedRowHandle.getRow()));
  1762. checkBox.sinkEvents(Event.ONCLICK);
  1763. checkBox.addClickHandler(event -> {
  1764. T row = pinnedRowHandle.getRow();
  1765. if (grid.isSelected(row)) {
  1766. grid.deselect(row);
  1767. } else {
  1768. grid.select(row);
  1769. }
  1770. });
  1771. grid.attachWidget(checkBox, cell);
  1772. columnToWidget.put(column, checkBox);
  1773. // Only enable CheckBox in non-buffered mode
  1774. checkBox.setEnabled(!isBuffered());
  1775. } else if (!(column
  1776. .getRenderer() instanceof WidgetRenderer)) {
  1777. // Copy non-widget content directly
  1778. cell.setInnerHTML(
  1779. tr.getCells().getItem(i).getInnerHTML());
  1780. }
  1781. }
  1782. }
  1783. setBounds(frozenCellWrapper, 0, 0, frozenColumnsWidth, 0);
  1784. setBounds(cellWrapper, frozenColumnsWidth, 0,
  1785. tr.getOffsetWidth() - frozenColumnsWidth, cellHeight);
  1786. // Only add these elements once
  1787. if (!messageAndButtonsWrapper.isOrHasChild(messageWrapper)) {
  1788. messageAndButtonsWrapper.appendChild(messageWrapper);
  1789. messageAndButtonsWrapper.appendChild(buttonsWrapper);
  1790. }
  1791. if (isBuffered()) {
  1792. grid.attachWidget(saveButton, buttonsWrapper);
  1793. grid.attachWidget(cancelButton, buttonsWrapper);
  1794. }
  1795. setMessageAndButtonsWrapperVisible(isBuffered());
  1796. updateHorizontalScrollPosition();
  1797. AbstractRowContainer body = (AbstractRowContainer) grid
  1798. .getEscalator().getBody();
  1799. double rowTop = body.getRowTop(tr);
  1800. int bodyTop = body.getElement().getAbsoluteTop();
  1801. int gridTop = gridElement.getAbsoluteTop();
  1802. double overlayTop = rowTop + bodyTop - gridTop;
  1803. originalScrollTop = grid.getScrollTop();
  1804. if (!isBuffered() || buttonsShouldBeRenderedBelow(tr)) {
  1805. // Default case, editor buttons are below the edited row
  1806. editorOverlay.getStyle().setTop(overlayTop, Unit.PX);
  1807. originalTop = overlayTop;
  1808. editorOverlay.getStyle().clearBottom();
  1809. } else {
  1810. // Move message and buttons wrapper on top of cell wrapper if
  1811. // there is not enough space visible space under and fix the
  1812. // overlay from the bottom
  1813. editorOverlay.insertFirst(messageAndButtonsWrapper);
  1814. int gridHeight = grid.getElement().getOffsetHeight();
  1815. double borderHeight = WidgetUtil
  1816. .getBorderBottomThickness(editorOverlay);
  1817. editorOverlay.getStyle().setBottom(gridHeight - overlayTop
  1818. - tr.getOffsetHeight() + borderHeight, Unit.PX);
  1819. editorOverlay.getStyle().clearTop();
  1820. }
  1821. // Do not render over the vertical scrollbar
  1822. editorOverlay.getStyle().setWidth(grid.escalator.getInnerWidth(),
  1823. Unit.PX);
  1824. }
  1825. private void focusColumn(int columnIndexDOM) {
  1826. if (columnIndexDOM < 0
  1827. || columnIndexDOM >= grid.getVisibleColumns().size()) {
  1828. // NO-OP
  1829. return;
  1830. }
  1831. Widget editor = getWidget(grid.getVisibleColumn(columnIndexDOM));
  1832. if (editor instanceof Focusable) {
  1833. ((Focusable) editor).focus();
  1834. } else if (editor instanceof com.google.gwt.user.client.ui.Focusable) {
  1835. ((com.google.gwt.user.client.ui.Focusable) editor)
  1836. .setFocus(true);
  1837. } else {
  1838. grid.focus();
  1839. }
  1840. }
  1841. private boolean buttonsShouldBeRenderedBelow(TableRowElement tr) {
  1842. TableSectionElement tfoot = grid.escalator.getFooter().getElement();
  1843. double tfootPageTop = WidgetUtil.getBoundingClientRect(tfoot)
  1844. .getTop();
  1845. double trPageBottom = WidgetUtil.getBoundingClientRect(tr)
  1846. .getBottom();
  1847. int messageAndButtonsHeight = messageAndButtonsWrapper
  1848. .getOffsetHeight();
  1849. double bottomOfButtons = trPageBottom + messageAndButtonsHeight;
  1850. return bottomOfButtons < tfootPageTop;
  1851. }
  1852. protected void hideOverlay() {
  1853. if (editorOverlay.getParentElement() == null) {
  1854. return;
  1855. }
  1856. if (pinnedRowHandle != null) {
  1857. pinnedRowHandle.unpin();
  1858. pinnedRowHandle = null;
  1859. }
  1860. for (HandlerRegistration r : focusHandlers) {
  1861. r.removeHandler();
  1862. }
  1863. focusHandlers.clear();
  1864. for (Widget w : columnToWidget.values()) {
  1865. setParent(w, null);
  1866. }
  1867. columnToWidget.clear();
  1868. if (isBuffered()) {
  1869. grid.detachWidget(saveButton);
  1870. grid.detachWidget(cancelButton);
  1871. }
  1872. editorOverlay.removeAllChildren();
  1873. cellWrapper.removeAllChildren();
  1874. frozenCellWrapper.removeAllChildren();
  1875. editorOverlay.removeFromParent();
  1876. hScrollHandler.removeHandler();
  1877. clearEditorColumnErrors();
  1878. }
  1879. private void updateBufferedStyleName() {
  1880. if (isBuffered()) {
  1881. editorOverlay.removeClassName("unbuffered");
  1882. editorOverlay.addClassName("buffered");
  1883. } else {
  1884. editorOverlay.removeClassName("buffered");
  1885. editorOverlay.addClassName("unbuffered");
  1886. }
  1887. }
  1888. protected void setStylePrimaryName(String primaryName) {
  1889. if (styleName != null) {
  1890. editorOverlay.removeClassName(styleName);
  1891. cellWrapper.removeClassName(styleName + "-cells");
  1892. frozenCellWrapper.removeClassName(styleName + "-cells");
  1893. messageAndButtonsWrapper.removeClassName(styleName + "-footer");
  1894. messageWrapper.removeClassName(styleName + "-message");
  1895. buttonsWrapper.removeClassName(styleName + "-buttons");
  1896. saveButton.removeStyleName(styleName + "-save");
  1897. cancelButton.removeStyleName(styleName + "-cancel");
  1898. }
  1899. styleName = primaryName + "-editor";
  1900. editorOverlay.setClassName(styleName);
  1901. cellWrapper.setClassName(styleName + "-cells");
  1902. frozenCellWrapper.setClassName(styleName + "-cells frozen");
  1903. messageAndButtonsWrapper.setClassName(styleName + "-footer");
  1904. messageWrapper.setClassName(styleName + "-message");
  1905. buttonsWrapper.setClassName(styleName + "-buttons");
  1906. saveButton.setStyleName(styleName + "-save");
  1907. cancelButton.setStyleName(styleName + "-cancel");
  1908. }
  1909. /**
  1910. * Creates an editor cell corresponding to the given table cell. The
  1911. * returned element is empty and has the same dimensions and position as
  1912. * the table cell.
  1913. *
  1914. * @param td
  1915. * the table cell used as a reference
  1916. * @return an editor cell corresponding to the given cell
  1917. */
  1918. protected Element createCell(TableCellElement td) {
  1919. DivElement cell = DivElement.as(DOM.createDiv());
  1920. double width = WidgetUtil
  1921. .getRequiredWidthBoundingClientRectDouble(td);
  1922. double height = WidgetUtil
  1923. .getRequiredHeightBoundingClientRectDouble(td);
  1924. setBounds(cell, td.getOffsetLeft(), td.getOffsetTop(), width,
  1925. height);
  1926. return cell;
  1927. }
  1928. private static void setBounds(Element e, double left, double top,
  1929. double width, double height) {
  1930. Style style = e.getStyle();
  1931. style.setLeft(left, Unit.PX);
  1932. style.setTop(top, Unit.PX);
  1933. style.setWidth(width, Unit.PX);
  1934. style.setHeight(height, Unit.PX);
  1935. }
  1936. private void updateHorizontalScrollPosition() {
  1937. double scrollLeft = grid.getScrollLeft();
  1938. cellWrapper.getStyle().setLeft(
  1939. frozenCellWrapper.getOffsetWidth() - scrollLeft, Unit.PX);
  1940. }
  1941. /**
  1942. * Moves the editor overlay on scroll so that it stays on top of the
  1943. * edited row. This will also snap the editor to top or bottom of the
  1944. * row container if the edited row is scrolled out of the visible area.
  1945. */
  1946. private void updateVerticalScrollPosition() {
  1947. if (isBuffered()) {
  1948. return;
  1949. }
  1950. double newScrollTop = grid.getScrollTop();
  1951. int gridTop = grid.getElement().getAbsoluteTop();
  1952. int editorHeight = editorOverlay.getOffsetHeight();
  1953. Escalator escalator = grid.getEscalator();
  1954. TableSectionElement header = escalator.getHeader().getElement();
  1955. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  1956. int headerBottom = header.getAbsoluteBottom();
  1957. double newTop = originalTop - (newScrollTop - originalScrollTop);
  1958. if (newTop + gridTop < headerBottom) {
  1959. // Snap editor to top of the row container
  1960. newTop = header.getOffsetHeight();
  1961. } else if (newTop + gridTop > footerTop - editorHeight) {
  1962. // Snap editor to the bottom of the row container
  1963. newTop = footerTop - editorHeight - gridTop;
  1964. }
  1965. editorOverlay.getStyle().setTop(newTop, Unit.PX);
  1966. }
  1967. protected void setGridEnabled(boolean enabled) {
  1968. // TODO: This should be informed to handler as well so possible
  1969. // fields can be disabled.
  1970. setButtonsEnabled(enabled);
  1971. }
  1972. private void setButtonsEnabled(boolean enabled) {
  1973. saveButton.setEnabled(enabled);
  1974. cancelButton.setEnabled(enabled);
  1975. }
  1976. public void setSaveCaption(String saveCaption)
  1977. throws IllegalArgumentException {
  1978. if (saveCaption == null) {
  1979. throw new IllegalArgumentException(
  1980. "Save caption cannot be null");
  1981. }
  1982. saveButton.setText(saveCaption);
  1983. }
  1984. public String getSaveCaption() {
  1985. return saveButton.getText();
  1986. }
  1987. public void setCancelCaption(String cancelCaption)
  1988. throws IllegalArgumentException {
  1989. if (cancelCaption == null) {
  1990. throw new IllegalArgumentException(
  1991. "Cancel caption cannot be null");
  1992. }
  1993. cancelButton.setText(cancelCaption);
  1994. }
  1995. public String getCancelCaption() {
  1996. return cancelButton.getText();
  1997. }
  1998. public void setEditorColumnError(Column<?, T> column,
  1999. boolean hasError) {
  2000. if (state != State.ACTIVE && state != State.SAVING) {
  2001. throw new IllegalStateException("Cannot set cell error "
  2002. + "status: editor is neither active nor saving.");
  2003. }
  2004. if (isEditorColumnError(column) == hasError) {
  2005. return;
  2006. }
  2007. Element editorCell = getWidget(column).getElement()
  2008. .getParentElement();
  2009. if (hasError) {
  2010. editorCell.addClassName(ERROR_CLASS_NAME);
  2011. columnErrors.add(column);
  2012. } else {
  2013. editorCell.removeClassName(ERROR_CLASS_NAME);
  2014. columnErrors.remove(column);
  2015. }
  2016. }
  2017. public void clearEditorColumnErrors() {
  2018. /*
  2019. * editorOverlay has no children if it's not active, effectively
  2020. * making this loop a NOOP.
  2021. */
  2022. Element e = editorOverlay.getFirstChildElement();
  2023. while (e != null) {
  2024. e.removeClassName(ERROR_CLASS_NAME);
  2025. e = e.getNextSiblingElement();
  2026. }
  2027. columnErrors.clear();
  2028. }
  2029. public boolean isEditorColumnError(Column<?, T> column) {
  2030. return columnErrors.contains(column);
  2031. }
  2032. public void setBuffered(boolean buffered) {
  2033. this.buffered = buffered;
  2034. setMessageAndButtonsWrapperVisible(buffered);
  2035. }
  2036. public boolean isBuffered() {
  2037. return buffered;
  2038. }
  2039. private void setMessageAndButtonsWrapperVisible(boolean visible) {
  2040. if (visible) {
  2041. messageAndButtonsWrapper.getStyle().clearDisplay();
  2042. } else {
  2043. messageAndButtonsWrapper.getStyle().setDisplay(Display.NONE);
  2044. }
  2045. }
  2046. /**
  2047. * Sets the event handler for this Editor.
  2048. *
  2049. * @since 7.6
  2050. * @param handler
  2051. * the new event handler
  2052. */
  2053. public void setEventHandler(EventHandler<T> handler) {
  2054. eventHandler = handler;
  2055. }
  2056. /**
  2057. * Returns the event handler of this Editor.
  2058. *
  2059. * @since 7.6
  2060. * @return the current event handler
  2061. */
  2062. public EventHandler<T> getEventHandler() {
  2063. return eventHandler;
  2064. }
  2065. @Override
  2066. public boolean isWorkPending() {
  2067. return saveTimeout.isRunning() || bindTimeout.isRunning();
  2068. }
  2069. protected int getElementColumn(Element e) {
  2070. int frozenCells = frozenCellWrapper.getChildCount();
  2071. if (frozenCellWrapper.isOrHasChild(e)) {
  2072. for (int i = 0; i < frozenCells; ++i) {
  2073. if (frozenCellWrapper.getChild(i).isOrHasChild(e)) {
  2074. return i;
  2075. }
  2076. }
  2077. }
  2078. if (cellWrapper.isOrHasChild(e)) {
  2079. for (int i = 0; i < cellWrapper.getChildCount(); ++i) {
  2080. if (cellWrapper.getChild(i).isOrHasChild(e)) {
  2081. return i + frozenCells;
  2082. }
  2083. }
  2084. }
  2085. return -1;
  2086. }
  2087. }
  2088. public abstract static class AbstractGridKeyEvent<HANDLER extends AbstractGridKeyEventHandler>
  2089. extends KeyEvent<HANDLER> {
  2090. /**
  2091. * @since 7.7.9
  2092. */
  2093. public AbstractGridKeyEvent() {
  2094. }
  2095. /**
  2096. * @deprecated This constructor's arguments are no longer used. Use the
  2097. * no-args constructor instead.
  2098. */
  2099. @Deprecated
  2100. public AbstractGridKeyEvent(Grid<?> grid, CellReference<?> targetCell) {
  2101. }
  2102. protected abstract String getBrowserEventType();
  2103. /**
  2104. * Gets the Grid instance for this event, if it originated from a Grid.
  2105. *
  2106. * @return the grid this event originated from, or {@code null} if this
  2107. * event did not originate from a grid
  2108. */
  2109. public Grid<?> getGrid() {
  2110. EventTarget target = getNativeEvent().getEventTarget();
  2111. if (!Element.is(target)) {
  2112. return null;
  2113. }
  2114. return WidgetUtil.findWidget(Element.as(target), Grid.class, false);
  2115. }
  2116. /**
  2117. * Gets the reference of target cell for this event, if this event
  2118. * originated from a Grid.
  2119. *
  2120. * @return target cell, or {@code null} if this event did not originate
  2121. * from a grid
  2122. */
  2123. public CellReference<?> getFocusedCell() {
  2124. return getGrid().getEventCell();
  2125. }
  2126. @Override
  2127. protected void dispatch(HANDLER handler) {
  2128. EventTarget target = getNativeEvent().getEventTarget();
  2129. Grid<?> grid = getGrid();
  2130. if (Element.is(target) && grid != null) {
  2131. final RowContainer container = Stream
  2132. .of(grid.escalator.getHeader(),
  2133. grid.escalator.getBody(),
  2134. grid.escalator.getFooter())
  2135. .filter(c -> c.getCell(target.cast()) != null)
  2136. .findFirst()
  2137. .orElse(grid.cellFocusHandler.containerWithFocus);
  2138. Section section = Section.FOOTER;
  2139. if (container == grid.escalator.getHeader()) {
  2140. section = Section.HEADER;
  2141. } else if (container == getGrid().escalator.getBody()) {
  2142. section = Section.BODY;
  2143. }
  2144. // Don't handle event of child widget unless the column has been
  2145. // explicitly permitted to do so
  2146. if (grid.isElementInChildWidget(Element.as(target))) {
  2147. Cell cell = container.getCell(target.cast());
  2148. if (cell != null) {
  2149. Column<?, ?> column = grid
  2150. .getVisibleColumn(cell.getColumn());
  2151. if (column == null || !column.isHandleWidgetEvents()) {
  2152. return;
  2153. }
  2154. }
  2155. }
  2156. doDispatch(handler, section);
  2157. }
  2158. }
  2159. protected abstract void doDispatch(HANDLER handler, Section section);
  2160. }
  2161. public abstract static class AbstractGridMouseEvent<HANDLER extends AbstractGridMouseEventHandler>
  2162. extends MouseEvent<HANDLER> {
  2163. /**
  2164. * @since 7.7.9
  2165. */
  2166. public AbstractGridMouseEvent() {
  2167. }
  2168. /**
  2169. * @deprecated This constructor's arguments are no longer used. Use the
  2170. * no-args constructor instead.
  2171. */
  2172. @Deprecated
  2173. public AbstractGridMouseEvent(Grid<?> grid,
  2174. CellReference<?> targetCell) {
  2175. }
  2176. protected abstract String getBrowserEventType();
  2177. /**
  2178. * Gets the Grid instance for this event, if it originated from a Grid.
  2179. *
  2180. * @return the grid this event originated from, or {@code null} if this
  2181. * event did not originate from a grid
  2182. */
  2183. public Grid<?> getGrid() {
  2184. EventTarget target = getNativeEvent().getEventTarget();
  2185. if (!Element.is(target)) {
  2186. return null;
  2187. }
  2188. return WidgetUtil.findWidget(Element.as(target), Grid.class, false);
  2189. }
  2190. /**
  2191. * Gets the reference of target cell for this event, if this event
  2192. * originated from a Grid.
  2193. *
  2194. * @return target cell, or {@code null} if this event did not originate
  2195. * from a grid
  2196. */
  2197. public CellReference<?> getTargetCell() {
  2198. Grid<?> grid = getGrid();
  2199. if (grid == null) {
  2200. return null;
  2201. }
  2202. return grid.getEventCell();
  2203. }
  2204. @Override
  2205. protected void dispatch(HANDLER handler) {
  2206. EventTarget target = getNativeEvent().getEventTarget();
  2207. if (!Element.is(target)) {
  2208. // Target is not an element
  2209. return;
  2210. }
  2211. Grid<?> grid = getGrid();
  2212. if (grid == null) {
  2213. // Target is not an element of a grid
  2214. return;
  2215. }
  2216. Element targetElement = Element.as(target);
  2217. if (ignoreEventFromTarget(grid, targetElement)) {
  2218. // Event on this target should be ignored
  2219. return;
  2220. }
  2221. final RowContainer container = grid.escalator
  2222. .findRowContainer(targetElement);
  2223. if (container == null) {
  2224. // No container for given element
  2225. return;
  2226. }
  2227. Section section = Section.FOOTER;
  2228. if (container == grid.escalator.getHeader()) {
  2229. section = Section.HEADER;
  2230. } else if (container == grid.escalator.getBody()) {
  2231. section = Section.BODY;
  2232. }
  2233. doDispatch(handler, section);
  2234. }
  2235. /**
  2236. * Returns whether the mouse event on the target element should be
  2237. * ignored.
  2238. *
  2239. * @param grid
  2240. * the {@code Grid} instance from which the event originated
  2241. * @param targetElement
  2242. * the element from which the event originated
  2243. * @return {@code true} if the event should be ignored, {@code false} if
  2244. * it should be handled
  2245. * @since 8.2
  2246. */
  2247. protected boolean ignoreEventFromTarget(Grid<?> grid,
  2248. Element targetElement) {
  2249. boolean childWidget = grid.isElementInChildWidget(targetElement);
  2250. boolean handleWidgetEvent = false;
  2251. RowContainer container = grid.getEscalator()
  2252. .findRowContainer(targetElement);
  2253. if (container != null) {
  2254. Cell cell = container.getCell(targetElement);
  2255. if (cell != null) {
  2256. Column<?, ?> column = grid
  2257. .getVisibleColumn(cell.getColumn());
  2258. handleWidgetEvent = column != null
  2259. && column.isHandleWidgetEvents();
  2260. }
  2261. }
  2262. return childWidget && !handleWidgetEvent;
  2263. }
  2264. protected abstract void doDispatch(HANDLER handler, Section section);
  2265. }
  2266. private static final String CUSTOM_STYLE_PROPERTY_NAME = "customStyle";
  2267. /**
  2268. * An initial height that is given to new details rows before rendering the
  2269. * appropriate widget that we then can be measure
  2270. *
  2271. * @see Grid.GridSpacerUpdater
  2272. */
  2273. private static final double DETAILS_ROW_INITIAL_HEIGHT = 50;
  2274. private EventCellReference<T> eventCell = new EventCellReference<T>(this);
  2275. private class CellFocusHandler {
  2276. private RowContainer containerWithFocus = escalator.getBody();
  2277. private int rowWithFocus = 0;
  2278. private Range cellFocusRange = Range.withLength(0, 1);
  2279. private int lastFocusedBodyRow = 0;
  2280. private int lastFocusedHeaderRow = 0;
  2281. private int lastFocusedFooterRow = 0;
  2282. private TableCellElement cellWithFocusStyle = null;
  2283. private TableRowElement rowWithFocusStyle = null;
  2284. public CellFocusHandler() {
  2285. sinkEvents(getNavigationEvents());
  2286. }
  2287. private Cell getFocusedCell() {
  2288. return new Cell(rowWithFocus, cellFocusRange.getStart(),
  2289. cellWithFocusStyle);
  2290. }
  2291. /**
  2292. * Sets style names for given cell when needed.
  2293. */
  2294. public void updateFocusedCellStyle(FlyweightCell cell,
  2295. RowContainer cellContainer) {
  2296. int cellRow = cell.getRow();
  2297. int cellColumn = cell.getColumn();
  2298. int colSpan = cell.getColSpan();
  2299. boolean columnHasFocus = Range.withLength(cellColumn, colSpan)
  2300. .intersects(cellFocusRange);
  2301. if (cellContainer == containerWithFocus) {
  2302. // Cell is in the current container
  2303. if (cellRow == rowWithFocus && columnHasFocus) {
  2304. if (cellWithFocusStyle != cell.getElement()) {
  2305. // Cell is correct but it does not have focused style
  2306. if (cellWithFocusStyle != null) {
  2307. // Remove old focus style
  2308. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2309. false);
  2310. }
  2311. cellWithFocusStyle = cell.getElement();
  2312. // Add focus style to correct cell.
  2313. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2314. true);
  2315. }
  2316. } else if (cellWithFocusStyle == cell.getElement()) {
  2317. // Due to escalator reusing cells, a new cell has the same
  2318. // element but is not the focused cell.
  2319. setStyleName(cellWithFocusStyle, cellFocusStyleName, false);
  2320. cellWithFocusStyle = null;
  2321. }
  2322. }
  2323. }
  2324. /**
  2325. * Sets focus style for the given row if needed.
  2326. *
  2327. * @param row
  2328. * a row object
  2329. */
  2330. public void updateFocusedRowStyle(Row row) {
  2331. if (rowWithFocus == row.getRow()
  2332. && containerWithFocus == escalator.getBody()) {
  2333. if (row.getElement() != rowWithFocusStyle) {
  2334. // Row should have focus style but does not have it.
  2335. if (rowWithFocusStyle != null) {
  2336. setStyleName(rowWithFocusStyle, rowFocusStyleName,
  2337. false);
  2338. }
  2339. rowWithFocusStyle = row.getElement();
  2340. setStyleName(rowWithFocusStyle, rowFocusStyleName, true);
  2341. }
  2342. } else if (rowWithFocusStyle == row.getElement()
  2343. || containerWithFocus != escalator.getBody()
  2344. && rowWithFocusStyle != null) {
  2345. // Remove focus style.
  2346. setStyleName(rowWithFocusStyle, rowFocusStyleName, false);
  2347. rowWithFocusStyle = null;
  2348. }
  2349. }
  2350. /**
  2351. * Sets the currently focused.
  2352. * <p>
  2353. * <em>NOTE:</em> the column index is the index in DOM, not the logical
  2354. * column index which includes hidden columns.
  2355. *
  2356. * @param rowIndex
  2357. * the index of the row having focus
  2358. * @param columnIndexDOM
  2359. * the index of the cell having focus
  2360. * @param container
  2361. * the row container having focus
  2362. */
  2363. private void setCellFocus(int rowIndex, int columnIndexDOM,
  2364. RowContainer container) {
  2365. if (container == null || rowIndex == rowWithFocus
  2366. && cellFocusRange.contains(columnIndexDOM)
  2367. && container == this.containerWithFocus) {
  2368. return;
  2369. }
  2370. int oldRow = rowWithFocus;
  2371. rowWithFocus = rowIndex;
  2372. Range oldRange = cellFocusRange;
  2373. if (container == escalator.getBody()) {
  2374. scrollToRow(rowWithFocus);
  2375. cellFocusRange = Range.withLength(columnIndexDOM, 1);
  2376. } else {
  2377. int i = 0;
  2378. Element cell = container.getRowElement(rowWithFocus)
  2379. .getFirstChildElement();
  2380. do {
  2381. int colSpan = cell
  2382. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  2383. Range cellRange = Range.withLength(i, colSpan);
  2384. if (cellRange.contains(columnIndexDOM)) {
  2385. cellFocusRange = cellRange;
  2386. break;
  2387. }
  2388. cell = cell.getNextSiblingElement();
  2389. ++i;
  2390. } while (cell != null);
  2391. }
  2392. if (columnIndexDOM >= escalator.getColumnConfiguration()
  2393. .getFrozenColumnCount()) {
  2394. escalator.scrollToColumn(columnIndexDOM, ScrollDestination.ANY,
  2395. 10);
  2396. }
  2397. if (this.containerWithFocus == container) {
  2398. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  2399. refreshRow(oldRow);
  2400. } else {
  2401. refreshHeader();
  2402. refreshFooter();
  2403. }
  2404. } else {
  2405. RowContainer oldContainer = this.containerWithFocus;
  2406. this.containerWithFocus = container;
  2407. if (oldContainer == escalator.getBody()) {
  2408. lastFocusedBodyRow = oldRow;
  2409. } else if (oldContainer == escalator.getHeader()) {
  2410. lastFocusedHeaderRow = oldRow;
  2411. } else {
  2412. lastFocusedFooterRow = oldRow;
  2413. }
  2414. if (!oldRange.equals(cellFocusRange)) {
  2415. refreshHeader();
  2416. refreshFooter();
  2417. if (oldContainer == escalator.getBody()) {
  2418. oldContainer.refreshRows(oldRow, 1);
  2419. }
  2420. } else {
  2421. oldContainer.refreshRows(oldRow, 1);
  2422. }
  2423. }
  2424. refreshRow(rowWithFocus);
  2425. }
  2426. /**
  2427. * Sets focus on a cell.
  2428. *
  2429. * <p>
  2430. * <em>Note</em>: cell focus is not the same as JavaScript's
  2431. * {@code document.activeElement}.
  2432. *
  2433. * @param cell
  2434. * a cell object
  2435. */
  2436. public void setCellFocus(CellReference<T> cell) {
  2437. setCellFocus(cell.getRowIndex(), cell.getColumnIndexDOM(),
  2438. escalator.findRowContainer(cell.getElement()));
  2439. }
  2440. /**
  2441. * Gets list of events that can be used for cell focusing.
  2442. *
  2443. * @return list of navigation related event types
  2444. */
  2445. public Collection<String> getNavigationEvents() {
  2446. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  2447. }
  2448. /**
  2449. * Handle events that can move the cell focus.
  2450. */
  2451. public void handleNavigationEvent(Event event, CellReference<T> cell) {
  2452. if (event.getType().equals(BrowserEvents.CLICK)) {
  2453. setCellFocus(cell);
  2454. // Grid should have focus when clicked.
  2455. getElement().focus();
  2456. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  2457. int newRow = rowWithFocus;
  2458. RowContainer newContainer = containerWithFocus;
  2459. int newColumn = cellFocusRange.getStart();
  2460. switch (event.getKeyCode()) {
  2461. case KeyCodes.KEY_DOWN:
  2462. ++newRow;
  2463. break;
  2464. case KeyCodes.KEY_UP:
  2465. --newRow;
  2466. break;
  2467. case KeyCodes.KEY_RIGHT:
  2468. if (cellFocusRange.getEnd() >= getVisibleColumns().size()) {
  2469. return;
  2470. }
  2471. newColumn = cellFocusRange.getEnd();
  2472. break;
  2473. case KeyCodes.KEY_LEFT:
  2474. if (newColumn == 0) {
  2475. return;
  2476. }
  2477. --newColumn;
  2478. break;
  2479. case KeyCodes.KEY_TAB:
  2480. if (event.getShiftKey()) {
  2481. newContainer = getPreviousContainer(containerWithFocus);
  2482. } else {
  2483. newContainer = getNextContainer(containerWithFocus);
  2484. }
  2485. if (newContainer == containerWithFocus) {
  2486. return;
  2487. }
  2488. break;
  2489. case KeyCodes.KEY_HOME:
  2490. if (newContainer.getRowCount() > 0) {
  2491. newRow = 0;
  2492. }
  2493. break;
  2494. case KeyCodes.KEY_END:
  2495. if (newContainer.getRowCount() > 0) {
  2496. newRow = newContainer.getRowCount() - 1;
  2497. }
  2498. break;
  2499. case KeyCodes.KEY_PAGEDOWN:
  2500. case KeyCodes.KEY_PAGEUP:
  2501. if (newContainer.getRowCount() > 0) {
  2502. boolean down = event
  2503. .getKeyCode() == KeyCodes.KEY_PAGEDOWN;
  2504. // If there is a visible focused cell, scroll by one
  2505. // page from its position. Otherwise, use the first or
  2506. // the last visible row as the scroll start position.
  2507. // This avoids jumping when using both keyboard and the
  2508. // scroll bar for scrolling.
  2509. int firstVisible = getFirstVisibleRowIndex();
  2510. int lastVisible = getLastVisibleRowIndex();
  2511. if (newRow < firstVisible || newRow > lastVisible) {
  2512. newRow = down ? lastVisible : firstVisible;
  2513. }
  2514. // Scroll by a little less than the visible area to
  2515. // account for the possibility that the top and the
  2516. // bottom row are only partially visible.
  2517. int moveFocusBy = Math.max(1,
  2518. lastVisible - firstVisible - 1);
  2519. moveFocusBy *= down ? 1 : -1;
  2520. newRow += moveFocusBy;
  2521. newRow = Math.max(0, Math
  2522. .min(newContainer.getRowCount() - 1, newRow));
  2523. }
  2524. break;
  2525. default:
  2526. return;
  2527. }
  2528. if (newContainer != containerWithFocus) {
  2529. if (newContainer == escalator.getBody()) {
  2530. newRow = lastFocusedBodyRow;
  2531. } else if (newContainer == escalator.getHeader()) {
  2532. newRow = lastFocusedHeaderRow;
  2533. } else {
  2534. newRow = lastFocusedFooterRow;
  2535. }
  2536. } else if (newRow < 0) {
  2537. newContainer = getPreviousContainer(newContainer);
  2538. if (newContainer == containerWithFocus) {
  2539. newRow = 0;
  2540. } else if (newContainer == escalator.getBody()) {
  2541. newRow = getLastVisibleRowIndex();
  2542. } else {
  2543. newRow = newContainer.getRowCount() - 1;
  2544. }
  2545. } else if (newRow >= containerWithFocus.getRowCount()) {
  2546. newContainer = getNextContainer(newContainer);
  2547. if (newContainer == containerWithFocus) {
  2548. newRow = containerWithFocus.getRowCount() - 1;
  2549. } else if (newContainer == escalator.getBody()) {
  2550. newRow = getFirstVisibleRowIndex();
  2551. } else {
  2552. newRow = 0;
  2553. }
  2554. }
  2555. if (newContainer.getRowCount() == 0) {
  2556. /*
  2557. * There are no rows in the container. Can't change the
  2558. * focused cell.
  2559. */
  2560. return;
  2561. }
  2562. event.preventDefault();
  2563. event.stopPropagation();
  2564. setCellFocus(newRow, newColumn, newContainer);
  2565. }
  2566. }
  2567. private RowContainer getPreviousContainer(RowContainer current) {
  2568. if (current == escalator.getFooter()) {
  2569. current = escalator.getBody();
  2570. } else if (current == escalator.getBody()) {
  2571. current = escalator.getHeader();
  2572. } else {
  2573. return current;
  2574. }
  2575. if (current.getRowCount() == 0) {
  2576. return getPreviousContainer(current);
  2577. }
  2578. return current;
  2579. }
  2580. private RowContainer getNextContainer(RowContainer current) {
  2581. if (current == escalator.getHeader()) {
  2582. current = escalator.getBody();
  2583. } else if (current == escalator.getBody()) {
  2584. current = escalator.getFooter();
  2585. } else {
  2586. return current;
  2587. }
  2588. if (current.getRowCount() == 0) {
  2589. return getNextContainer(current);
  2590. }
  2591. return current;
  2592. }
  2593. private void refreshRow(int row) {
  2594. containerWithFocus.refreshRows(row, 1);
  2595. }
  2596. /**
  2597. * Offsets the focused cell's range.
  2598. *
  2599. * @param offset
  2600. * offset for fixing focused cell's range
  2601. */
  2602. public void offsetRangeBy(int offset) {
  2603. cellFocusRange = cellFocusRange.offsetBy(offset);
  2604. }
  2605. /**
  2606. * Informs {@link CellFocusHandler} that certain range of rows has been
  2607. * added to the Grid body. {@link CellFocusHandler} will fix indices
  2608. * accordingly.
  2609. *
  2610. * @param added
  2611. * a range of added rows
  2612. */
  2613. public void rowsAddedToBody(Range added) {
  2614. boolean bodyHasFocus = containerWithFocus == escalator.getBody();
  2615. boolean insertionIsAboveFocusedCell = added
  2616. .getStart() < rowWithFocus;
  2617. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  2618. rowWithFocus += added.length();
  2619. rowWithFocus = Math.min(rowWithFocus,
  2620. escalator.getBody().getRowCount() - 1);
  2621. refreshRow(rowWithFocus);
  2622. }
  2623. }
  2624. /**
  2625. * Informs {@link CellFocusHandler} that certain range of rows has been
  2626. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  2627. * accordingly.
  2628. *
  2629. * @param removed
  2630. * a range of removed rows
  2631. */
  2632. public void rowsRemovedFromBody(Range removed) {
  2633. if (containerWithFocus != escalator.getBody()) {
  2634. return;
  2635. } else if (!removed.contains(rowWithFocus)) {
  2636. if (removed.getStart() > rowWithFocus) {
  2637. return;
  2638. }
  2639. rowWithFocus = rowWithFocus - removed.length();
  2640. } else {
  2641. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  2642. rowWithFocus = removed.getStart();
  2643. } else if (removed.getStart() > 0) {
  2644. rowWithFocus = removed.getStart() - 1;
  2645. } else {
  2646. if (escalator.getHeader().getRowCount() > 0) {
  2647. rowWithFocus = Math.min(lastFocusedHeaderRow,
  2648. escalator.getHeader().getRowCount() - 1);
  2649. containerWithFocus = escalator.getHeader();
  2650. } else if (escalator.getFooter().getRowCount() > 0) {
  2651. rowWithFocus = Math.min(lastFocusedFooterRow,
  2652. escalator.getFooter().getRowCount() - 1);
  2653. containerWithFocus = escalator.getFooter();
  2654. }
  2655. }
  2656. }
  2657. refreshRow(rowWithFocus);
  2658. }
  2659. }
  2660. public final class SelectionColumn extends Column<Boolean, T>
  2661. implements GridEnabledHandler, GridSelectionAllowedHandler {
  2662. private boolean initDone = false;
  2663. private boolean selected = false;
  2664. private CheckBox selectAllCheckBox;
  2665. private boolean selectAllCheckBoxVisible;
  2666. private HeaderCell selectionCell;
  2667. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  2668. super(selectColumnRenderer);
  2669. addEnabledHandler(this);
  2670. addSelectionAllowedHandler(this);
  2671. }
  2672. void initDone() {
  2673. setWidth(-1);
  2674. setEditable(false);
  2675. setResizable(false);
  2676. updateEnable();
  2677. initDone = true;
  2678. }
  2679. @Override
  2680. protected void setDefaultHeaderContent(HeaderCell selectionCell) {
  2681. this.selectionCell = selectionCell;
  2682. if (selectAllCheckBox == null) {
  2683. // there is no checkbox yet -> create it
  2684. selectAllCheckBox = GWT.create(CheckBox.class);
  2685. selectAllCheckBox.setStylePrimaryName(
  2686. getStylePrimaryName() + SELECT_ALL_CHECKBOX_CLASSNAME);
  2687. // label of checkbox should only be visible for assistive
  2688. // devices
  2689. selectAllCheckBox.addStyleName("v-assistive-device-only-label");
  2690. selectAllCheckBox.addValueChangeHandler(event -> {
  2691. selected = event.getValue();
  2692. fireEvent(new SelectAllEvent<>(getSelectionModel(),
  2693. selected));
  2694. });
  2695. selectAllCheckBox.setText("Selects all rows of the table.");
  2696. selectAllCheckBox.setValue(selected);
  2697. addHeaderClickHandler(this::onHeaderClickEvent);
  2698. // Select all with space when "select all" cell is active
  2699. addHeaderKeyUpHandler(this::onHeaderKeyUpEvent);
  2700. } else {
  2701. // checkbox exists, but default header row has changed -> clear
  2702. // rows
  2703. for (HeaderRow row : header.getRows()) {
  2704. if (row.getCell(this)
  2705. .getType() == GridStaticCellType.WIDGET) {
  2706. // Detach from old header.
  2707. row.getCell(this).setText("");
  2708. }
  2709. }
  2710. }
  2711. // attach the checkbox to default row depending on visibility
  2712. doSetSelectAllCheckBoxVisible();
  2713. }
  2714. @Override
  2715. public Column<Boolean, T> setWidth(double pixels) {
  2716. if (pixels != getWidth() && initDone) {
  2717. throw new UnsupportedOperationException("The selection "
  2718. + "column cannot be modified after init");
  2719. } else {
  2720. super.setWidth(pixels);
  2721. }
  2722. return this;
  2723. }
  2724. @Override
  2725. public Boolean getValue(T row) {
  2726. return Boolean.valueOf(isSelected(row));
  2727. }
  2728. @Override
  2729. public Column<Boolean, T> setExpandRatio(int ratio) {
  2730. throw new UnsupportedOperationException(
  2731. "can't change the expand ratio of the selection column");
  2732. }
  2733. @Override
  2734. public int getExpandRatio() {
  2735. return 0;
  2736. }
  2737. @Override
  2738. public Column<Boolean, T> setMaximumWidth(double pixels) {
  2739. throw new UnsupportedOperationException(
  2740. "can't change the maximum width of the selection column");
  2741. }
  2742. @Override
  2743. public double getMaximumWidth() {
  2744. return -1;
  2745. }
  2746. @Override
  2747. public Column<Boolean, T> setMinimumWidth(double pixels) {
  2748. throw new UnsupportedOperationException(
  2749. "can't change the minimum width of the selection column");
  2750. }
  2751. @Override
  2752. public double getMinimumWidth() {
  2753. return -1;
  2754. }
  2755. @Override
  2756. public Column<Boolean, T> setEditable(boolean editable) {
  2757. if (initDone) {
  2758. throw new UnsupportedOperationException(
  2759. "can't set the selection column editable");
  2760. }
  2761. super.setEditable(editable);
  2762. return this;
  2763. }
  2764. @Override
  2765. public void onEnabled(boolean enabled) {
  2766. updateEnable();
  2767. }
  2768. /**
  2769. * Sets the select all checkbox visible in the default header row for
  2770. * selection column.
  2771. *
  2772. * @param selectAllCheckBoxVisible
  2773. * {@code true} for visible, {@code false} for not
  2774. */
  2775. public void setSelectAllCheckBoxVisible(
  2776. boolean selectAllCheckBoxVisible) {
  2777. if (this.selectAllCheckBoxVisible != selectAllCheckBoxVisible) {
  2778. this.selectAllCheckBoxVisible = selectAllCheckBoxVisible;
  2779. doSetSelectAllCheckBoxVisible();
  2780. }
  2781. }
  2782. /**
  2783. * Returns whether the select all checkbox is visible or not.
  2784. *
  2785. * @return {@code true} for visible, {@code false} for not
  2786. */
  2787. public boolean isSelectAllCheckBoxVisible() {
  2788. return selectAllCheckBoxVisible;
  2789. }
  2790. /**
  2791. * Returns the select all checkbox, which is present in the default
  2792. * header if the used selection model is of type
  2793. * {@link SelectionModelWithSelectionColumn}.
  2794. *
  2795. * To handle select all, add {@link SelectAllHandler} the grid with
  2796. * {@link #addSelectAllHandler(SelectAllHandler)}.
  2797. *
  2798. * @return the select all checkbox, or an empty optional if not in use
  2799. */
  2800. public Optional<CheckBox> getSelectAllCheckBox() {
  2801. return Optional.ofNullable(selectionColumn == null ? null
  2802. : selectionColumn.selectAllCheckBox);
  2803. }
  2804. /**
  2805. * Sets the select all checkbox visible or hidden.
  2806. */
  2807. protected void doSetSelectAllCheckBoxVisible() {
  2808. if (selectAllCheckBox == null || selectionCell == null) {
  2809. // There is no default header row to display select all checkbox
  2810. return;
  2811. }
  2812. if (selectAllCheckBoxVisible) {
  2813. selectionCell.setWidget(selectAllCheckBox);
  2814. } else {
  2815. selectionCell.setText("");
  2816. }
  2817. }
  2818. private void updateEnable() {
  2819. if (selectAllCheckBox != null) {
  2820. selectAllCheckBox.setEnabled(isEnabled()
  2821. && getSelectionModel().isSelectionAllowed());
  2822. }
  2823. }
  2824. private void onHeaderClickEvent(GridClickEvent event) {
  2825. if (selectAllCheckBox.isEnabled()) {
  2826. CellReference<?> targetCell = event.getTargetCell();
  2827. int defaultRowIndex = getHeader().getRows()
  2828. .indexOf(getDefaultHeaderRow());
  2829. if (targetCell.getColumnIndex() == 0
  2830. && targetCell.getRowIndex() == defaultRowIndex) {
  2831. selectAllCheckBox.setValue(!selectAllCheckBox.getValue(),
  2832. true);
  2833. }
  2834. }
  2835. }
  2836. private void onHeaderKeyUpEvent(GridKeyUpEvent event) {
  2837. if (event.getNativeKeyCode() != KeyCodes.KEY_SPACE
  2838. || !selectAllCheckBox.isEnabled()) {
  2839. return;
  2840. }
  2841. HeaderRow targetHeaderRow = getHeader()
  2842. .getRow(event.getFocusedCell().getRowIndex());
  2843. if (!targetHeaderRow.isDefault()) {
  2844. return;
  2845. }
  2846. if (event.getFocusedCell().getColumn() == SelectionColumn.this) {
  2847. // Send events to ensure state is updated
  2848. selectAllCheckBox.setValue(!selectAllCheckBox.getValue(), true);
  2849. }
  2850. }
  2851. @Override
  2852. public void onSelectionAllowed(GridSelectionAllowedEvent event) {
  2853. updateEnable();
  2854. }
  2855. }
  2856. /**
  2857. * Helper class for performing sorting through the user interface. Controls
  2858. * the sort() method, reporting USER as the event originator. This is a
  2859. * completely internal class, and is, as such, safe to re-name should a more
  2860. * descriptive name come to mind.
  2861. */
  2862. private final class UserSorter {
  2863. private final Timer timer;
  2864. private boolean scheduledMultisort;
  2865. private Column<?, T> column;
  2866. private UserSorter() {
  2867. timer = new Timer() {
  2868. @Override
  2869. public void run() {
  2870. scheduledMultisort = true;
  2871. }
  2872. };
  2873. }
  2874. /**
  2875. * Toggle sorting for a cell. If the multisort parameter is set to true,
  2876. * the cell's sort order is modified as a natural part of a multi-sort
  2877. * chain. If false, the sorting order is set to ASCENDING for that
  2878. * cell's column. If that column was already the only sorted column in
  2879. * the Grid, the sort direction is flipped.
  2880. *
  2881. * @param cell
  2882. * a valid cell reference
  2883. * @param multisort
  2884. * whether the sort command should act as a multi-sort stack
  2885. * or not
  2886. */
  2887. public void sort(Column<?, ?> column, boolean multisort) {
  2888. if (!columns.contains(column)) {
  2889. throw new IllegalArgumentException(
  2890. "Given column is not a column in this grid. " + column);
  2891. }
  2892. if (!column.isSortable()) {
  2893. return;
  2894. }
  2895. final SortOrder so = getSortOrder(column);
  2896. if (multisort) {
  2897. // If the sort order exists, replace existing value with its
  2898. // opposite
  2899. if (so != null) {
  2900. final int idx = sortOrder.indexOf(so);
  2901. sortOrder.set(idx, so.getOpposite());
  2902. } else {
  2903. // If it doesn't, just add a new sort order to the end of
  2904. // the list
  2905. sortOrder.add(new SortOrder(column));
  2906. }
  2907. } else {
  2908. // Since we're doing single column sorting, first clear the
  2909. // list. Then, if the sort order existed, add its opposite,
  2910. // otherwise just add a new sort value
  2911. int items = sortOrder.size();
  2912. sortOrder.clear();
  2913. if (so != null && items == 1) {
  2914. sortOrder.add(so.getOpposite());
  2915. } else {
  2916. sortOrder.add(new SortOrder(column));
  2917. }
  2918. }
  2919. // sortOrder has been changed; tell the Grid to re-sort itself by
  2920. // user request.
  2921. Grid.this.sort(true);
  2922. }
  2923. /**
  2924. * Invoked on touchstart, marks itself that we will perform sorting on
  2925. * touchend. By default single sort is performed, however on long touch
  2926. * we will perform multitouch.
  2927. *
  2928. * Actual sorting is only performed after {@link #onTouchEnd()} is
  2929. * invoked.
  2930. *
  2931. * @param delay
  2932. * delay, in milliseconds
  2933. */
  2934. public void awaitForTouchEnd(int delay) {
  2935. cancelAwaitForTouchEnd();
  2936. column = eventCell.getColumn();
  2937. scheduledMultisort = false;
  2938. timer.schedule(delay);
  2939. }
  2940. /**
  2941. * Notifies that the finger has been lifted from the tablet/mobile.
  2942. * Depending on how much time has passed, we need to perform singlesort
  2943. * or multisort.
  2944. *
  2945. * Does nothing if the await has been canceled by a call to
  2946. * {@link #cancelAwaitForTouchEnd()}.
  2947. */
  2948. public void onTouchEnd() {
  2949. if (column != null) {
  2950. sort(column, scheduledMultisort);
  2951. cancelAwaitForTouchEnd();
  2952. }
  2953. }
  2954. /**
  2955. * Cancel a scheduled sort.
  2956. */
  2957. public void cancelAwaitForTouchEnd() {
  2958. timer.cancel();
  2959. column = null;
  2960. }
  2961. }
  2962. /**
  2963. * @see Grid#autoColumnWidthsRecalculator
  2964. */
  2965. private class AutoColumnWidthsRecalculator {
  2966. private double lastCalculatedInnerWidth = -1;
  2967. private double lastCalculatedInnerHeight = -1;
  2968. private final ScheduledCommand calculateCommand = new ScheduledCommand() {
  2969. @Override
  2970. public void execute() {
  2971. if (!isScheduled) {
  2972. // something cancelled running this.
  2973. return;
  2974. }
  2975. if (header.markAsDirty || footer.markAsDirty) {
  2976. if (rescheduleCount < 10) {
  2977. /*
  2978. * Headers and footers are rendered as finally, this way
  2979. * we re-schedule this loop as finally, at the end of
  2980. * the queue, so that the headers have a chance to
  2981. * render themselves.
  2982. */
  2983. Scheduler.get().scheduleFinally(this);
  2984. rescheduleCount++;
  2985. } else {
  2986. /*
  2987. * We've tried too many times reschedule finally. Seems
  2988. * like something is being deferred. Let the queue
  2989. * execute and retry again.
  2990. */
  2991. rescheduleCount = 0;
  2992. Scheduler.get().scheduleDeferred(this);
  2993. }
  2994. } else if (currentDataAvailable.isEmpty()
  2995. && (dataSource.isWaitingForData()
  2996. || escalator.getBody().getRowCount() > 0)) {
  2997. Scheduler.get().scheduleDeferred(this);
  2998. } else {
  2999. calculate();
  3000. }
  3001. }
  3002. };
  3003. private int rescheduleCount = 0;
  3004. private boolean isScheduled;
  3005. /**
  3006. * Calculates and applies column widths, taking into account fixed
  3007. * widths and column expand rules.
  3008. *
  3009. * @see Column#setWidth(double)
  3010. * @see Column#setExpandRatio(int)
  3011. * @see Column#setMinimumWidth(double)
  3012. * @see Column#setMaximumWidth(double)
  3013. */
  3014. public void schedule() {
  3015. if (!isScheduled && isAttached() && !(currentDataAvailable.isEmpty()
  3016. && escalator.getBody().getRowCount() > 0)) {
  3017. isScheduled = true;
  3018. Scheduler.get().scheduleFinally(calculateCommand);
  3019. }
  3020. }
  3021. private void calculate() {
  3022. isScheduled = false;
  3023. rescheduleCount = 0;
  3024. assert !(currentDataAvailable.isEmpty() && dataSource
  3025. .isWaitingForData()) : "Trying to calculate column widths without data while data is still being fetched.";
  3026. // Make SelectAllCheckbox visible
  3027. getSelectionColumn().ifPresent(col -> {
  3028. if (getDefaultHeaderRow() == null) {
  3029. return;
  3030. }
  3031. HeaderCell headerCell = getDefaultHeaderRow().getCell(col);
  3032. if (headerCell.getType().equals(GridStaticCellType.WIDGET)) {
  3033. // SelectAllCheckbox is present already
  3034. return;
  3035. }
  3036. headerCell.setWidget(col.selectAllCheckBox);
  3037. refreshHeader(); // Paint.
  3038. });
  3039. if (columnsAreGuaranteedToBeWiderThanGrid()) {
  3040. applyColumnWidths();
  3041. } else {
  3042. applyColumnWidthsWithExpansion();
  3043. }
  3044. // Hide the SelectAllCheckbox if needed
  3045. getSelectionColumn()
  3046. .ifPresent(SelectionColumn::doSetSelectAllCheckBoxVisible);
  3047. // Update latest width to prevent recalculate on height change.
  3048. lastCalculatedInnerWidth = escalator.getInnerWidth();
  3049. lastCalculatedInnerHeight = escalator.getInnerHeight();
  3050. }
  3051. private boolean columnsAreGuaranteedToBeWiderThanGrid() {
  3052. double freeSpace = escalator.getInnerWidth();
  3053. for (Column<?, ?> column : getVisibleColumns()) {
  3054. /*
  3055. * Check the width and min width and ensure that no column can
  3056. * be expected to be narrower than what the resize handler
  3057. * requires, if one is present.
  3058. */
  3059. if (column.getWidth() >= 0) {
  3060. if (column.isResizable() && resizeHandleWidth > 0) {
  3061. freeSpace -= Math.max(resizeHandleWidth,
  3062. column.getWidth());
  3063. } else {
  3064. freeSpace -= column.getWidth();
  3065. }
  3066. } else if (column.getMinimumWidth() >= 0) {
  3067. if (column.isResizable() && resizeHandleWidth > 0) {
  3068. freeSpace -= Math.max(resizeHandleWidth,
  3069. column.getMinimumWidth());
  3070. } else {
  3071. freeSpace -= column.getMinimumWidth();
  3072. }
  3073. } else if (column.isResizable() && resizeHandleWidth > 0) {
  3074. freeSpace -= resizeHandleWidth;
  3075. }
  3076. }
  3077. return freeSpace < 0;
  3078. }
  3079. @SuppressWarnings("boxing")
  3080. private void applyColumnWidths() {
  3081. /* Step 1: Apply all column widths as they are. */
  3082. Map<Integer, Double> selfWidths = new LinkedHashMap<>();
  3083. List<Column<?, T>> columns = getVisibleColumns();
  3084. for (int index = 0; index < columns.size(); index++) {
  3085. selfWidths.put(index, columns.get(index).getWidth());
  3086. }
  3087. Grid.this.escalator.getColumnConfiguration()
  3088. .setColumnWidths(selfWidths, true);
  3089. /*
  3090. * Step 2: Make sure that each column ends up obeying their min/max
  3091. * width constraints if defined as autowidth. If constraints are
  3092. * violated, fix it.
  3093. */
  3094. Map<Integer, Double> constrainedWidths = new LinkedHashMap<>();
  3095. for (int index = 0; index < columns.size(); index++) {
  3096. Column<?, T> column = columns.get(index);
  3097. boolean hasAutoWidth = column.getWidth() < 0;
  3098. if (!hasAutoWidth) {
  3099. continue;
  3100. }
  3101. // TODO: bug: these don't honor the CSS max/min. :(
  3102. double actualWidth = column.getWidthActual();
  3103. if (actualWidth < getMinWidth(column)) {
  3104. constrainedWidths.put(index, column.getMinimumWidth());
  3105. } else if (actualWidth > getMaxWidth(column)) {
  3106. constrainedWidths.put(index, column.getMaximumWidth());
  3107. }
  3108. }
  3109. Grid.this.escalator.getColumnConfiguration()
  3110. .setColumnWidths(constrainedWidths, true);
  3111. }
  3112. private void applyColumnWidthsWithExpansion() {
  3113. boolean defaultExpandRatios = true;
  3114. int totalRatios = 0;
  3115. double reservedPixels = 0;
  3116. final Set<Column<?, T>> columnsToExpand = new HashSet<>();
  3117. List<Column<?, T>> nonFixedColumns = new ArrayList<>();
  3118. Map<Integer, Double> columnSizes = new HashMap<>();
  3119. final List<Column<?, T>> visibleColumns = getVisibleColumns();
  3120. /*
  3121. * Set all fixed widths and also calculate the size-to-fit widths
  3122. * for the autocalculated columns.
  3123. *
  3124. * This way we know with how many pixels we have left to expand the
  3125. * rest.
  3126. */
  3127. for (Column<?, T> column : visibleColumns) {
  3128. final double widthAsIs = column.getWidth();
  3129. final boolean isFixedWidth = widthAsIs >= 0;
  3130. defaultExpandRatios = defaultExpandRatios
  3131. && (column.getExpandRatio() == -1
  3132. || column == selectionColumn);
  3133. if (isFixedWidth) {
  3134. // Check for min & max width just to be sure we don't break
  3135. // the limits
  3136. double widthFixed = Math.max(
  3137. Math.min(getMaxWidth(column), widthAsIs),
  3138. column.getMinimumWidth());
  3139. if (column.isResizable() && resizeHandleWidth > 0) {
  3140. // Ensure the resize handle fits
  3141. widthFixed = Math.max(widthFixed, resizeHandleWidth);
  3142. }
  3143. columnSizes.put(visibleColumns.indexOf(column), widthFixed);
  3144. reservedPixels += widthFixed;
  3145. } else {
  3146. nonFixedColumns.add(column);
  3147. columnSizes.put(visibleColumns.indexOf(column), -1.0d);
  3148. }
  3149. }
  3150. /*
  3151. * Set column sizes so that it's possible to measure non-fixed
  3152. * actual sizes without previously applied expand ratio tweaks, but
  3153. * don't trigger the element size recalculation before the rest of
  3154. * this method has also been processed.
  3155. */
  3156. setColumnSizes(columnSizes, false);
  3157. for (Column<?, T> column : nonFixedColumns) {
  3158. final int expandRatio = defaultExpandRatios ? 1
  3159. : column.getExpandRatio();
  3160. final double maxWidth = getMaxWidth(column);
  3161. double newWidth;
  3162. if (column.isMinimumWidthFromContent()) {
  3163. if (column.isResizable() && resizeHandleWidth > 0) {
  3164. // Ensure the resize handle fits
  3165. newWidth = Math.max(
  3166. Math.min(maxWidth, column.getWidthActual()),
  3167. resizeHandleWidth);
  3168. } else {
  3169. newWidth = Math.min(maxWidth, column.getWidthActual());
  3170. }
  3171. } else {
  3172. if (column.isResizable() && resizeHandleWidth > 0) {
  3173. // Ensure the resize handle fits
  3174. newWidth = resizeHandleWidth;
  3175. } else {
  3176. newWidth = 0;
  3177. }
  3178. }
  3179. boolean shouldExpand = newWidth < maxWidth && expandRatio > 0
  3180. && column != selectionColumn;
  3181. if (shouldExpand) {
  3182. totalRatios += expandRatio;
  3183. columnsToExpand.add(column);
  3184. }
  3185. reservedPixels += newWidth;
  3186. columnSizes.put(visibleColumns.indexOf(column), newWidth);
  3187. }
  3188. /*
  3189. * Now that we know how many pixels we need at the very least, we
  3190. * can distribute the remaining pixels to all columns according to
  3191. * their expand ratios.
  3192. */
  3193. double pixelsToDistribute = escalator.getInnerWidth()
  3194. - reservedPixels;
  3195. if (pixelsToDistribute <= 0 || totalRatios <= 0) {
  3196. if (pixelsToDistribute <= 0) {
  3197. // Set column sizes for expanding columns
  3198. setColumnSizes(columnSizes, true);
  3199. }
  3200. /*
  3201. * If pixelsToDistribute > 0 the element size recalculation
  3202. * isn't done at all, even if some column sizes were set
  3203. * earlier, but this doesn't appear to be detrimental while
  3204. * attempting to trigger the recalculation here breaks a
  3205. * GridEditRow test.
  3206. */
  3207. return;
  3208. }
  3209. /*
  3210. * Check for columns that hit their max width. Adjust
  3211. * pixelsToDistribute and totalRatios accordingly. Recheck. Stop
  3212. * when no new columns hit their max width
  3213. */
  3214. boolean aColumnHasMaxedOut;
  3215. do {
  3216. aColumnHasMaxedOut = false;
  3217. final double widthPerRatio = pixelsToDistribute / totalRatios;
  3218. final Iterator<Column<?, T>> i = columnsToExpand.iterator();
  3219. while (i.hasNext()) {
  3220. final Column<?, T> column = i.next();
  3221. final int expandRatio = getExpandRatio(column,
  3222. defaultExpandRatios);
  3223. final int columnIndex = visibleColumns.indexOf(column);
  3224. final double autoWidth = columnSizes.get(columnIndex);
  3225. final double maxWidth = getMaxWidth(column);
  3226. double expandedWidth = autoWidth
  3227. + widthPerRatio * expandRatio;
  3228. if (maxWidth <= expandedWidth) {
  3229. i.remove();
  3230. totalRatios -= expandRatio;
  3231. aColumnHasMaxedOut = true;
  3232. pixelsToDistribute -= maxWidth - autoWidth;
  3233. columnSizes.put(columnIndex, maxWidth);
  3234. }
  3235. }
  3236. } while (aColumnHasMaxedOut);
  3237. if (totalRatios <= 0 && columnsToExpand.isEmpty()) {
  3238. setColumnSizes(columnSizes, true);
  3239. return;
  3240. }
  3241. assert pixelsToDistribute > 0 : "We've run out of pixels to distribute ("
  3242. + pixelsToDistribute + "px to " + totalRatios
  3243. + " ratios between " + columnsToExpand.size() + " columns)";
  3244. assert totalRatios > 0 && !columnsToExpand
  3245. .isEmpty() : "Bookkeeping out of sync. Ratios: "
  3246. + totalRatios + " Columns: "
  3247. + columnsToExpand.size();
  3248. /*
  3249. * If we still have anything left, distribute the remaining pixels
  3250. * to the remaining columns.
  3251. */
  3252. final double widthPerRatio;
  3253. int leftOver = 0;
  3254. if (BrowserInfo.getBrowserString().contains("PhantomJS")) {
  3255. // These browsers report subpixels as integers. this usually
  3256. // results into issues..
  3257. widthPerRatio = (int) (pixelsToDistribute / totalRatios);
  3258. leftOver = (int) (pixelsToDistribute
  3259. - widthPerRatio * totalRatios);
  3260. } else {
  3261. widthPerRatio = pixelsToDistribute / totalRatios;
  3262. }
  3263. for (Column<?, T> column : columnsToExpand) {
  3264. final int expandRatio = getExpandRatio(column,
  3265. defaultExpandRatios);
  3266. final int columnIndex = visibleColumns.indexOf(column);
  3267. final double autoWidth = columnSizes.get(columnIndex);
  3268. double totalWidth = autoWidth + widthPerRatio * expandRatio;
  3269. if (leftOver > 0) {
  3270. totalWidth += 1;
  3271. leftOver--;
  3272. }
  3273. columnSizes.put(columnIndex, totalWidth);
  3274. totalRatios -= expandRatio;
  3275. }
  3276. assert totalRatios == 0 : "Bookkeeping error: there were still some ratios left undistributed: "
  3277. + totalRatios;
  3278. /*
  3279. * Check the guarantees for minimum width and scoot back the columns
  3280. * that don't care.
  3281. */
  3282. boolean minWidthsCausedReflows;
  3283. do {
  3284. minWidthsCausedReflows = false;
  3285. /*
  3286. * First, let's check which columns were too cramped, and expand
  3287. * them. Also keep track on how many pixels we grew - we need to
  3288. * remove those pixels from other columns
  3289. */
  3290. double pixelsToRemoveFromOtherColumns = 0;
  3291. for (Column<?, T> column : visibleColumns) {
  3292. /*
  3293. * We can't iterate over columnsToExpand, even though that
  3294. * would be convenient. This is because some column without
  3295. * an expand ratio might still have a min width - those
  3296. * wouldn't show up in that set.
  3297. */
  3298. double minWidth = getMinWidth(column);
  3299. final int columnIndex = visibleColumns.indexOf(column);
  3300. double currentWidth = columnSizes.get(columnIndex);
  3301. boolean hasAutoWidth = column.getWidth() < 0;
  3302. if (hasAutoWidth && currentWidth < minWidth) {
  3303. columnSizes.put(columnIndex, minWidth);
  3304. pixelsToRemoveFromOtherColumns += minWidth
  3305. - currentWidth;
  3306. minWidthsCausedReflows = true;
  3307. /*
  3308. * Remove this column form the set if it exists. This
  3309. * way we make sure that it doesn't get shrunk in the
  3310. * next step.
  3311. */
  3312. columnsToExpand.remove(column);
  3313. }
  3314. }
  3315. /*
  3316. * Now we need to shrink the remaining columns according to
  3317. * their ratios. Recalculate the sum of remaining ratios.
  3318. */
  3319. totalRatios = 0;
  3320. for (Column<?, ?> column : columnsToExpand) {
  3321. totalRatios += getExpandRatio(column, defaultExpandRatios);
  3322. }
  3323. final double pixelsToRemovePerRatio = pixelsToRemoveFromOtherColumns
  3324. / totalRatios;
  3325. for (Column<?, T> column : columnsToExpand) {
  3326. final double pixelsToRemove = pixelsToRemovePerRatio
  3327. * getExpandRatio(column, defaultExpandRatios);
  3328. int colIndex = visibleColumns.indexOf(column);
  3329. columnSizes.put(colIndex,
  3330. columnSizes.get(colIndex) - pixelsToRemove);
  3331. }
  3332. } while (minWidthsCausedReflows);
  3333. // Finally set all the column sizes.
  3334. setColumnSizes(columnSizes, true);
  3335. }
  3336. private void setColumnSizes(Map<Integer, Double> columnSizes,
  3337. boolean recalculateElementSizes) {
  3338. // Set all widths at once
  3339. escalator.getColumnConfiguration().setColumnWidths(columnSizes,
  3340. recalculateElementSizes);
  3341. }
  3342. private int getExpandRatio(Column<?, ?> column,
  3343. boolean defaultExpandRatios) {
  3344. int expandRatio = column.getExpandRatio();
  3345. if (expandRatio > 0) {
  3346. return expandRatio;
  3347. } else if (expandRatio < 0) {
  3348. assert defaultExpandRatios : "No columns should've expanded";
  3349. return 1;
  3350. } else {
  3351. assert false : "this method should've not been called at all if expandRatio is 0";
  3352. return 0;
  3353. }
  3354. }
  3355. /**
  3356. * Returns the maximum width of the column, or {@link Double#MAX_VALUE}
  3357. * if defined as negative.
  3358. */
  3359. private double getMaxWidth(Column<?, ?> column) {
  3360. double maxWidth = column.getMaximumWidth();
  3361. if (maxWidth >= 0) {
  3362. return maxWidth;
  3363. } else {
  3364. return Double.MAX_VALUE;
  3365. }
  3366. }
  3367. /**
  3368. * Returns the minimum width of the column, or {@link Double#MIN_VALUE}
  3369. * if defined as negative.
  3370. */
  3371. private double getMinWidth(Column<?, ?> column) {
  3372. double minWidth = column.getMinimumWidth();
  3373. if (minWidth >= 0) {
  3374. return minWidth;
  3375. } else {
  3376. return Double.MIN_VALUE;
  3377. }
  3378. }
  3379. /**
  3380. * Check whether the auto width calculation is currently scheduled.
  3381. *
  3382. * @return <code>true</code> if auto width calculation is currently
  3383. * scheduled
  3384. */
  3385. public boolean isScheduled() {
  3386. return isScheduled;
  3387. }
  3388. }
  3389. private class GridSpacerUpdater implements SpacerUpdater {
  3390. private static final String STRIPE_CLASSNAME = "stripe";
  3391. private final Map<Element, Widget> elementToWidgetMap = new HashMap<>();
  3392. @Override
  3393. public void init(Spacer spacer) {
  3394. initTheming(spacer);
  3395. int rowIndex = spacer.getRow();
  3396. Widget detailsWidget = null;
  3397. try {
  3398. detailsWidget = detailsGenerator.getDetails(rowIndex);
  3399. } catch (Throwable e) {
  3400. getLogger().log(Level.SEVERE,
  3401. "Exception while generating details for row "
  3402. + rowIndex,
  3403. e);
  3404. }
  3405. final double spacerHeight;
  3406. Element spacerElement = spacer.getElement();
  3407. if (detailsWidget == null) {
  3408. spacerElement.removeAllChildren();
  3409. spacerHeight = DETAILS_ROW_INITIAL_HEIGHT;
  3410. } else {
  3411. Element element = detailsWidget.getElement();
  3412. spacerElement.appendChild(element);
  3413. setParent(detailsWidget, Grid.this);
  3414. Widget previousWidget = elementToWidgetMap.put(element,
  3415. detailsWidget);
  3416. assert previousWidget == null : "Overwrote a pre-existing widget on row "
  3417. + rowIndex + " without proper removal first.";
  3418. /*
  3419. * Once we have the content properly inside the DOM, we should
  3420. * re-measure it to make sure that it's the correct height.
  3421. *
  3422. * This is rather tricky, since the row (tr) will get the
  3423. * height, but the spacer cell (td) has the borders, which
  3424. * should go on top of the previous row and next row.
  3425. */
  3426. final double contentHeight;
  3427. if (detailsGenerator instanceof HeightAwareDetailsGenerator) {
  3428. HeightAwareDetailsGenerator sadg = (HeightAwareDetailsGenerator) detailsGenerator;
  3429. contentHeight = sadg.getDetailsHeight(rowIndex);
  3430. } else {
  3431. contentHeight = WidgetUtil
  3432. .getRequiredHeightBoundingClientRectDouble(element);
  3433. }
  3434. double borderTopAndBottomHeight = WidgetUtil
  3435. .getBorderTopAndBottomThickness(spacerElement);
  3436. double measuredHeight = 0d;
  3437. if (contentHeight > 0) {
  3438. measuredHeight = contentHeight + borderTopAndBottomHeight;
  3439. } else {
  3440. Scheduler.get().scheduleFinally(() -> {
  3441. // make sure the spacer hasn't got removed
  3442. if (spacer.getElement().getParentElement() != null) {
  3443. // re-check the height
  3444. double confirmedContentHeight = WidgetUtil
  3445. .getRequiredHeightBoundingClientRectDouble(
  3446. element);
  3447. if (confirmedContentHeight > 0) {
  3448. double confirmedMeasuredHeight = confirmedContentHeight
  3449. + WidgetUtil
  3450. .getBorderTopAndBottomThickness(
  3451. spacer.getElement());
  3452. escalator.getBody().setSpacer(spacer.getRow(),
  3453. confirmedMeasuredHeight);
  3454. if (getHeightMode() == HeightMode.UNDEFINED) {
  3455. setHeightByRows(getEscalator().getBody()
  3456. .getRowCount());
  3457. }
  3458. }
  3459. }
  3460. });
  3461. }
  3462. assert getElement().isOrHasChild(
  3463. spacerElement) : "The spacer element wasn't in the DOM during measurement, but was assumed to be.";
  3464. spacerHeight = measuredHeight;
  3465. }
  3466. escalator.getBody().setSpacer(rowIndex, spacerHeight);
  3467. if (getHeightMode() == HeightMode.UNDEFINED) {
  3468. setHeightByRows(getEscalator().getBody().getRowCount());
  3469. }
  3470. }
  3471. @Override
  3472. public void destroy(Spacer spacer) {
  3473. Element spacerElement = spacer.getElement();
  3474. assert getElement().isOrHasChild(spacerElement) : "Trying "
  3475. + "to destroy a spacer that is not connected to this "
  3476. + "Grid's DOM. (row: " + spacer.getRow() + ", element: "
  3477. + spacerElement + ")";
  3478. Widget detailsWidget = elementToWidgetMap
  3479. .remove(spacerElement.getFirstChildElement());
  3480. if (detailsWidget != null) {
  3481. /*
  3482. * The widget may be null here if the previous generator
  3483. * returned a null widget.
  3484. */
  3485. assert spacerElement.getFirstChild() != null : "The "
  3486. + "details row to destroy did not contain a widget - "
  3487. + "probably removed by something else without "
  3488. + "permission? (row: " + spacer.getRow() + ", element: "
  3489. + spacerElement + ")";
  3490. setParent(detailsWidget, null);
  3491. spacerElement.removeAllChildren();
  3492. if (getHeightMode() == HeightMode.UNDEFINED) {
  3493. setHeightByRows(getEscalator().getBody().getRowCount());
  3494. }
  3495. }
  3496. }
  3497. private void initTheming(Spacer spacer) {
  3498. Element spacerRoot = spacer.getElement();
  3499. if (spacer.getRow() % 2 == 1) {
  3500. spacerRoot.getParentElement().addClassName(STRIPE_CLASSNAME);
  3501. } else {
  3502. spacerRoot.getParentElement().removeClassName(STRIPE_CLASSNAME);
  3503. }
  3504. }
  3505. }
  3506. /**
  3507. * Sidebar displaying toggles for hidable columns and custom widgets
  3508. * provided by the application.
  3509. * <p>
  3510. * The button for opening the sidebar is automatically visible inside the
  3511. * grid, if it contains any column hiding options or custom widgets. The
  3512. * column hiding toggles and custom widgets become visible once the sidebar
  3513. * has been opened.
  3514. *
  3515. * @since 7.5.0
  3516. */
  3517. private static class Sidebar extends Composite implements HasEnabled {
  3518. private final ClickHandler openCloseButtonHandler = event -> {
  3519. if (!isOpen()) {
  3520. open();
  3521. } else {
  3522. close();
  3523. }
  3524. };
  3525. private final FlowPanel rootContainer;
  3526. private final FlowPanel content;
  3527. private final MenuBar menuBar;
  3528. private final Button openCloseButton;
  3529. private final Grid<?> grid;
  3530. private Overlay overlay;
  3531. private Sidebar(Grid<?> grid) {
  3532. this.grid = grid;
  3533. rootContainer = new FlowPanel();
  3534. initWidget(rootContainer);
  3535. openCloseButton = new Button();
  3536. openCloseButton.addClickHandler(openCloseButtonHandler);
  3537. rootContainer.add(openCloseButton);
  3538. content = new FlowPanel() {
  3539. @Override
  3540. public boolean remove(Widget w) {
  3541. // Check here to catch child.removeFromParent() calls
  3542. boolean removed = super.remove(w);
  3543. if (removed) {
  3544. updateVisibility();
  3545. }
  3546. return removed;
  3547. }
  3548. };
  3549. createOverlay();
  3550. menuBar = new MenuBar(true) {
  3551. @Override
  3552. public MenuItem insertItem(MenuItem item, int beforeIndex)
  3553. throws IndexOutOfBoundsException {
  3554. if (getParent() == null) {
  3555. content.insert(this, 0);
  3556. updateVisibility();
  3557. }
  3558. return super.insertItem(item, beforeIndex);
  3559. }
  3560. @Override
  3561. public void removeItem(MenuItem item) {
  3562. super.removeItem(item);
  3563. if (getItems().isEmpty()) {
  3564. menuBar.removeFromParent();
  3565. }
  3566. }
  3567. @Override
  3568. public void onBrowserEvent(Event event) {
  3569. // selecting a item with enter will lose the focus and
  3570. // selected item, which means that further keyboard
  3571. // selection won't work unless we do this:
  3572. if (event.getTypeInt() == Event.ONKEYDOWN
  3573. && event.getKeyCode() == KeyCodes.KEY_ENTER) {
  3574. final MenuItem item = getSelectedItem();
  3575. super.onBrowserEvent(event);
  3576. Scheduler.get().scheduleDeferred(() -> {
  3577. selectItem(item);
  3578. focus();
  3579. });
  3580. } else {
  3581. super.onBrowserEvent(event);
  3582. }
  3583. }
  3584. };
  3585. KeyDownHandler keyDownHandler = event -> {
  3586. if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
  3587. close();
  3588. }
  3589. };
  3590. openCloseButton.addDomHandler(keyDownHandler,
  3591. KeyDownEvent.getType());
  3592. menuBar.addDomHandler(keyDownHandler, KeyDownEvent.getType());
  3593. }
  3594. /**
  3595. * Creates and initializes the overlay.
  3596. */
  3597. private void createOverlay() {
  3598. overlay = GWT.create(Overlay.class);
  3599. overlay.setOwner(grid);
  3600. overlay.setAutoHideEnabled(true);
  3601. overlay.addStyleDependentName("popup");
  3602. overlay.add(content);
  3603. overlay.addAutoHidePartner(rootContainer.getElement());
  3604. overlay.addCloseHandler(new CloseHandler<PopupPanel>() {
  3605. @Override
  3606. public void onClose(CloseEvent<PopupPanel> event) {
  3607. removeStyleName("open");
  3608. addStyleName("closed");
  3609. }
  3610. });
  3611. overlay.setFitInWindow(true);
  3612. }
  3613. /**
  3614. * Opens the sidebar if not yet opened. Opening the sidebar has no
  3615. * effect if it is empty.
  3616. */
  3617. public void open() {
  3618. if (!isOpen() && isInDOM()) {
  3619. addStyleName("open");
  3620. removeStyleName("closed");
  3621. overlay.showRelativeTo(rootContainer);
  3622. }
  3623. }
  3624. /**
  3625. * Closes the sidebar if not yet closed.
  3626. */
  3627. public void close() {
  3628. overlay.hide();
  3629. }
  3630. /**
  3631. * Returns whether the sidebar is open or not.
  3632. *
  3633. * @return <code>true</code> if open, <code>false</code> if not
  3634. */
  3635. public boolean isOpen() {
  3636. return overlay != null && overlay.isShowing();
  3637. }
  3638. @Override
  3639. public void setStylePrimaryName(String styleName) {
  3640. super.setStylePrimaryName(styleName);
  3641. overlay.setStylePrimaryName(styleName);
  3642. content.setStylePrimaryName(styleName + "-content");
  3643. openCloseButton.setStylePrimaryName(styleName + "-button");
  3644. if (isOpen()) {
  3645. addStyleName("open");
  3646. removeStyleName("closed");
  3647. } else {
  3648. removeStyleName("open");
  3649. addStyleName("closed");
  3650. }
  3651. }
  3652. @Override
  3653. public void addStyleName(String style) {
  3654. super.addStyleName(style);
  3655. overlay.addStyleName(style);
  3656. }
  3657. @Override
  3658. public void removeStyleName(String style) {
  3659. super.removeStyleName(style);
  3660. overlay.removeStyleName(style);
  3661. }
  3662. private void setHeightToHeaderCellHeight() {
  3663. RowContainer header = grid.escalator.getHeader();
  3664. if (!WidgetUtil.isDisplayed(header.getElement())
  3665. || header.getRowCount() == 0
  3666. || !header.getRowElement(0).hasChildNodes()) {
  3667. getLogger().info(
  3668. "No header cell available when calculating sidebar button height");
  3669. // If the Grid is hidden with styles when this is called the
  3670. // border height will be off, but it's usually only a matter of
  3671. // a pixel or so. Removing a style name cannot trigger a full
  3672. // refresh of the layout, it's developer's responsibility to do
  3673. // that where needed.
  3674. double height = header.getDefaultRowHeight()
  3675. - WidgetUtil.measureVerticalBorder(getElement()) / 2;
  3676. openCloseButton.setHeight(height + "px");
  3677. return;
  3678. }
  3679. // Use actual height instead of expected height in case the height
  3680. // is modified by styles.
  3681. Element firstHeaderCell = header.getRowElement(0)
  3682. .getFirstChildElement();
  3683. double height = WidgetUtil
  3684. .getRequiredHeightBoundingClientRectDouble(firstHeaderCell)
  3685. - WidgetUtil.measureVerticalBorder(getElement()) / 2;
  3686. openCloseButton.setHeight(height + "px");
  3687. }
  3688. private void updateVisibility() {
  3689. final boolean hasWidgets = content.getWidgetCount() > 0;
  3690. final boolean isVisible = isInDOM();
  3691. if (isVisible && !hasWidgets) {
  3692. Grid.setParent(this, null);
  3693. getElement().removeFromParent();
  3694. } else if (!isVisible && hasWidgets) {
  3695. close();
  3696. grid.getElement().appendChild(getElement());
  3697. Grid.setParent(this, grid);
  3698. }
  3699. }
  3700. private boolean isInDOM() {
  3701. return getParent() != null;
  3702. }
  3703. @Override
  3704. protected void onAttach() {
  3705. super.onAttach();
  3706. // Make sure the button will get correct height whenever the Sidebar
  3707. // is added to the Grid.
  3708. setHeightToHeaderCellHeight();
  3709. }
  3710. @Override
  3711. public boolean isEnabled() {
  3712. return openCloseButton.isEnabled();
  3713. }
  3714. @Override
  3715. public void setEnabled(boolean enabled) {
  3716. if (!enabled && isOpen()) {
  3717. close();
  3718. }
  3719. openCloseButton.setEnabled(enabled);
  3720. }
  3721. }
  3722. /**
  3723. * UI and functionality related to hiding columns with toggles in the
  3724. * sidebar.
  3725. */
  3726. private final class ColumnHider {
  3727. /** Map from columns to their hiding toggles, component might change */
  3728. private Map<Column<?, T>, MenuItem> columnToHidingToggleMap = new HashMap<>();
  3729. /**
  3730. * When column is being hidden with a toggle, do not refresh toggles for
  3731. * no reason. Also helps for keeping the keyboard navigation working.
  3732. */
  3733. private boolean hidingColumn;
  3734. /**
  3735. * When several columns are set hidable, don't reset the Sidebar for
  3736. * every column separately.
  3737. */
  3738. private boolean toggleUpdateTriggered;
  3739. private void updateColumnHidable(final Column<?, T> column) {
  3740. if (column.isHidable()) {
  3741. MenuItem toggle = columnToHidingToggleMap.get(column);
  3742. if (toggle == null) {
  3743. toggle = createToggle(column);
  3744. }
  3745. toggle.setStyleName("hidden", column.isHidden());
  3746. } else if (columnToHidingToggleMap.containsKey(column)) {
  3747. sidebar.menuBar
  3748. .removeItem(columnToHidingToggleMap.remove(column));
  3749. }
  3750. updateTogglesOrder();
  3751. }
  3752. private MenuItem createToggle(final Column<?, T> column) {
  3753. MenuItem toggle = new MenuItem(createHTML(column), true, () -> {
  3754. hidingColumn = true;
  3755. column.setHidden(!column.isHidden(), true);
  3756. hidingColumn = false;
  3757. });
  3758. toggle.addStyleName("column-hiding-toggle");
  3759. columnToHidingToggleMap.put(column, toggle);
  3760. return toggle;
  3761. }
  3762. private String createHTML(Column<?, T> column) {
  3763. final StringBuilder buf = new StringBuilder();
  3764. buf.append("<span class=\"");
  3765. if (column.isHidden()) {
  3766. buf.append("v-off");
  3767. } else {
  3768. buf.append("v-on");
  3769. }
  3770. buf.append("\"><div>");
  3771. String caption = column.getHidingToggleCaption();
  3772. if (caption == null) {
  3773. caption = column.headerCaption;
  3774. }
  3775. buf.append(caption);
  3776. buf.append("</div></span>");
  3777. return buf.toString();
  3778. }
  3779. private void updateTogglesOrder() {
  3780. if (!hidingColumn && !toggleUpdateTriggered) {
  3781. // This method is called whenever a column is set hidable. If
  3782. // there are multiple hidable columns, it will get called
  3783. // separately for all of them. There is no need to update the
  3784. // order more than once and no other layouting is dependent on
  3785. // the Sidebar layouting getting finished first, so wait until
  3786. // all calls have arrived before proceeding further.
  3787. toggleUpdateTriggered = true;
  3788. Scheduler.get().scheduleFinally(() -> {
  3789. int lastIndex = 0;
  3790. for (Column<?, T> column : getColumns()) {
  3791. if (column.isHidable()) {
  3792. final MenuItem menuItem = columnToHidingToggleMap
  3793. .get(column);
  3794. sidebar.menuBar.removeItem(menuItem);
  3795. sidebar.menuBar.insertItem(menuItem, lastIndex++);
  3796. }
  3797. }
  3798. toggleUpdateTriggered = false;
  3799. });
  3800. }
  3801. }
  3802. private void updateHidingToggle(Column<?, T> column) {
  3803. if (column.isHidable()) {
  3804. MenuItem toggle = columnToHidingToggleMap.get(column);
  3805. toggle.setHTML(createHTML(column));
  3806. toggle.setStyleName("hidden", column.isHidden());
  3807. } // else we can just ignore
  3808. }
  3809. private void removeColumnHidingToggle(Column<?, T> column) {
  3810. sidebar.menuBar.removeItem(columnToHidingToggleMap.get(column));
  3811. }
  3812. }
  3813. /**
  3814. * Escalator used internally by grid to render the rows
  3815. */
  3816. private Escalator escalator = GWT.create(Escalator.class);
  3817. private final Header header = GWT.create(Header.class);
  3818. private final Footer footer = GWT.create(Footer.class);
  3819. private final Sidebar sidebar = new Sidebar(this);
  3820. /**
  3821. * List of columns in the grid. Order defines the visible order.
  3822. */
  3823. private List<Column<?, T>> columns = new ArrayList<>();
  3824. /**
  3825. * The datasource currently in use. <em>Note:</em> it is <code>null</code>
  3826. * on initialization, but not after that.
  3827. */
  3828. private DataSource<T> dataSource;
  3829. private Registration changeHandler;
  3830. private boolean recalculateColumnWidthsNeeded = false;
  3831. /**
  3832. * Currently available row range in DataSource.
  3833. */
  3834. private Range currentDataAvailable = Range.withLength(0, 0);
  3835. /**
  3836. * The number of frozen columns, 0 freezes the selection column if
  3837. * displayed, -1 also prevents selection col from freezing.
  3838. */
  3839. private int frozenColumnCount = 0;
  3840. /**
  3841. * Current sort order. The (private) sort() method reads this list to
  3842. * determine the order in which to present rows.
  3843. */
  3844. private List<SortOrder> sortOrder = new ArrayList<>();
  3845. private Renderer<Boolean> selectColumnRenderer = null;
  3846. private SelectionColumn selectionColumn;
  3847. private String rowStripeStyleName;
  3848. private String rowHasDataStyleName;
  3849. private String rowSelectedStyleName;
  3850. private String cellFocusStyleName;
  3851. private String rowFocusStyleName;
  3852. /**
  3853. * Current selection model.
  3854. */
  3855. private SelectionModel<T> selectionModel;
  3856. protected final CellFocusHandler cellFocusHandler;
  3857. private final UserSorter sorter = new UserSorter();
  3858. private final Editor<T> editor = GWT.create(Editor.class);
  3859. /**
  3860. * The cell a click event originated from
  3861. * <p>
  3862. * This is a workaround to make Chrome work like Firefox. In Chrome,
  3863. * normally if you start a drag on one cell and release on:
  3864. * <ul>
  3865. * <li>that same cell, the click event is that <code>&lt;td></code>.
  3866. * <li>a cell on that same row, the click event is the parent
  3867. * <code>&lt;tr></code>.
  3868. * <li>a cell on another row, the click event is the table section ancestor
  3869. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  3870. * </ul>
  3871. *
  3872. * @see #onBrowserEvent(Event)
  3873. */
  3874. private Cell cellOnPrevMouseDown;
  3875. /**
  3876. * A scheduled command to re-evaluate the widths of <em>all columns</em>
  3877. * that have calculated widths. Most probably called because
  3878. * minwidth/maxwidth/expandratio has changed.
  3879. */
  3880. private final AutoColumnWidthsRecalculator autoColumnWidthsRecalculator = new AutoColumnWidthsRecalculator();
  3881. private boolean enabled = true;
  3882. private DetailsGenerator detailsGenerator = DetailsGenerator.NULL;
  3883. private GridSpacerUpdater gridSpacerUpdater = new GridSpacerUpdater();
  3884. /** A set keeping track of the indices of all currently open details */
  3885. private Set<Integer> visibleDetails = new HashSet<>();
  3886. /** A set of indices of details to reopen after detach and on attach */
  3887. private final Set<Integer> reattachVisibleDetails = new HashSet<>();
  3888. private boolean columnReorderingAllowed;
  3889. private ColumnHider columnHider = new ColumnHider();
  3890. private DragAndDropHandler dndHandler = new DragAndDropHandler();
  3891. private AutoScroller autoScroller = new AutoScroller(this);
  3892. private ColumnResizeMode columnResizeMode = ColumnResizeMode.ANIMATED;
  3893. private final List<GridEventHandler<T>> browserEventHandlers = new ArrayList<>();
  3894. private CellStyleGenerator<T> cellStyleGenerator;
  3895. private RowStyleGenerator<T> rowStyleGenerator;
  3896. private RowReference<T> rowReference = new RowReference<>(this);
  3897. private CellReference<T> cellReference = new CellReference<>(rowReference);
  3898. private RendererCellReference rendererCellReference = new RendererCellReference(
  3899. (RowReference<Object>) rowReference);
  3900. private boolean refreshBodyRequested = false;
  3901. private double resizeHandleWidth = 0;
  3902. private DragAndDropHandler.DragAndDropCallback headerCellDndCallback = new DragAndDropCallback() {
  3903. private final AutoScrollerCallback autoScrollerCallback = new AutoScrollerCallback() {
  3904. @Override
  3905. public void onAutoScroll(int scrollDiff) {
  3906. autoScrollX = scrollDiff;
  3907. onDragUpdate(null);
  3908. }
  3909. @Override
  3910. public void onAutoScrollReachedMin() {
  3911. // make sure the drop marker is visible on the left
  3912. autoScrollX = 0;
  3913. updateDragDropMarker(clientX);
  3914. }
  3915. @Override
  3916. public void onAutoScrollReachedMax() {
  3917. // make sure the drop marker is visible on the right
  3918. autoScrollX = 0;
  3919. updateDragDropMarker(clientX);
  3920. }
  3921. };
  3922. /**
  3923. * Elements for displaying the dragged column(s) and drop marker
  3924. * properly
  3925. */
  3926. private Element table;
  3927. private Element tableHeader;
  3928. /** Marks the column drop location */
  3929. private Element dropMarker;
  3930. /** A copy of the dragged column(s), moves with cursor. */
  3931. private Element dragElement;
  3932. /** Tracks index of the column whose left side the drop would occur */
  3933. private int latestColumnDropIndex;
  3934. /**
  3935. * Map of possible drop positions for the column and the corresponding
  3936. * column index.
  3937. */
  3938. private final TreeMap<Double, Integer> possibleDropPositions = new TreeMap<>();
  3939. /**
  3940. * Makes sure that drag cancel doesn't cause anything unwanted like sort
  3941. */
  3942. private HandlerRegistration columnSortPreventRegistration;
  3943. private int clientX;
  3944. /** How much the grid is being auto scrolled while dragging. */
  3945. private int autoScrollX;
  3946. /** Captures the value of the focused column before reordering */
  3947. private int focusedColumnIndex;
  3948. /** Offset caused by the drag and drop marker width */
  3949. private double dropMarkerWidthOffset;
  3950. private void initHeaderDragElementDOM() {
  3951. if (table == null) {
  3952. tableHeader = DOM.createTHead();
  3953. dropMarker = DOM.createDiv();
  3954. tableHeader.appendChild(dropMarker);
  3955. table = DOM.createTable();
  3956. table.appendChild(tableHeader);
  3957. table.setClassName("header-drag-table");
  3958. }
  3959. // update the style names on each run in case primary name has been
  3960. // modified
  3961. tableHeader.setClassName(
  3962. escalator.getHeader().getElement().getClassName());
  3963. dropMarker.setClassName(getStylePrimaryName() + "-drop-marker");
  3964. int topOffset = 0;
  3965. for (int i = 0; i < eventCell.getRowIndex(); i++) {
  3966. topOffset += escalator.getHeader().getRowElement(i)
  3967. .getFirstChildElement().getOffsetHeight();
  3968. }
  3969. tableHeader.getStyle().setTop(topOffset, Unit.PX);
  3970. getElement().appendChild(table);
  3971. dropMarkerWidthOffset = WidgetUtil
  3972. .getRequiredWidthBoundingClientRectDouble(dropMarker) / 2;
  3973. }
  3974. @Override
  3975. public void onDragUpdate(Event e) {
  3976. if (e != null) {
  3977. clientX = WidgetUtil.getTouchOrMouseClientX(e);
  3978. autoScrollX = 0;
  3979. }
  3980. resolveDragElementHorizontalPosition(clientX);
  3981. updateDragDropMarker(clientX);
  3982. }
  3983. private void updateDragDropMarker(final int clientX) {
  3984. final double scrollLeft = getScrollLeft();
  3985. final double cursorXCoordinate = clientX
  3986. - escalator.getHeader().getElement().getAbsoluteLeft();
  3987. final Entry<Double, Integer> cellEdgeOnRight = possibleDropPositions
  3988. .ceilingEntry(cursorXCoordinate);
  3989. final Entry<Double, Integer> cellEdgeOnLeft = possibleDropPositions
  3990. .floorEntry(cursorXCoordinate);
  3991. final double diffToRightEdge = cellEdgeOnRight == null
  3992. ? Double.MAX_VALUE
  3993. : cellEdgeOnRight.getKey() - cursorXCoordinate;
  3994. final double diffToLeftEdge = cellEdgeOnLeft == null
  3995. ? Double.MAX_VALUE
  3996. : cursorXCoordinate - cellEdgeOnLeft.getKey();
  3997. double dropMarkerLeft = 0 - scrollLeft;
  3998. if (diffToRightEdge > diffToLeftEdge) {
  3999. latestColumnDropIndex = cellEdgeOnLeft.getValue();
  4000. dropMarkerLeft += cellEdgeOnLeft.getKey();
  4001. } else {
  4002. latestColumnDropIndex = cellEdgeOnRight.getValue();
  4003. dropMarkerLeft += cellEdgeOnRight.getKey();
  4004. }
  4005. dropMarkerLeft += autoScrollX;
  4006. final double frozenColumnsWidth = autoScroller
  4007. .getFrozenColumnsWidth();
  4008. final double rightBoundaryForDrag = getSidebarBoundaryComparedTo(
  4009. dropMarkerLeft);
  4010. final int visibleColumns = getVisibleColumns().size();
  4011. // First check if the drop marker should move left because of the
  4012. // sidebar opening button. this only the case if the grid is
  4013. // scrolled to the right
  4014. if (latestColumnDropIndex == visibleColumns
  4015. && rightBoundaryForDrag < dropMarkerLeft
  4016. && dropMarkerLeft <= escalator.getInnerWidth()) {
  4017. dropMarkerLeft = rightBoundaryForDrag - dropMarkerWidthOffset;
  4018. } else if (
  4019. // Check if the drop marker shouldn't be shown at all
  4020. dropMarkerLeft < frozenColumnsWidth || dropMarkerLeft > Math
  4021. .min(rightBoundaryForDrag, escalator.getInnerWidth())
  4022. || dropMarkerLeft < 0) {
  4023. dropMarkerLeft = -10000000;
  4024. }
  4025. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  4026. }
  4027. private void resolveDragElementHorizontalPosition(final int clientX) {
  4028. double left = clientX - table.getAbsoluteLeft();
  4029. // Do not show the drag element beyond a spanned header cell
  4030. // limitation
  4031. final Double leftBound = possibleDropPositions.firstKey();
  4032. final Double rightBound = possibleDropPositions.lastKey();
  4033. final double scrollLeft = getScrollLeft();
  4034. if (left + scrollLeft < leftBound) {
  4035. left = leftBound - scrollLeft + autoScrollX;
  4036. } else if (left + scrollLeft > rightBound) {
  4037. left = rightBound - scrollLeft + autoScrollX;
  4038. }
  4039. // Do not show the drag element beyond the grid
  4040. final double sidebarBoundary = getSidebarBoundaryComparedTo(left);
  4041. final double gridBoundary = escalator.getInnerWidth();
  4042. final double rightBoundary = Math.min(sidebarBoundary,
  4043. gridBoundary);
  4044. // Do not show on left of the frozen columns (even if scrolled)
  4045. final int frozenColumnsWidth = (int) autoScroller
  4046. .getFrozenColumnsWidth();
  4047. left = Math.max(frozenColumnsWidth, Math.min(left, rightBoundary));
  4048. left -= dragElement.getClientWidth() / 2;
  4049. dragElement.getStyle().setLeft(left, Unit.PX);
  4050. }
  4051. private boolean isSidebarOnDraggedRow() {
  4052. return eventCell.getRowIndex() == 0 && sidebar.isInDOM()
  4053. && !sidebar.isOpen();
  4054. }
  4055. /**
  4056. * Returns the sidebar left coordinate, in relation to the grid. Or
  4057. * Double.MAX_VALUE if it doesn't cause a boundary.
  4058. */
  4059. private double getSidebarBoundaryComparedTo(double left) {
  4060. if (isSidebarOnDraggedRow()) {
  4061. double absoluteLeft = left + getElement().getAbsoluteLeft();
  4062. double sidebarLeft = sidebar.getElement().getAbsoluteLeft();
  4063. double diff = absoluteLeft - sidebarLeft;
  4064. if (diff > 0) {
  4065. return left - diff;
  4066. }
  4067. }
  4068. return Double.MAX_VALUE;
  4069. }
  4070. @Override
  4071. public boolean onDragStart(Event e) {
  4072. calculatePossibleDropPositions();
  4073. if (possibleDropPositions.isEmpty()) {
  4074. return false;
  4075. }
  4076. initHeaderDragElementDOM();
  4077. // needs to clone focus and sorting indicators too (UX)
  4078. dragElement = DOM.clone(eventCell.getElement(), true);
  4079. dragElement.getStyle().clearWidth();
  4080. dropMarker.getStyle().setProperty("height",
  4081. dragElement.getStyle().getHeight());
  4082. tableHeader.appendChild(dragElement);
  4083. // mark the column being dragged for styling
  4084. eventCell.getElement().addClassName("dragged");
  4085. // mark the floating cell, for styling & testing
  4086. dragElement.addClassName("dragged-column-header");
  4087. // start the auto scroll handler
  4088. autoScroller.setScrollArea(60);
  4089. autoScroller.start(e, ScrollAxis.HORIZONTAL, autoScrollerCallback);
  4090. return true;
  4091. }
  4092. @Override
  4093. public void onDragEnd() {
  4094. table.removeFromParent();
  4095. dragElement.removeFromParent();
  4096. eventCell.getElement().removeClassName("dragged");
  4097. }
  4098. @Override
  4099. public void onDrop() {
  4100. final int draggedColumnIndex = eventCell.getColumnIndex();
  4101. final int colspan = header.getRow(eventCell.getRowIndex())
  4102. .getCell(eventCell.getColumn()).getColspan();
  4103. if (latestColumnDropIndex != draggedColumnIndex
  4104. && latestColumnDropIndex != draggedColumnIndex + colspan) {
  4105. List<Column<?, T>> columns = getColumns();
  4106. List<Column<?, T>> reordered = new ArrayList<>();
  4107. if (draggedColumnIndex < latestColumnDropIndex) {
  4108. reordered.addAll(columns.subList(0, draggedColumnIndex));
  4109. reordered.addAll(
  4110. columns.subList(draggedColumnIndex + colspan,
  4111. latestColumnDropIndex));
  4112. reordered.addAll(columns.subList(draggedColumnIndex,
  4113. draggedColumnIndex + colspan));
  4114. reordered.addAll(columns.subList(latestColumnDropIndex,
  4115. columns.size()));
  4116. } else {
  4117. reordered.addAll(columns.subList(0, latestColumnDropIndex));
  4118. reordered.addAll(columns.subList(draggedColumnIndex,
  4119. draggedColumnIndex + colspan));
  4120. reordered.addAll(columns.subList(latestColumnDropIndex,
  4121. draggedColumnIndex));
  4122. reordered.addAll(columns.subList(
  4123. draggedColumnIndex + colspan, columns.size()));
  4124. }
  4125. // since setColumnOrder will add it anyway!
  4126. reordered.remove(selectionColumn);
  4127. // capture focused cell column before reorder
  4128. Cell focusedCell = cellFocusHandler.getFocusedCell();
  4129. if (focusedCell != null) {
  4130. // take hidden columns into account
  4131. focusedColumnIndex = getColumns()
  4132. .indexOf(getVisibleColumn(focusedCell.getColumn()));
  4133. }
  4134. Column<?, T>[] array = reordered
  4135. .toArray(new Column[reordered.size()]);
  4136. setColumnOrder(true, array);
  4137. transferCellFocusOnDrop();
  4138. } // else
  4139. // no
  4140. // reordering
  4141. }
  4142. private void transferCellFocusOnDrop() {
  4143. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  4144. if (focusedCell != null && focusedCell.getElement() != null) {
  4145. final int focusedColumnIndexDOM = focusedCell.getColumn();
  4146. final int focusedRowIndex = focusedCell.getRow();
  4147. final int draggedColumnIndex = eventCell.getColumnIndex();
  4148. // transfer focus if it was effected by the new column order
  4149. final RowContainer rowContainer = escalator
  4150. .findRowContainer(focusedCell.getElement());
  4151. if (focusedColumnIndex == draggedColumnIndex) {
  4152. // move with the dragged column
  4153. int adjustedDropIndex = latestColumnDropIndex > draggedColumnIndex
  4154. ? latestColumnDropIndex - 1
  4155. : latestColumnDropIndex;
  4156. // remove hidden columns from indexing
  4157. adjustedDropIndex = getVisibleColumns()
  4158. .indexOf(getColumn(adjustedDropIndex));
  4159. cellFocusHandler.setCellFocus(focusedRowIndex,
  4160. adjustedDropIndex, rowContainer);
  4161. } else if (latestColumnDropIndex <= focusedColumnIndex
  4162. && draggedColumnIndex > focusedColumnIndex) {
  4163. cellFocusHandler.setCellFocus(focusedRowIndex,
  4164. focusedColumnIndexDOM + 1, rowContainer);
  4165. } else if (latestColumnDropIndex > focusedColumnIndex
  4166. && draggedColumnIndex < focusedColumnIndex) {
  4167. cellFocusHandler.setCellFocus(focusedRowIndex,
  4168. focusedColumnIndexDOM - 1, rowContainer);
  4169. }
  4170. }
  4171. }
  4172. @Override
  4173. public void onDragCancel() {
  4174. // cancel next click so that we may prevent column sorting if
  4175. // mouse was released on top of the dragged cell
  4176. if (columnSortPreventRegistration == null) {
  4177. columnSortPreventRegistration = Event
  4178. .addNativePreviewHandler(event -> {
  4179. if (event.getTypeInt() == Event.ONCLICK) {
  4180. event.cancel();
  4181. event.getNativeEvent().preventDefault();
  4182. columnSortPreventRegistration.removeHandler();
  4183. columnSortPreventRegistration = null;
  4184. }
  4185. });
  4186. }
  4187. autoScroller.stop();
  4188. }
  4189. /**
  4190. * Returns the amount of frozen columns. The selection column is always
  4191. * considered frozen, since it can't be moved.
  4192. */
  4193. private int getSelectionAndFrozenColumnCount() {
  4194. // no matter if selection column is frozen or not, it is considered
  4195. // frozen for column dnd reorder
  4196. if (getSelectionModel() instanceof SelectionModelWithSelectionColumn) {
  4197. return Math.max(0, getFrozenColumnCount()) + 1;
  4198. } else {
  4199. return Math.max(0, getFrozenColumnCount());
  4200. }
  4201. }
  4202. @SuppressWarnings("boxing")
  4203. private void calculatePossibleDropPositions() {
  4204. possibleDropPositions.clear();
  4205. final int draggedColumnIndex = eventCell.getColumnIndex();
  4206. final StaticRow<?> draggedCellRow = header
  4207. .getRow(eventCell.getRowIndex());
  4208. final int draggedColumnRightIndex = draggedColumnIndex
  4209. + draggedCellRow.getCell(eventCell.getColumn())
  4210. .getColspan();
  4211. final int frozenColumns = getSelectionAndFrozenColumnCount();
  4212. final Range draggedCellRange = Range.between(draggedColumnIndex,
  4213. draggedColumnRightIndex);
  4214. /*
  4215. * If the dragged cell intersects with a spanned cell in any other
  4216. * header or footer row, then the drag is limited inside that
  4217. * spanned cell. The same rules apply: the cell can't be dropped
  4218. * inside another spanned cell. The left and right bounds keep track
  4219. * of the edges of the most limiting spanned cell.
  4220. */
  4221. int leftBound = -1;
  4222. int rightBound = getColumnCount() + 1;
  4223. final HashSet<Integer> unavailableColumnDropIndices = new HashSet<>();
  4224. final List<StaticRow<?>> rows = new ArrayList<>();
  4225. rows.addAll(header.getRows());
  4226. rows.addAll(footer.getRows());
  4227. for (StaticRow<?> row : rows) {
  4228. if (!row.hasSpannedCells()) {
  4229. continue;
  4230. }
  4231. final boolean isDraggedCellRow = row.equals(draggedCellRow);
  4232. for (int cellColumnIndex = frozenColumns; cellColumnIndex < getColumnCount(); cellColumnIndex++) {
  4233. StaticCell cell = row.getCell(getColumn(cellColumnIndex));
  4234. int colspan = cell.getColspan();
  4235. if (colspan <= 1) {
  4236. continue;
  4237. }
  4238. final int cellColumnRightIndex = cellColumnIndex + row
  4239. .getSizeOfCellGroup(getColumn(cellColumnIndex));
  4240. final Range cellRange = Range.between(cellColumnIndex,
  4241. cellColumnRightIndex);
  4242. final boolean intersects = draggedCellRange
  4243. .intersects(cellRange);
  4244. if (intersects && !isDraggedCellRow) {
  4245. // if the currently iterated cell is inside or same as
  4246. // the dragged cell, then it doesn't restrict the drag
  4247. if (cellRange.isSubsetOf(draggedCellRange)) {
  4248. cellColumnIndex = cellColumnRightIndex - 1;
  4249. continue;
  4250. }
  4251. /*
  4252. * if the dragged cell is a spanned cell and it crosses
  4253. * with the currently iterated cell without sharing
  4254. * either start or end then not possible to drag the
  4255. * cell.
  4256. */
  4257. if (!draggedCellRange.isSubsetOf(cellRange)) {
  4258. return;
  4259. }
  4260. // the spanned cell overlaps the dragged cell (but is
  4261. // not the dragged cell)
  4262. if (cellColumnIndex <= draggedColumnIndex
  4263. && cellColumnIndex > leftBound) {
  4264. leftBound = cellColumnIndex;
  4265. }
  4266. if (cellColumnRightIndex < rightBound) {
  4267. rightBound = cellColumnRightIndex;
  4268. }
  4269. cellColumnIndex = cellColumnRightIndex - 1;
  4270. } else {
  4271. // can't drop inside a spanned cell, or this is the
  4272. // dragged cell
  4273. while (colspan > 1) {
  4274. cellColumnIndex++;
  4275. colspan--;
  4276. unavailableColumnDropIndices.add(cellColumnIndex);
  4277. }
  4278. }
  4279. }
  4280. }
  4281. if (leftBound == rightBound - 1) {
  4282. return;
  4283. }
  4284. double position = autoScroller.getFrozenColumnsWidth();
  4285. // iterate column indices and add possible drop positions
  4286. for (int i = frozenColumns; i < getColumnCount(); i++) {
  4287. Column<?, T> column = getColumn(i);
  4288. if (!unavailableColumnDropIndices.contains(i)
  4289. && !column.isHidden()) {
  4290. if (leftBound != -1) {
  4291. if (i >= leftBound && i <= rightBound) {
  4292. possibleDropPositions.put(position, i);
  4293. }
  4294. } else {
  4295. possibleDropPositions.put(position, i);
  4296. }
  4297. }
  4298. position += column.getWidthActual();
  4299. }
  4300. if (leftBound == -1) {
  4301. // add the right side of the last column as columns.size()
  4302. possibleDropPositions.put(position, getColumnCount());
  4303. }
  4304. }
  4305. };
  4306. /**
  4307. * Base class for grid columns internally used by the Grid. The user should
  4308. * use {@link Column} when creating new columns.
  4309. *
  4310. * @param <C>
  4311. * the column type
  4312. *
  4313. * @param <T>
  4314. * the row type
  4315. */
  4316. public abstract static class Column<C, T> {
  4317. /**
  4318. * Default renderer for GridColumns. Renders everything into text
  4319. * through {@link Object#toString()}.
  4320. */
  4321. private final class DefaultTextRenderer implements Renderer<Object> {
  4322. boolean warned = false;
  4323. private static final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  4324. + "A more suitable renderer should be set using the setRenderer() method.";
  4325. @Override
  4326. public void render(RendererCellReference cell, Object data) {
  4327. if (!warned && !(data instanceof String)) {
  4328. getLogger().warning(
  4329. Column.this + ": " + DEFAULT_RENDERER_WARNING);
  4330. warned = true;
  4331. }
  4332. final String text;
  4333. if (data == null) {
  4334. text = "";
  4335. } else {
  4336. text = data.toString();
  4337. }
  4338. cell.getElement().setInnerText(text);
  4339. }
  4340. }
  4341. /**
  4342. * the column is associated with
  4343. */
  4344. private Grid<T> grid;
  4345. /**
  4346. * Width of column in pixels as {@link #setWidth(double)} has been
  4347. * called
  4348. */
  4349. private double widthUser = GridConstants.DEFAULT_COLUMN_WIDTH_PX;
  4350. /**
  4351. * Renderer for rendering a value into the cell
  4352. */
  4353. private Renderer<? super C> bodyRenderer;
  4354. private boolean sortable = false;
  4355. private boolean editable = true;
  4356. private boolean resizable = true;
  4357. private boolean hidden = false;
  4358. private boolean hidable = false;
  4359. private String headerCaption = "";
  4360. private String assistiveCaption = null;
  4361. private String hidingToggleCaption = null;
  4362. private boolean handleWidgetEvents = false;
  4363. private double minimumWidthPx = GridConstants.DEFAULT_MIN_WIDTH;
  4364. private double maximumWidthPx = GridConstants.DEFAULT_MAX_WIDTH;
  4365. private int expandRatio = GridConstants.DEFAULT_EXPAND_RATIO;
  4366. private boolean minimumWidthFromContent = true;
  4367. /**
  4368. * Constructs a new column with a simple TextRenderer.
  4369. */
  4370. public Column() {
  4371. setRenderer(new DefaultTextRenderer());
  4372. }
  4373. /**
  4374. * Constructs a new column with a simple TextRenderer.
  4375. *
  4376. * @param caption
  4377. * The header caption for this column
  4378. *
  4379. * @throws IllegalArgumentException
  4380. * if given header caption is null
  4381. */
  4382. public Column(String caption) throws IllegalArgumentException {
  4383. this();
  4384. setHeaderCaption(caption);
  4385. }
  4386. /**
  4387. * Constructs a new column with a custom renderer.
  4388. *
  4389. * @param renderer
  4390. * The renderer to use for rendering the cells
  4391. *
  4392. * @throws IllegalArgumentException
  4393. * if given Renderer is null
  4394. */
  4395. public Column(Renderer<? super C> renderer)
  4396. throws IllegalArgumentException {
  4397. setRenderer(renderer);
  4398. }
  4399. /**
  4400. * Constructs a new column with a custom renderer.
  4401. *
  4402. * @param renderer
  4403. * The renderer to use for rendering the cells
  4404. * @param caption
  4405. * The header caption for this column
  4406. *
  4407. * @throws IllegalArgumentException
  4408. * if given Renderer or header caption is null
  4409. */
  4410. public Column(String caption, Renderer<? super C> renderer)
  4411. throws IllegalArgumentException {
  4412. this(renderer);
  4413. setHeaderCaption(caption);
  4414. }
  4415. /**
  4416. * Internally used by the grid to set itself
  4417. *
  4418. * @param grid
  4419. */
  4420. private void setGrid(Grid<T> grid) {
  4421. if (this.grid != null && grid != null) {
  4422. // Trying to replace grid
  4423. throw new IllegalStateException("Column already is attached "
  4424. + "to a grid. Remove the column first from the grid "
  4425. + "and then add it. (in: " + toString() + ")");
  4426. }
  4427. if (this.grid != null) {
  4428. this.grid.recalculateColumnWidths();
  4429. }
  4430. this.grid = grid;
  4431. if (this.grid != null) {
  4432. this.grid.recalculateColumnWidths();
  4433. }
  4434. }
  4435. /**
  4436. * Sets a header caption for this column.
  4437. *
  4438. * @param caption
  4439. * The header caption for this column
  4440. * @return the column itself
  4441. *
  4442. */
  4443. public Column<C, T> setHeaderCaption(String caption) {
  4444. if (caption == null) {
  4445. caption = "";
  4446. }
  4447. if (!this.headerCaption.equals(caption)) {
  4448. this.headerCaption = caption;
  4449. if (grid != null) {
  4450. updateHeader();
  4451. }
  4452. }
  4453. return this;
  4454. }
  4455. /**
  4456. * Returns the current header caption for this column.
  4457. *
  4458. * @since 7.6
  4459. * @return the header caption string
  4460. */
  4461. public String getHeaderCaption() {
  4462. return headerCaption;
  4463. }
  4464. /**
  4465. * Sets the header aria-label for this column.
  4466. *
  4467. * @param caption
  4468. * The header aria-label for this column
  4469. * @return the column itself
  4470. *
  4471. * @since 8.2
  4472. */
  4473. public Column<C, T> setAssistiveCaption(String caption) {
  4474. if (!Objects.equals(this.assistiveCaption, caption)) {
  4475. this.assistiveCaption = caption;
  4476. if (grid != null) {
  4477. grid.getHeader().requestSectionRefresh();
  4478. }
  4479. }
  4480. return this;
  4481. }
  4482. /**
  4483. * Returns the current header aria-label for this column.
  4484. *
  4485. * @return the header aria-label string
  4486. *
  4487. * @since 8.2
  4488. */
  4489. public String getAssistiveCaption() {
  4490. return assistiveCaption;
  4491. }
  4492. private void updateHeader() {
  4493. HeaderRow row = grid.getHeader().getDefaultRow();
  4494. if (row != null) {
  4495. setDefaultHeaderContent(row.getCell(this));
  4496. if (isHidable()) {
  4497. grid.columnHider.updateHidingToggle(this);
  4498. }
  4499. }
  4500. }
  4501. /**
  4502. * Returns the data that should be rendered into the cell. By default
  4503. * returning Strings and Widgets are supported. If the return type is a
  4504. * String then it will be treated as preformatted text.
  4505. * <p>
  4506. * To support other types you will need to pass a custom renderer to the
  4507. * column via the column constructor.
  4508. *
  4509. * @param row
  4510. * The row object that provides the cell content.
  4511. *
  4512. * @return The cell content
  4513. */
  4514. public abstract C getValue(T row);
  4515. /**
  4516. * The renderer to render the cell with. By default renders the data as
  4517. * a String or adds the widget into the cell if the column type is of
  4518. * widget type.
  4519. *
  4520. * @return The renderer to render the cell content with
  4521. */
  4522. public Renderer<? super C> getRenderer() {
  4523. return bodyRenderer;
  4524. }
  4525. /**
  4526. * Sets a custom {@link Renderer} for this column.
  4527. *
  4528. * @param renderer
  4529. * The renderer to use for rendering the cells
  4530. * @return the column itself
  4531. *
  4532. * @throws IllegalArgumentException
  4533. * if given Renderer is null
  4534. */
  4535. public Column<C, T> setRenderer(Renderer<? super C> renderer)
  4536. throws IllegalArgumentException {
  4537. if (renderer == null) {
  4538. throw new IllegalArgumentException("Renderer cannot be null.");
  4539. }
  4540. if (renderer != bodyRenderer) {
  4541. // Variables used to restore removed column.
  4542. boolean columnRemoved = false;
  4543. double widthInConfiguration = 0.0d;
  4544. ColumnConfiguration conf = null;
  4545. int index = 0;
  4546. if (!isHidden() && grid != null
  4547. && (bodyRenderer instanceof WidgetRenderer
  4548. || renderer instanceof WidgetRenderer)) {
  4549. // Column needs to be recreated.
  4550. index = grid.getVisibleColumns().indexOf(this);
  4551. conf = grid.escalator.getColumnConfiguration();
  4552. widthInConfiguration = conf.getColumnWidth(index);
  4553. conf.removeColumns(index, 1);
  4554. columnRemoved = true;
  4555. }
  4556. // Complex renderers need to be destroyed.
  4557. if (bodyRenderer instanceof ComplexRenderer) {
  4558. ((ComplexRenderer) bodyRenderer).destroy();
  4559. }
  4560. bodyRenderer = renderer;
  4561. if (columnRemoved) {
  4562. // Restore the column.
  4563. conf.insertColumns(index, 1);
  4564. conf.setColumnWidth(index, widthInConfiguration);
  4565. }
  4566. if (!isHidden() && grid != null) {
  4567. grid.requestRefreshBody();
  4568. }
  4569. }
  4570. return this;
  4571. }
  4572. /**
  4573. * Sets the pixel width of the column. Use a negative value for the grid
  4574. * to autosize column based on content and available space.
  4575. * <p>
  4576. * This action is done "finally", once the current execution loop
  4577. * returns. This is done to reduce overhead of unintentionally always
  4578. * recalculate all columns, when modifying several columns at once.
  4579. * <p>
  4580. * If the column is currently {@link #isHidden() hidden}, then this set
  4581. * width has effect only once the column has been made visible again.
  4582. *
  4583. * @param pixels
  4584. * the width in pixels or negative for auto sizing
  4585. * @return this column
  4586. */
  4587. public Column<C, T> setWidth(double pixels) {
  4588. if (!WidgetUtil.pixelValuesEqual(widthUser, pixels)) {
  4589. widthUser = pixels;
  4590. if (!isHidden()) {
  4591. scheduleColumnWidthRecalculator();
  4592. }
  4593. }
  4594. return this;
  4595. }
  4596. void doSetWidth(double pixels) {
  4597. assert !isHidden() : "applying width for a hidden column";
  4598. if (grid != null) {
  4599. int index = grid.getVisibleColumns().indexOf(this);
  4600. ColumnConfiguration conf = grid.escalator
  4601. .getColumnConfiguration();
  4602. conf.setColumnWidth(index, pixels);
  4603. }
  4604. }
  4605. /**
  4606. * Returns the pixel width of the column as given by the user.
  4607. * <p>
  4608. * <em>Note:</em> If a negative value was given to
  4609. * {@link #setWidth(double)}, that same negative value is returned here.
  4610. * <p>
  4611. * <em>Note:</em> Returns the value, even if the column is currently
  4612. * {@link #isHidden() hidden}.
  4613. *
  4614. * @return pixel width of the column, or a negative number if the column
  4615. * width has been automatically calculated.
  4616. * @see #setWidth(double)
  4617. * @see #getWidthActual()
  4618. */
  4619. public double getWidth() {
  4620. return widthUser;
  4621. }
  4622. /**
  4623. * Returns the effective pixel width of the column.
  4624. * <p>
  4625. * This differs from {@link #getWidth()} only when the column has been
  4626. * automatically resized, or when the column is currently
  4627. * {@link #isHidden() hidden}, when the value is 0.
  4628. *
  4629. * @return pixel width of the column.
  4630. */
  4631. public double getWidthActual() {
  4632. if (isHidden()) {
  4633. return 0;
  4634. }
  4635. return grid.escalator.getColumnConfiguration().getColumnWidthActual(
  4636. grid.getVisibleColumns().indexOf(this));
  4637. }
  4638. void reapplyWidth() {
  4639. scheduleColumnWidthRecalculator();
  4640. }
  4641. /**
  4642. * Sets whether the column should be sortable by the user. The grid can
  4643. * be sorted by a sortable column by clicking or tapping the column's
  4644. * default header. Programmatic sorting using the Grid#sort methods is
  4645. * not affected by this setting.
  4646. *
  4647. * @param sortable
  4648. * {@code true} if the user should be able to sort the
  4649. * column, {@code false} otherwise
  4650. * @return the column itself
  4651. */
  4652. public Column<C, T> setSortable(boolean sortable) {
  4653. if (this.sortable != sortable) {
  4654. this.sortable = sortable;
  4655. if (grid != null) {
  4656. grid.getHeader().requestSectionRefresh();
  4657. }
  4658. }
  4659. return this;
  4660. }
  4661. /**
  4662. * Returns whether the user can sort the grid by this column.
  4663. * <p>
  4664. * <em>Note:</em> it is possible to sort by this column programmatically
  4665. * using the Grid#sort methods regardless of the returned value.
  4666. *
  4667. * @return {@code true} if the column is sortable by the user,
  4668. * {@code false} otherwise
  4669. */
  4670. public boolean isSortable() {
  4671. return sortable;
  4672. }
  4673. /**
  4674. * Sets whether this column can be resized by the user.
  4675. *
  4676. * @since 7.6
  4677. *
  4678. * @param resizable
  4679. * {@code true} if this column should be resizable,
  4680. * {@code false} otherwise
  4681. * @return this column
  4682. */
  4683. public Column<C, T> setResizable(boolean resizable) {
  4684. if (this.resizable != resizable) {
  4685. this.resizable = resizable;
  4686. if (grid != null) {
  4687. grid.getHeader().requestSectionRefresh();
  4688. }
  4689. }
  4690. return this;
  4691. }
  4692. /**
  4693. * Returns whether this column can be resized by the user. Default is
  4694. * {@code true}.
  4695. * <p>
  4696. * <em>Note:</em> the column can be programmatically resized using
  4697. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  4698. * of the returned value.
  4699. *
  4700. * @since 7.6
  4701. *
  4702. * @return {@code true} if this column is resizable, {@code false}
  4703. * otherwise
  4704. */
  4705. public boolean isResizable() {
  4706. return grid.isEnabled() && resizable;
  4707. }
  4708. /**
  4709. * Hides or shows the column. By default columns are visible before
  4710. * explicitly hiding them.
  4711. *
  4712. * @since 7.5.0
  4713. * @param hidden
  4714. * <code>true</code> to hide the column, <code>false</code>
  4715. * to show
  4716. * @return this column
  4717. */
  4718. public Column<C, T> setHidden(boolean hidden) {
  4719. setHidden(hidden, false);
  4720. return this;
  4721. }
  4722. private void setHidden(boolean hidden, boolean userOriginated) {
  4723. if (this.hidden != hidden) {
  4724. if (grid == null) {
  4725. // Not yet attached so just update the flag so that a column
  4726. // can initially be hidden
  4727. this.hidden = hidden;
  4728. return;
  4729. }
  4730. if (hidden) {
  4731. grid.escalator.getColumnConfiguration().removeColumns(
  4732. grid.getVisibleColumns().indexOf(this), 1);
  4733. this.hidden = hidden;
  4734. } else {
  4735. this.hidden = hidden;
  4736. int columnIndex = grid.getVisibleColumns().indexOf(this);
  4737. grid.escalator.getColumnConfiguration()
  4738. .insertColumns(columnIndex, 1);
  4739. // make sure column is set to frozen if it needs to be,
  4740. // escalator doesn't handle situation where the added column
  4741. // would be the last frozen column
  4742. int gridFrozenColumns = grid.getFrozenColumnCount();
  4743. // Correct column index for multiselect mode
  4744. if (grid.getSelectionColumn().isPresent()) {
  4745. gridFrozenColumns++;
  4746. }
  4747. int escalatorFrozenColumns = grid.escalator
  4748. .getColumnConfiguration().getFrozenColumnCount();
  4749. if (gridFrozenColumns > escalatorFrozenColumns
  4750. && escalatorFrozenColumns == columnIndex
  4751. && grid.getColumns()
  4752. .indexOf(this) < gridFrozenColumns) {
  4753. grid.escalator.getColumnConfiguration()
  4754. .setFrozenColumnCount(++escalatorFrozenColumns);
  4755. }
  4756. }
  4757. grid.columnHider.updateHidingToggle(this);
  4758. grid.header.updateColSpans();
  4759. grid.footer.updateColSpans();
  4760. scheduleColumnWidthRecalculator();
  4761. this.grid.fireEvent(new ColumnVisibilityChangeEvent<>(this,
  4762. hidden, userOriginated));
  4763. }
  4764. }
  4765. /**
  4766. * Returns whether this column is hidden. Default is {@code false}.
  4767. *
  4768. * @since 7.5.0
  4769. * @return {@code true} if the column is currently hidden, {@code false}
  4770. * otherwise
  4771. */
  4772. public boolean isHidden() {
  4773. return hidden;
  4774. }
  4775. /**
  4776. * Set whether it is possible for the user to hide this column or not.
  4777. * Default is {@code false}.
  4778. * <p>
  4779. * <em>Note:</em> it is still possible to hide the column
  4780. * programmatically using {@link #setHidden(boolean)}.
  4781. *
  4782. * @since 7.5.0
  4783. * @param hidable
  4784. * {@code true} the user can hide this column, {@code false}
  4785. * otherwise
  4786. * @return this column
  4787. */
  4788. public Column<C, T> setHidable(boolean hidable) {
  4789. if (this.hidable != hidable) {
  4790. this.hidable = hidable;
  4791. grid.columnHider.updateColumnHidable(this);
  4792. }
  4793. return this;
  4794. }
  4795. /**
  4796. * Is it possible for the the user to hide this column. Default is
  4797. * {@code false}.
  4798. * <p>
  4799. * <em>Note:</em> the column can be programmatically hidden using
  4800. * {@link #setHidden(boolean)} regardless of the returned value.
  4801. *
  4802. * @since 7.5.0
  4803. * @return <code>true</code> if the user can hide the column,
  4804. * <code>false</code> if not
  4805. */
  4806. public boolean isHidable() {
  4807. return hidable;
  4808. }
  4809. /**
  4810. * Sets the hiding toggle's caption for this column. Shown in the toggle
  4811. * for this column in the grid's sidebar when the column is
  4812. * {@link #isHidable() hidable}.
  4813. * <p>
  4814. * The default value is <code>null</code>. In this case the header
  4815. * caption is used, see {@link #setHeaderCaption(String)}.
  4816. *
  4817. * @since 7.5.0
  4818. * @param hidingToggleCaption
  4819. * the caption for the hiding toggle for this column
  4820. * @return this column
  4821. */
  4822. public Column<C, T> setHidingToggleCaption(String hidingToggleCaption) {
  4823. this.hidingToggleCaption = hidingToggleCaption;
  4824. if (isHidable()) {
  4825. grid.columnHider.updateHidingToggle(this);
  4826. }
  4827. return this;
  4828. }
  4829. /**
  4830. * Gets the hiding toggle caption for this column.
  4831. *
  4832. * @since 7.5.0
  4833. * @see #setHidingToggleCaption(String)
  4834. * @return the hiding toggle's caption for this column
  4835. */
  4836. public String getHidingToggleCaption() {
  4837. return hidingToggleCaption;
  4838. }
  4839. @Override
  4840. public String toString() {
  4841. String details = "";
  4842. if (headerCaption != null && !headerCaption.isEmpty()) {
  4843. details += "header:\"" + headerCaption + "\" ";
  4844. } else {
  4845. details += "header:empty ";
  4846. }
  4847. if (grid != null) {
  4848. int index = grid.getColumns().indexOf(this);
  4849. if (index != -1) {
  4850. details += "attached:#" + index + " ";
  4851. } else {
  4852. details += "attached:unindexed ";
  4853. }
  4854. } else {
  4855. details += "detached ";
  4856. }
  4857. details += "sortable:" + sortable + " ";
  4858. return getClass().getSimpleName() + "[" + details.trim() + "]";
  4859. }
  4860. /**
  4861. * Sets the minimum width for this column.
  4862. * <p>
  4863. * This defines the minimum guaranteed pixel width of the column
  4864. * <em>when it is set to expand</em>.
  4865. * <p>
  4866. * This action is done "finally", once the current execution loop
  4867. * returns. This is done to reduce overhead of unintentionally always
  4868. * recalculate all columns, when modifying several columns at once.
  4869. *
  4870. * @param pixels
  4871. * the minimum width
  4872. * @return this column
  4873. */
  4874. public Column<C, T> setMinimumWidth(double pixels) {
  4875. final double maxwidth = getMaximumWidth();
  4876. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  4877. throw new IllegalArgumentException("New minimum width ("
  4878. + pixels + ") was greater than maximum width ("
  4879. + maxwidth + ")");
  4880. }
  4881. if (minimumWidthPx != pixels) {
  4882. minimumWidthPx = pixels;
  4883. scheduleColumnWidthRecalculator();
  4884. }
  4885. return this;
  4886. }
  4887. /**
  4888. * Sets whether the width of the contents in the column should be
  4889. * considered minimum width for this column.
  4890. * <p>
  4891. * If this is set to <code>true</code> (default for backwards
  4892. * compatibility), then a column will not shrink to smaller than the
  4893. * width required to show the contents available when calculating the
  4894. * widths (first N rows).
  4895. * <p>
  4896. * If this is set to <code>false</code>, then a column will shrink if
  4897. * necessary to the minimum width defined by
  4898. * {@link #setMinimumWidth(double)} <em>when it is set to expand</em>.
  4899. *
  4900. * @param minimumWidthFromContent
  4901. * <code>true</code> to reserve space for all contents,
  4902. * <code>false</code> to allow the column to shrink smaller
  4903. * than the contents
  4904. * @since 8.1
  4905. */
  4906. public void setMinimumWidthFromContent(
  4907. boolean minimumWidthFromContent) {
  4908. this.minimumWidthFromContent = minimumWidthFromContent;
  4909. }
  4910. /**
  4911. * Gets whether the width of the contents in the column should be
  4912. * considered minimum width for this column.
  4913. *
  4914. * @return <code>true</code> to reserve space for all contents,
  4915. * <code>false</code> to allow the column to shrink smaller than
  4916. * the contents
  4917. * @since 8.1
  4918. */
  4919. public boolean isMinimumWidthFromContent() {
  4920. return minimumWidthFromContent;
  4921. }
  4922. /**
  4923. * Sets the maximum width for this column.
  4924. * <p>
  4925. * This defines the maximum allowed pixel width of the column <em>when
  4926. * it is set to expand</em>.
  4927. * <p>
  4928. * This action is done "finally", once the current execution loop
  4929. * returns. This is done to reduce overhead of unintentionally always
  4930. * recalculate all columns, when modifying several columns at once.
  4931. *
  4932. * @param pixels
  4933. * the maximum width
  4934. * @return this column
  4935. */
  4936. public Column<C, T> setMaximumWidth(double pixels) {
  4937. final double minwidth = getMinimumWidth();
  4938. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  4939. throw new IllegalArgumentException("New maximum width ("
  4940. + pixels + ") was less than minimum width (" + minwidth
  4941. + ")");
  4942. }
  4943. if (maximumWidthPx != pixels) {
  4944. maximumWidthPx = pixels;
  4945. scheduleColumnWidthRecalculator();
  4946. }
  4947. return this;
  4948. }
  4949. /**
  4950. * Sets the ratio with which the column expands.
  4951. * <p>
  4952. * By default, all columns expand equally (treated as if all of them had
  4953. * an expand ratio of 1). Once at least one column gets a defined expand
  4954. * ratio, the implicit expand ratio is removed, and only the defined
  4955. * expand ratios are taken into account.
  4956. * <p>
  4957. * If a column has a defined width ({@link #setWidth(double)}), it
  4958. * overrides this method's effects.
  4959. * <p>
  4960. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  4961. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  4962. * as wide as its contents requires</strong>. The column with a ratio of
  4963. * 1 is as wide as it needs, <strong>plus a third of any excess
  4964. * space</strong>, bceause we have 3 parts total, and this column
  4965. * reservs only one of those. The column with a ratio of 2, is as wide
  4966. * as it needs to be, <strong>plus two thirds</strong> of the excess
  4967. * width.
  4968. * <p>
  4969. * This action is done "finally", once the current execution loop
  4970. * returns. This is done to reduce overhead of unintentionally always
  4971. * recalculate all columns, when modifying several columns at once.
  4972. *
  4973. * @param ratio
  4974. * the expand ratio of this column. {@code 0} to not have it
  4975. * expand at all. A negative number to clear the expand
  4976. * value.
  4977. * @return this column
  4978. */
  4979. public Column<C, T> setExpandRatio(int ratio) {
  4980. if (expandRatio != ratio) {
  4981. expandRatio = ratio;
  4982. scheduleColumnWidthRecalculator();
  4983. }
  4984. return this;
  4985. }
  4986. /**
  4987. * Clears the column's expand ratio.
  4988. * <p>
  4989. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  4990. *
  4991. * @return this column
  4992. */
  4993. public Column<C, T> clearExpandRatio() {
  4994. return setExpandRatio(-1);
  4995. }
  4996. /**
  4997. * Gets the minimum width for this column.
  4998. *
  4999. * @return the minimum width for this column
  5000. * @see #setMinimumWidth(double)
  5001. */
  5002. public double getMinimumWidth() {
  5003. return minimumWidthPx;
  5004. }
  5005. /**
  5006. * Gets the maximum width for this column.
  5007. *
  5008. * @return the maximum width for this column
  5009. * @see #setMaximumWidth(double)
  5010. */
  5011. public double getMaximumWidth() {
  5012. return maximumWidthPx;
  5013. }
  5014. /**
  5015. * Gets the expand ratio for this column.
  5016. *
  5017. * @return the expand ratio for this column
  5018. * @see #setExpandRatio(int)
  5019. */
  5020. public int getExpandRatio() {
  5021. return expandRatio;
  5022. }
  5023. /**
  5024. * Sets whether the values in this column should be editable by the user
  5025. * when the row editor is active. By default columns are editable.
  5026. *
  5027. * @param editable
  5028. * {@code true} to set this column editable, {@code false}
  5029. * otherwise
  5030. * @return this column
  5031. *
  5032. * @throws IllegalStateException
  5033. * if the editor is currently active
  5034. *
  5035. * @see Grid#editRow(int)
  5036. * @see Grid#isEditorActive()
  5037. */
  5038. public Column<C, T> setEditable(boolean editable) {
  5039. if (editable != this.editable && grid != null
  5040. && grid.isEditorActive()) {
  5041. throw new IllegalStateException(
  5042. "Cannot change column editable status while the editor is active");
  5043. }
  5044. this.editable = editable;
  5045. return this;
  5046. }
  5047. /**
  5048. * Returns whether the values in this column are editable by the user
  5049. * when the row editor is active.
  5050. *
  5051. * @return {@code true} if this column is editable, {@code false}
  5052. * otherwise
  5053. *
  5054. * @see #setEditable(boolean)
  5055. */
  5056. public boolean isEditable() {
  5057. return editable;
  5058. }
  5059. private void scheduleColumnWidthRecalculator() {
  5060. if (grid != null) {
  5061. grid.recalculateColumnWidths();
  5062. } else {
  5063. /*
  5064. * NOOP
  5065. *
  5066. * Since setGrid() will call reapplyWidths as the colum is
  5067. * attached to a grid, it will call setWidth, which, in turn,
  5068. * will call this method again. Therefore, it's guaranteed that
  5069. * the recalculation is scheduled eventually, once the column is
  5070. * attached to a grid.
  5071. */
  5072. }
  5073. }
  5074. /**
  5075. * Resets the default header cell contents to column header captions.
  5076. *
  5077. * @since 7.5.1
  5078. * @param cell
  5079. * default header cell for this column
  5080. */
  5081. protected void setDefaultHeaderContent(HeaderCell cell) {
  5082. cell.setText(headerCaption);
  5083. }
  5084. /**
  5085. * Returns whether Grid should handle events from Widgets in this
  5086. * Column.
  5087. *
  5088. * @return {@code true} to handle events from widgets; {@code false} to
  5089. * not
  5090. * @since 8.3
  5091. */
  5092. public boolean isHandleWidgetEvents() {
  5093. return handleWidgetEvents;
  5094. }
  5095. /**
  5096. * Sets whether Grid should handle events from Widgets in this Column.
  5097. *
  5098. * @param handleWidgetEvents
  5099. * {@code true} to let grid handle events from widgets;
  5100. * {@code false} to not
  5101. *
  5102. * @since 8.3
  5103. */
  5104. public void setHandleWidgetEvents(boolean handleWidgetEvents) {
  5105. this.handleWidgetEvents = handleWidgetEvents;
  5106. }
  5107. }
  5108. protected class BodyUpdater implements EscalatorUpdater {
  5109. @Override
  5110. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5111. int rowIndex = row.getRow();
  5112. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  5113. row.getElement());
  5114. for (FlyweightCell cell : cellsToAttach) {
  5115. Renderer<?> renderer = findRenderer(cell);
  5116. if (renderer instanceof ComplexRenderer) {
  5117. try {
  5118. Column<?, T> column = getVisibleColumn(
  5119. cell.getColumn());
  5120. rendererCellReference.set(cell,
  5121. getColumns().indexOf(column), column);
  5122. ((ComplexRenderer<?>) renderer)
  5123. .init(rendererCellReference);
  5124. } catch (RuntimeException e) {
  5125. getLogger().log(Level.SEVERE,
  5126. "Error initing cell in column "
  5127. + cell.getColumn(),
  5128. e);
  5129. }
  5130. }
  5131. }
  5132. }
  5133. @Override
  5134. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5135. for (FlyweightCell cell : attachedCells) {
  5136. Renderer<?> renderer = findRenderer(cell);
  5137. if (renderer instanceof WidgetRenderer) {
  5138. try {
  5139. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  5140. Widget widget = widgetRenderer.createWidget();
  5141. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  5142. assert widget
  5143. .getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  5144. assert cell.getElement()
  5145. .getChildCount() == 0 : "Cell content should be empty when adding Widget";
  5146. // Physical attach
  5147. cell.getElement().appendChild(widget.getElement());
  5148. // Logical attach
  5149. setParent(widget, Grid.this);
  5150. } catch (RuntimeException e) {
  5151. getLogger().log(Level.SEVERE,
  5152. "Error attaching child widget in column "
  5153. + cell.getColumn(),
  5154. e);
  5155. }
  5156. }
  5157. }
  5158. }
  5159. @Override
  5160. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  5161. int rowIndex = row.getRow();
  5162. TableRowElement rowElement = row.getElement();
  5163. T rowData = dataSource.getRow(rowIndex);
  5164. boolean hasData = rowData != null;
  5165. /*
  5166. * TODO could be more efficient to build a list of all styles that
  5167. * should be used and update the element only once instead of
  5168. * attempting to update only the ones that have changed.
  5169. */
  5170. // Assign stylename for rows with data
  5171. boolean usedToHaveData = rowElement
  5172. .hasClassName(rowHasDataStyleName);
  5173. if (usedToHaveData != hasData) {
  5174. setStyleName(rowElement, rowHasDataStyleName, hasData);
  5175. }
  5176. boolean isEvenIndex = row.getRow() % 2 == 0;
  5177. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  5178. rowReference.set(rowIndex, rowData, rowElement);
  5179. boolean isSelected = hasData && isSelected(rowData);
  5180. if (Grid.this.selectionModel.isSelectionAllowed()) {
  5181. rowElement.setAttribute("aria-selected",
  5182. String.valueOf(isSelected));
  5183. } else {
  5184. rowElement.removeAttribute("aria-selected");
  5185. }
  5186. if (hasData) {
  5187. setStyleName(rowElement, rowSelectedStyleName, isSelected);
  5188. if (rowStyleGenerator != null) {
  5189. try {
  5190. String rowStylename = rowStyleGenerator
  5191. .getStyle(rowReference);
  5192. setCustomStyleName(rowElement, rowStylename);
  5193. } catch (RuntimeException e) {
  5194. getLogger().log(Level.SEVERE,
  5195. "Error generating styles for row "
  5196. + row.getRow(),
  5197. e);
  5198. }
  5199. } else {
  5200. // Remove in case there was a generator previously
  5201. setCustomStyleName(rowElement, null);
  5202. }
  5203. } else if (usedToHaveData) {
  5204. setStyleName(rowElement, rowSelectedStyleName, false);
  5205. setCustomStyleName(rowElement, null);
  5206. }
  5207. cellFocusHandler.updateFocusedRowStyle(row);
  5208. for (FlyweightCell cell : cellsToUpdate) {
  5209. Column<?, T> column = getVisibleColumn(cell.getColumn());
  5210. final int columnIndex = getColumns().indexOf(column);
  5211. assert column != null : "Column was not found from cell ("
  5212. + cell.getColumn() + "," + cell.getRow() + ")";
  5213. cellFocusHandler.updateFocusedCellStyle(cell,
  5214. escalator.getBody());
  5215. if (hasData && cellStyleGenerator != null) {
  5216. try {
  5217. cellReference.set(cell.getColumn(), columnIndex,
  5218. column);
  5219. String generatedStyle = cellStyleGenerator
  5220. .getStyle(cellReference);
  5221. setCustomStyleName(cell.getElement(), generatedStyle);
  5222. } catch (RuntimeException e) {
  5223. getLogger().log(Level.SEVERE,
  5224. "Error generating style for cell in column "
  5225. + cell.getColumn(),
  5226. e);
  5227. }
  5228. } else if (hasData || usedToHaveData) {
  5229. setCustomStyleName(cell.getElement(), null);
  5230. }
  5231. Renderer renderer = column.getRenderer();
  5232. try {
  5233. rendererCellReference.set(cell, columnIndex, column);
  5234. if (renderer instanceof ComplexRenderer) {
  5235. // Hide cell content if needed
  5236. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  5237. if (hasData) {
  5238. if (!usedToHaveData) {
  5239. // Prepare cell for rendering
  5240. clxRenderer.setContentVisible(
  5241. rendererCellReference, true);
  5242. }
  5243. Object value = column.getValue(rowData);
  5244. clxRenderer.render(rendererCellReference, value);
  5245. } else {
  5246. // Prepare cell for no data
  5247. clxRenderer.setContentVisible(rendererCellReference,
  5248. false);
  5249. }
  5250. } else if (hasData) {
  5251. // Simple renderers just render
  5252. Object value = column.getValue(rowData);
  5253. renderer.render(rendererCellReference, value);
  5254. } else {
  5255. // Clear cell if there is no data
  5256. cell.getElement().removeAllChildren();
  5257. }
  5258. } catch (RuntimeException e) {
  5259. getLogger().log(Level.SEVERE,
  5260. "Error rendering cell in column "
  5261. + cell.getColumn(),
  5262. e);
  5263. }
  5264. }
  5265. }
  5266. @Override
  5267. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5268. for (FlyweightCell cell : cellsToDetach) {
  5269. Renderer<?> renderer = findRenderer(cell);
  5270. if (renderer instanceof WidgetRenderer) {
  5271. try {
  5272. Widget w = WidgetUtil.findWidget(
  5273. cell.getElement().getFirstChildElement());
  5274. if (w != null) {
  5275. // Logical detach
  5276. setParent(w, null);
  5277. // Physical detach
  5278. cell.getElement().removeChild(w.getElement());
  5279. }
  5280. } catch (RuntimeException e) {
  5281. getLogger().log(Level.SEVERE,
  5282. "Error detaching widget in column "
  5283. + cell.getColumn(),
  5284. e);
  5285. }
  5286. }
  5287. }
  5288. }
  5289. @Override
  5290. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5291. int rowIndex = row.getRow();
  5292. // Passing null row data since it might not exist in the data source
  5293. // any more
  5294. rowReference.set(rowIndex, null, row.getElement());
  5295. for (FlyweightCell cell : detachedCells) {
  5296. Renderer<?> renderer = findRenderer(cell);
  5297. if (renderer instanceof ComplexRenderer) {
  5298. try {
  5299. Column<?, T> column = getVisibleColumn(
  5300. cell.getColumn());
  5301. rendererCellReference.set(cell,
  5302. getColumns().indexOf(column), column);
  5303. ((ComplexRenderer) renderer)
  5304. .destroy(rendererCellReference);
  5305. } catch (RuntimeException e) {
  5306. getLogger().log(Level.SEVERE,
  5307. "Error destroying cell in column "
  5308. + cell.getColumn(),
  5309. e);
  5310. }
  5311. }
  5312. }
  5313. }
  5314. }
  5315. protected class StaticSectionUpdater implements EscalatorUpdater {
  5316. private StaticSection<?> section;
  5317. private RowContainer container;
  5318. public StaticSectionUpdater(StaticSection<?> section,
  5319. RowContainer container) {
  5320. super();
  5321. this.section = section;
  5322. this.container = container;
  5323. }
  5324. @Override
  5325. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  5326. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  5327. final List<Column<?, T>> columns = getVisibleColumns();
  5328. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  5329. for (FlyweightCell cell : cellsToUpdate) {
  5330. final StaticSection.StaticCell metadata = staticRow
  5331. .getCell(columns.get(cell.getColumn()));
  5332. // Decorate default row with sorting indicators
  5333. if (staticRow instanceof HeaderRow) {
  5334. addAriaLabelToHeaderRow(cell);
  5335. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow,
  5336. cell);
  5337. }
  5338. // Assign colspan to cell before rendering
  5339. cell.setColSpan(metadata.getColspan());
  5340. Element td = cell.getElement();
  5341. td.removeAllChildren();
  5342. setCustomStyleName(td, metadata.getStyleName());
  5343. Element content;
  5344. // Wrap text or html content in default header to isolate
  5345. // the content from the possible column resize drag handle
  5346. // next to it
  5347. if (metadata.getType() != GridStaticCellType.WIDGET) {
  5348. content = DOM.createDiv();
  5349. if (staticRow instanceof HeaderRow) {
  5350. content.setClassName(getStylePrimaryName()
  5351. + "-column-header-content");
  5352. if (((HeaderRow) staticRow).isDefault()) {
  5353. content.setClassName(content.getClassName() + " "
  5354. + getStylePrimaryName()
  5355. + "-column-default-header-content");
  5356. }
  5357. } else if (staticRow instanceof FooterRow) {
  5358. content.setClassName(getStylePrimaryName()
  5359. + "-column-footer-content");
  5360. } else {
  5361. getLogger().severe("Unhandled static row type "
  5362. + staticRow.getClass().getCanonicalName());
  5363. }
  5364. td.appendChild(content);
  5365. } else {
  5366. content = td;
  5367. }
  5368. switch (metadata.getType()) {
  5369. case TEXT:
  5370. content.setInnerText(metadata.getText());
  5371. break;
  5372. case HTML:
  5373. content.setInnerHTML(metadata.getHtml());
  5374. break;
  5375. case WIDGET:
  5376. preDetach(row, Arrays.asList(cell));
  5377. content.setInnerHTML("");
  5378. postAttach(row, Arrays.asList(cell));
  5379. break;
  5380. }
  5381. // XXX: Should add only once in preAttach/postAttach or when
  5382. // resizable status changes
  5383. // Only add resize handles to default header row for now
  5384. if (columns.get(cell.getColumn()).isResizable()
  5385. && staticRow instanceof HeaderRow
  5386. && ((HeaderRow) staticRow).isDefault()) {
  5387. final DivElement resizeElement = Document.get()
  5388. .createDivElement();
  5389. resizeElement.addClassName(getStylePrimaryName()
  5390. + "-column-resize-simple-indicator");
  5391. final int column = cell.getColumn();
  5392. final DragHandle dragger = new DragHandle(
  5393. getStylePrimaryName() + "-column-resize-handle");
  5394. dragger.addTo(td);
  5395. // Save the newest resize handle's width with the assumption
  5396. // that all the resize handles are the same size. This is
  5397. // used in column's minimum width calculations, so the
  5398. // border of the cell is also included.
  5399. resizeHandleWidth = dragger.getElement().getOffsetWidth()
  5400. + WidgetUtil.getBorderLeftAndRightThickness(td);
  5401. // Common functionality for drag handle callback
  5402. // implementations
  5403. abstract class AbstractDHCallback
  5404. implements DragHandleCallback {
  5405. protected Column<?, T> col = getVisibleColumn(column);
  5406. protected double initialWidth = 0;
  5407. protected double minCellWidth;
  5408. protected double width;
  5409. protected void dragStarted() {
  5410. initialWidth = col.getWidthActual();
  5411. width = initialWidth;
  5412. minCellWidth = escalator.getMinCellWidth(
  5413. getVisibleColumns().indexOf(col));
  5414. for (Column<?, T> c : getVisibleColumns()) {
  5415. if (selectionColumn == c) {
  5416. // Don't modify selection column.
  5417. continue;
  5418. }
  5419. if (c.getWidth() < 0) {
  5420. c.setWidth(c.getWidthActual());
  5421. fireEvent(new ColumnResizeEvent<>(c));
  5422. }
  5423. }
  5424. WidgetUtil.setTextSelectionEnabled(getElement(),
  5425. false);
  5426. }
  5427. protected void dragEnded() {
  5428. WidgetUtil.setTextSelectionEnabled(getElement(),
  5429. true);
  5430. }
  5431. }
  5432. final DragHandleCallback simpleResizeMode = new AbstractDHCallback() {
  5433. @Override
  5434. protected void dragEnded() {
  5435. super.dragEnded();
  5436. dragger.getElement().removeChild(resizeElement);
  5437. }
  5438. @Override
  5439. public void onStart() {
  5440. dragStarted();
  5441. dragger.getElement().appendChild(resizeElement);
  5442. resizeElement.getStyle().setLeft(
  5443. (dragger.getElement().getOffsetWidth()
  5444. - resizeElement.getOffsetWidth())
  5445. * .5,
  5446. Unit.PX);
  5447. resizeElement.getStyle().setHeight(
  5448. col.grid.getOffsetHeight(), Unit.PX);
  5449. }
  5450. @Override
  5451. public void onUpdate(double deltaX, double deltaY) {
  5452. width = Math.max(minCellWidth,
  5453. initialWidth + deltaX);
  5454. resizeElement.getStyle().setLeft(
  5455. (dragger.getElement().getOffsetWidth()
  5456. - resizeElement.getOffsetWidth())
  5457. * .5 + (width - initialWidth),
  5458. Unit.PX);
  5459. }
  5460. @Override
  5461. public void onCancel() {
  5462. dragEnded();
  5463. }
  5464. @Override
  5465. public void onComplete() {
  5466. dragEnded();
  5467. col.setWidth(width);
  5468. // Need to wait for column width recalculation
  5469. // scheduled by setWidth() before firing the event
  5470. Scheduler.get().scheduleDeferred(() -> fireEvent(
  5471. new ColumnResizeEvent<>(col)));
  5472. }
  5473. };
  5474. final DragHandleCallback animatedResizeMode = new AbstractDHCallback() {
  5475. @Override
  5476. public void onStart() {
  5477. dragStarted();
  5478. }
  5479. @Override
  5480. public void onUpdate(double deltaX, double deltaY) {
  5481. width = Math.max(minCellWidth,
  5482. initialWidth + deltaX);
  5483. col.setWidth(width);
  5484. }
  5485. @Override
  5486. public void onCancel() {
  5487. dragEnded();
  5488. col.setWidth(initialWidth);
  5489. }
  5490. @Override
  5491. public void onComplete() {
  5492. dragEnded();
  5493. col.setWidth(width);
  5494. fireEvent(new ColumnResizeEvent<>(col));
  5495. }
  5496. };
  5497. // DragHandle gets assigned a 'master callback' that
  5498. // delegates
  5499. // functionality to the correct case-specific implementation
  5500. dragger.setCallback(new DragHandleCallback() {
  5501. private DragHandleCallback currentCallback;
  5502. @Override
  5503. public void onStart() {
  5504. switch (getColumnResizeMode()) {
  5505. case SIMPLE:
  5506. currentCallback = simpleResizeMode;
  5507. break;
  5508. case ANIMATED:
  5509. currentCallback = animatedResizeMode;
  5510. break;
  5511. default:
  5512. throw new UnsupportedOperationException(
  5513. "Support for current column resize mode is not yet implemented");
  5514. }
  5515. currentCallback.onStart();
  5516. }
  5517. @Override
  5518. public void onUpdate(double deltaX, double deltaY) {
  5519. currentCallback.onUpdate(deltaX, deltaY);
  5520. }
  5521. @Override
  5522. public void onCancel() {
  5523. currentCallback.onCancel();
  5524. }
  5525. @Override
  5526. public void onComplete() {
  5527. currentCallback.onComplete();
  5528. }
  5529. });
  5530. }
  5531. cellFocusHandler.updateFocusedCellStyle(cell, container);
  5532. }
  5533. }
  5534. private void addAriaLabelToHeaderRow(FlyweightCell cell) {
  5535. Element cellElement = cell.getElement();
  5536. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5537. if (column.getAssistiveCaption() != null) {
  5538. cellElement.setAttribute("aria-label",
  5539. column.getAssistiveCaption());
  5540. } else {
  5541. cellElement.removeAttribute("aria-label");
  5542. }
  5543. }
  5544. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  5545. FlyweightCell cell) {
  5546. Element cellElement = cell.getElement();
  5547. boolean sortedBefore = cellElement.hasClassName("sort-asc")
  5548. || cellElement.hasClassName("sort-desc");
  5549. cleanup(cell);
  5550. if (!headerRow.isDefault()) {
  5551. // Nothing more to do if not in the default row
  5552. return;
  5553. }
  5554. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5555. SortOrder sortingOrder = getSortOrder(column);
  5556. boolean sortable = column.isSortable();
  5557. if (sortable) {
  5558. cellElement.addClassName("sortable");
  5559. cellElement.setAttribute("aria-sort", "none");
  5560. }
  5561. if (!sortable || sortingOrder == null) {
  5562. // Only apply sorting indicators to sortable header columns
  5563. return;
  5564. }
  5565. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  5566. cellElement.addClassName("sort-asc");
  5567. cellElement.setAttribute("aria-sort", "ascending");
  5568. } else {
  5569. cellElement.addClassName("sort-desc");
  5570. cellElement.setAttribute("aria-sort", "descending");
  5571. }
  5572. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  5573. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  5574. // Show sort order indicator if column is
  5575. // sorted and other sorted columns also exists.
  5576. cellElement.setAttribute("sort-order",
  5577. String.valueOf(sortIndex + 1));
  5578. cellElement.setAttribute("aria-sort", "other");
  5579. }
  5580. if (!sortedBefore) {
  5581. verifyColumnWidth(column);
  5582. }
  5583. }
  5584. /**
  5585. * Sort indicator requires a bit more space from the cell than normally.
  5586. * This method check that the now sorted column has enough width.
  5587. *
  5588. * @param column
  5589. * sorted column
  5590. */
  5591. private void verifyColumnWidth(Column<?, T> column) {
  5592. int colIndex = getColumns().indexOf(column);
  5593. double minWidth = escalator.getMinCellWidth(colIndex);
  5594. if (column.getWidthActual() < minWidth) {
  5595. // Fix column size
  5596. escalator.getColumnConfiguration().setColumnWidth(colIndex,
  5597. minWidth);
  5598. fireEvent(new ColumnResizeEvent<>(column));
  5599. }
  5600. }
  5601. /**
  5602. * Finds the sort order for this column
  5603. */
  5604. private SortOrder getSortOrder(Column<?, ?> column) {
  5605. for (SortOrder order : Grid.this.getSortOrder()) {
  5606. if (order.getColumn() == column) {
  5607. return order;
  5608. }
  5609. }
  5610. return null;
  5611. }
  5612. private void cleanup(FlyweightCell cell) {
  5613. Element cellElement = cell.getElement();
  5614. cellElement.removeAttribute("sort-order");
  5615. cellElement.removeAttribute("aria-sort");
  5616. cellElement.removeClassName("sort-desc");
  5617. cellElement.removeClassName("sort-asc");
  5618. cellElement.removeClassName("sortable");
  5619. }
  5620. @Override
  5621. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5622. }
  5623. @Override
  5624. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5625. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  5626. List<Column<?, T>> columns = getVisibleColumns();
  5627. for (FlyweightCell cell : attachedCells) {
  5628. StaticSection.StaticCell metadata = gridRow
  5629. .getCell(columns.get(cell.getColumn()));
  5630. /*
  5631. * If the cell contains widgets that are not currently attached
  5632. * then attach them now.
  5633. */
  5634. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  5635. final Widget widget = metadata.getWidget();
  5636. if (widget != null && !widget.isAttached()) {
  5637. getGrid().attachWidget(metadata.getWidget(),
  5638. cell.getElement());
  5639. }
  5640. }
  5641. }
  5642. }
  5643. @Override
  5644. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5645. if (section.getRowCount() > row.getRow()) {
  5646. StaticSection.StaticRow<?> gridRow = section
  5647. .getRow(row.getRow());
  5648. List<Column<?, T>> columns = getVisibleColumns();
  5649. for (FlyweightCell cell : cellsToDetach) {
  5650. StaticSection.StaticCell metadata = gridRow
  5651. .getCell(columns.get(cell.getColumn()));
  5652. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  5653. && metadata.getWidget() != null
  5654. && metadata.getWidget().isAttached()) {
  5655. getGrid().detachWidget(metadata.getWidget());
  5656. }
  5657. }
  5658. }
  5659. }
  5660. protected Grid getGrid() {
  5661. return section.grid;
  5662. }
  5663. @Override
  5664. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5665. }
  5666. };
  5667. /**
  5668. * Creates a new instance.
  5669. */
  5670. public Grid() {
  5671. initWidget(escalator);
  5672. getElement().setTabIndex(0);
  5673. cellFocusHandler = new CellFocusHandler();
  5674. setStylePrimaryName(STYLE_NAME);
  5675. setAriaRole("grid");
  5676. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  5677. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  5678. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  5679. header.setGrid(this);
  5680. HeaderRow defaultRow = header.appendRow();
  5681. header.setDefaultRow(defaultRow);
  5682. footer.setGrid(this);
  5683. editor.setGrid(this);
  5684. setSelectionModel(new SelectionModel.NoSelectionModel<>());
  5685. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  5686. escalator.addScrollHandler(event -> fireEvent(new ScrollEvent()));
  5687. escalator.addRowVisibilityChangeHandler(event -> {
  5688. if (dataSource != null && dataSource.size() != 0) {
  5689. dataSource.ensureAvailability(event.getFirstVisibleRow(),
  5690. event.getVisibleRowCount());
  5691. }
  5692. });
  5693. escalator.addVerticalScrollbarVisibilityChangeHandler(event -> {
  5694. if (!(currentDataAvailable.isEmpty()
  5695. && escalator.getBody().getRowCount() > 0)) {
  5696. recalculateColumnWidths();
  5697. } else {
  5698. recalculateColumnWidthsNeeded = true;
  5699. }
  5700. });
  5701. // Default action on SelectionEvents. Refresh the body so changed
  5702. // become visible.
  5703. addSelectionHandler(new SelectionHandler<T>() {
  5704. @Override
  5705. public void onSelect(SelectionEvent<T> event) {
  5706. refreshBody();
  5707. }
  5708. });
  5709. addSpacerIndexChangedHandler(new SpacerIndexChangedHandler() {
  5710. @Override
  5711. public void onSpacerIndexChanged(SpacerIndexChangedEvent event) {
  5712. // remove old index and add new index
  5713. visibleDetails.remove(event.getOldIndex());
  5714. visibleDetails.add(event.getNewIndex());
  5715. }
  5716. });
  5717. // Sink header events and key events
  5718. sinkEvents(getHeader().getConsumedEvents());
  5719. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  5720. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  5721. BrowserEvents.MOUSEDOWN, BrowserEvents.CLICK));
  5722. // Make ENTER and SHIFT+ENTER in the header perform sorting
  5723. addHeaderKeyUpHandler(event -> {
  5724. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  5725. return;
  5726. }
  5727. if (getHeader().getRow(event.getFocusedCell().getRowIndex())
  5728. .isDefault()) {
  5729. // Only sort for enter on the default header
  5730. sorter.sort(event.getFocusedCell().getColumn(),
  5731. event.isShiftKeyDown());
  5732. }
  5733. });
  5734. browserEventHandlers.addAll(Arrays.asList(
  5735. // Opening, closing and navigating in the editor
  5736. new EditorEventHandler(),
  5737. // Keyboard and click handlers, Escalator events
  5738. new SuperEventHandler(),
  5739. // Column reordering via header drag&drop
  5740. new HeaderCellDragStartHandler(),
  5741. // Column sorting via header click
  5742. new HeaderDefaultRowEventHandler(),
  5743. // Invoking event-aware renderers
  5744. new RendererEventHandler(),
  5745. // Moving cell focus by keyboard or mouse
  5746. new CellFocusEventHandler()));
  5747. }
  5748. @Override
  5749. public boolean isEnabled() {
  5750. return enabled;
  5751. }
  5752. @Override
  5753. public void setEnabled(boolean enabled) {
  5754. if (enabled == this.enabled) {
  5755. return;
  5756. }
  5757. this.enabled = enabled;
  5758. getElement().setTabIndex(enabled ? 0 : -1);
  5759. // Editor save and cancel buttons need to be disabled.
  5760. boolean editorOpen = editor.getState() != State.INACTIVE;
  5761. if (editorOpen) {
  5762. editor.setGridEnabled(enabled);
  5763. }
  5764. sidebar.setEnabled(enabled);
  5765. getEscalator().setScrollLocked(Direction.VERTICAL,
  5766. !enabled || editorOpen);
  5767. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  5768. getHeader().requestSectionRefresh();
  5769. fireEvent(new GridEnabledEvent(enabled));
  5770. }
  5771. /**
  5772. * Sets the column resize mode to use. The default mode is
  5773. * {@link ColumnResizeMode.ANIMATED}.
  5774. *
  5775. * @param mode
  5776. * a ColumnResizeMode value
  5777. *
  5778. * @since 7.7.5
  5779. */
  5780. public void setColumnResizeMode(ColumnResizeMode mode) {
  5781. columnResizeMode = mode;
  5782. }
  5783. /**
  5784. * Returns the current column resize mode. The default mode is
  5785. * {@link ColumnResizeMode.ANIMATED}.
  5786. *
  5787. * @return a ColumnResizeMode value
  5788. * @since 7.7.5
  5789. */
  5790. public ColumnResizeMode getColumnResizeMode() {
  5791. return columnResizeMode;
  5792. }
  5793. @Override
  5794. public void setStylePrimaryName(String style) {
  5795. super.setStylePrimaryName(style);
  5796. escalator.setStylePrimaryName(style);
  5797. editor.setStylePrimaryName(style);
  5798. sidebar.setStylePrimaryName(style + "-sidebar");
  5799. sidebar.addStyleName("v-contextmenu");
  5800. String rowStyle = getStylePrimaryName() + "-row";
  5801. rowHasDataStyleName = rowStyle + "-has-data";
  5802. rowSelectedStyleName = rowStyle + "-selected";
  5803. rowStripeStyleName = rowStyle + "-stripe";
  5804. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  5805. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  5806. if (isAttached()) {
  5807. refreshHeader();
  5808. requestRefreshBody();
  5809. refreshFooter();
  5810. }
  5811. }
  5812. /**
  5813. * Adds the given role as 'role="$param"' to the <code>&lt;table&gt;</code>
  5814. * element of the grid.
  5815. *
  5816. * @param role
  5817. * the role param
  5818. * @since 8.2
  5819. */
  5820. protected void setAriaRole(String role) {
  5821. escalator.getTable().setAttribute("role", role);
  5822. }
  5823. /**
  5824. * Creates the escalator updater used to update the header rows in this
  5825. * grid. The updater is invoked when header rows or columns are added or
  5826. * removed, or the content of existing header cells is changed.
  5827. *
  5828. * @return the new header updater instance
  5829. *
  5830. * @see GridHeader
  5831. * @see Grid#getHeader()
  5832. */
  5833. protected EscalatorUpdater createHeaderUpdater() {
  5834. return new StaticSectionUpdater(header, escalator.getHeader());
  5835. }
  5836. /**
  5837. * Creates the escalator updater used to update the body rows in this grid.
  5838. * The updater is invoked when body rows or columns are added or removed,
  5839. * the content of body cells is changed, or the body is scrolled to expose
  5840. * previously hidden content.
  5841. *
  5842. * @return the new body updater instance
  5843. */
  5844. protected EscalatorUpdater createBodyUpdater() {
  5845. return new BodyUpdater();
  5846. }
  5847. /**
  5848. * Creates the escalator updater used to update the footer rows in this
  5849. * grid. The updater is invoked when header rows or columns are added or
  5850. * removed, or the content of existing header cells is changed.
  5851. *
  5852. * @return the new footer updater instance
  5853. *
  5854. * @see GridFooter
  5855. * @see #getFooter()
  5856. */
  5857. protected EscalatorUpdater createFooterUpdater() {
  5858. return new StaticSectionUpdater(footer, escalator.getFooter());
  5859. }
  5860. /**
  5861. * Refreshes header or footer rows on demand
  5862. *
  5863. * @param rows
  5864. * The row container
  5865. * @param firstRowIsVisible
  5866. * is the first row visible
  5867. * @param isHeader
  5868. * <code>true</code> if we refreshing the header, else assumed
  5869. * the footer
  5870. */
  5871. private void refreshRowContainer(RowContainer rows,
  5872. StaticSection<?> section) {
  5873. // Add or Remove rows on demand
  5874. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  5875. if (rowDiff > 0) {
  5876. rows.insertRows(0, rowDiff);
  5877. } else if (rowDiff < 0) {
  5878. rows.removeRows(0, -rowDiff);
  5879. }
  5880. // Refresh all the rows
  5881. if (rows.getRowCount() > 0) {
  5882. rows.refreshRows(0, rows.getRowCount());
  5883. }
  5884. }
  5885. /**
  5886. * Focus a body cell by row and column index.
  5887. *
  5888. * @param rowIndex
  5889. * index of row to focus
  5890. * @param columnIndexDOM
  5891. * index (excluding hidden columns) of cell to focus
  5892. */
  5893. void focusCell(int rowIndex, int columnIndexDOM) {
  5894. final Range rowRange = Range.between(0, dataSource.size());
  5895. final Range columnRange = Range.between(0, getVisibleColumns().size());
  5896. assert rowRange.contains(
  5897. rowIndex) : "Illegal row index. Should be in range " + rowRange;
  5898. assert columnRange.contains(
  5899. columnIndexDOM) : "Illegal column index. Should be in range "
  5900. + columnRange;
  5901. if (rowRange.contains(rowIndex)
  5902. && columnRange.contains(columnIndexDOM)) {
  5903. cellFocusHandler.setCellFocus(rowIndex, columnIndexDOM,
  5904. escalator.getBody());
  5905. WidgetUtil.focus(getElement());
  5906. }
  5907. }
  5908. /**
  5909. * Refreshes all header rows
  5910. */
  5911. void refreshHeader() {
  5912. refreshRowContainer(escalator.getHeader(), header);
  5913. }
  5914. /**
  5915. * Refreshes all body rows
  5916. */
  5917. private void refreshBody() {
  5918. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  5919. }
  5920. /**
  5921. * Request delayed refresh of all body rows.
  5922. *
  5923. * @since 8.1
  5924. */
  5925. public void requestRefreshBody() {
  5926. if (!refreshBodyRequested) {
  5927. refreshBodyRequested = true;
  5928. Scheduler.get().scheduleFinally(() -> {
  5929. refreshBodyRequested = false;
  5930. refreshBody();
  5931. });
  5932. }
  5933. }
  5934. /**
  5935. * Refreshes all footer rows
  5936. */
  5937. void refreshFooter() {
  5938. refreshRowContainer(escalator.getFooter(), footer);
  5939. }
  5940. /**
  5941. * Adds columns as the last columns in the grid.
  5942. *
  5943. * @param columns
  5944. * the columns to add
  5945. */
  5946. public void addColumns(Column<?, T>... columns) {
  5947. if (columns.length == 0) {
  5948. // Nothing to add.
  5949. return;
  5950. }
  5951. addColumnsSkipSelectionColumnCheck(Arrays.asList(columns),
  5952. getVisibleColumns().size());
  5953. }
  5954. /**
  5955. * Adds a column as the last column in the grid.
  5956. *
  5957. * @param column
  5958. * the column to add
  5959. * @return given column
  5960. */
  5961. public <C extends Column<?, T>> C addColumn(C column) {
  5962. addColumn(column, getColumnCount());
  5963. return column;
  5964. }
  5965. /**
  5966. * Inserts a column into a specific position in the grid.
  5967. *
  5968. * @param index
  5969. * the index where the column should be inserted into
  5970. * @param column
  5971. * the column to add
  5972. * @return given column
  5973. *
  5974. * @throws IllegalStateException
  5975. * if Grid's current selection model renders a selection column,
  5976. * and {@code index} is 0.
  5977. */
  5978. public <C extends Column<?, T>> C addColumn(C column, int index) {
  5979. if (column == selectionColumn) {
  5980. throw new IllegalArgumentException(
  5981. "The selection column may not be added manually");
  5982. } else if (selectionColumn != null && index == 0) {
  5983. throw new IllegalStateException("A column cannot be inserted "
  5984. + "before the selection column");
  5985. }
  5986. addColumnsSkipSelectionColumnCheck(Collections.singleton(column),
  5987. index);
  5988. return column;
  5989. }
  5990. private void addColumnsSkipSelectionColumnCheck(
  5991. Collection<Column<?, T>> columnsToAdd, int startIndex) {
  5992. AtomicInteger index = new AtomicInteger(startIndex);
  5993. columnsToAdd.forEach(col -> {
  5994. // Register column with grid
  5995. columns.add(index.getAndIncrement(), col);
  5996. header.addColumn(col);
  5997. footer.addColumn(col);
  5998. // Register this grid instance with the column
  5999. col.setGrid(this);
  6000. });
  6001. escalator.getColumnConfiguration().insertColumns(startIndex,
  6002. (int) columnsToAdd.stream().filter(col -> !col.isHidden())
  6003. .count());
  6004. columnsToAdd.forEach(col -> {
  6005. // Reapply column width
  6006. col.reapplyWidth();
  6007. // Sink all renderer events
  6008. Set<String> events = new HashSet<>();
  6009. events.addAll(getConsumedEventsForRenderer(col.getRenderer()));
  6010. if (col.isHidable()) {
  6011. columnHider.updateColumnHidable(col);
  6012. }
  6013. sinkEvents(events);
  6014. });
  6015. }
  6016. private void sinkEvents(Collection<String> events) {
  6017. assert events != null;
  6018. int eventsToSink = 0;
  6019. for (String typeName : events) {
  6020. int typeInt = Event.getTypeInt(typeName);
  6021. if (typeInt < 0) {
  6022. // Type not recognized by typeInt
  6023. sinkBitlessEvent(typeName);
  6024. } else {
  6025. eventsToSink |= typeInt;
  6026. }
  6027. }
  6028. if (eventsToSink > 0) {
  6029. sinkEvents(eventsToSink);
  6030. }
  6031. }
  6032. private Renderer<?> findRenderer(FlyweightCell cell) {
  6033. Column<?, T> column = getVisibleColumn(cell.getColumn());
  6034. assert column != null : "Could not find column at index:"
  6035. + cell.getColumn();
  6036. return column.getRenderer();
  6037. }
  6038. /**
  6039. * Removes a column from the grid.
  6040. *
  6041. * @param column
  6042. * the column to remove
  6043. */
  6044. public void removeColumn(Column<?, T> column) {
  6045. if (column != null && column.equals(selectionColumn)) {
  6046. throw new IllegalArgumentException(
  6047. "The selection column may not be removed manually.");
  6048. }
  6049. removeColumnSkipSelectionColumnCheck(column);
  6050. }
  6051. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  6052. int columnIndex = columns.indexOf(column);
  6053. // Remove from column configuration
  6054. int visibleColumnIndex = getVisibleColumns().indexOf(column);
  6055. if (visibleColumnIndex < 0) {
  6056. assert column.isHidden();
  6057. // Hidden columns are not included in Escalator
  6058. } else {
  6059. getEscalator().getColumnConfiguration()
  6060. .removeColumns(visibleColumnIndex, 1);
  6061. }
  6062. header.removeColumn(column);
  6063. footer.removeColumn(column);
  6064. // de-register column with grid
  6065. ((Column<?, T>) column).setGrid(null);
  6066. columns.remove(columnIndex);
  6067. if (column.isHidable()) {
  6068. columnHider.removeColumnHidingToggle(column);
  6069. }
  6070. updateFrozenColumns();
  6071. }
  6072. /**
  6073. * Returns the amount of columns in the grid.
  6074. * <p>
  6075. * <em>NOTE:</em> this includes the hidden columns in the count.
  6076. *
  6077. * @return The number of columns in the grid
  6078. */
  6079. public int getColumnCount() {
  6080. return columns.size();
  6081. }
  6082. /**
  6083. * Returns a list columns in the grid, including hidden columns.
  6084. * <p>
  6085. * For currently visible columns, use {@link #getVisibleColumns()}.
  6086. *
  6087. * @return A unmodifiable list of the columns in the grid
  6088. */
  6089. public List<Column<?, T>> getColumns() {
  6090. return Collections.unmodifiableList(new ArrayList<>(columns));
  6091. }
  6092. /**
  6093. * Returns a list of the currently visible columns in the grid.
  6094. * <p>
  6095. * No {@link Column#isHidden() hidden} columns included.
  6096. *
  6097. * @since 7.5.0
  6098. * @return A unmodifiable list of the currently visible columns in the grid
  6099. */
  6100. public List<Column<?, T>> getVisibleColumns() {
  6101. List<Column<?, T>> visible = new ArrayList<>();
  6102. for (Column<?, T> c : columns) {
  6103. if (!c.isHidden()) {
  6104. visible.add(c);
  6105. }
  6106. }
  6107. return Collections.unmodifiableList(visible);
  6108. }
  6109. /**
  6110. * Returns a column by its index in the grid.
  6111. * <p>
  6112. * <em>NOTE:</em> The indexing includes hidden columns.
  6113. *
  6114. * @param index
  6115. * the index of the column
  6116. * @return The column in the given index
  6117. * @throws IllegalArgumentException
  6118. * if the column index does not exist in the grid
  6119. */
  6120. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  6121. if (index < 0 || index >= columns.size()) {
  6122. throw new IllegalStateException("Column not found.");
  6123. }
  6124. return columns.get(index);
  6125. }
  6126. private Column<?, T> getVisibleColumn(int index)
  6127. throws IllegalArgumentException {
  6128. List<Column<?, T>> visibleColumns = getVisibleColumns();
  6129. if (index < 0 || index >= visibleColumns.size()) {
  6130. throw new IllegalStateException("Column not found.");
  6131. }
  6132. return visibleColumns.get(index);
  6133. }
  6134. /**
  6135. * Returns the header section of this grid. The default header contains a
  6136. * single row displaying the column captions.
  6137. *
  6138. * @return the header
  6139. */
  6140. protected Header getHeader() {
  6141. return header;
  6142. }
  6143. /**
  6144. * Gets the header row at given index.
  6145. *
  6146. * @param rowIndex
  6147. * 0 based index for row. Counted from top to bottom
  6148. * @return header row at given index
  6149. * @throws IllegalArgumentException
  6150. * if no row exists at given index
  6151. */
  6152. public HeaderRow getHeaderRow(int rowIndex) {
  6153. return header.getRow(rowIndex);
  6154. }
  6155. /**
  6156. * Inserts a new row at the given position to the header section. Shifts the
  6157. * row currently at that position and any subsequent rows down (adds one to
  6158. * their indices).
  6159. *
  6160. * @param index
  6161. * the position at which to insert the row
  6162. * @return the new row
  6163. *
  6164. * @throws IllegalArgumentException
  6165. * if the index is less than 0 or greater than row count
  6166. * @see #appendHeaderRow()
  6167. * @see #prependHeaderRow()
  6168. * @see #removeHeaderRow(HeaderRow)
  6169. * @see #removeHeaderRow(int)
  6170. */
  6171. public HeaderRow addHeaderRowAt(int index) {
  6172. return header.addRowAt(index);
  6173. }
  6174. /**
  6175. * Adds a new row at the bottom of the header section.
  6176. *
  6177. * @return the new row
  6178. * @see #prependHeaderRow()
  6179. * @see #addHeaderRowAt(int)
  6180. * @see #removeHeaderRow(HeaderRow)
  6181. * @see #removeHeaderRow(int)
  6182. */
  6183. public HeaderRow appendHeaderRow() {
  6184. return header.appendRow();
  6185. }
  6186. /**
  6187. * Returns the current default row of the header section. The default row is
  6188. * a special header row providing a user interface for sorting columns.
  6189. * Setting a header caption for column updates cells in the default header.
  6190. *
  6191. * @return the default row or null if no default row set
  6192. */
  6193. public HeaderRow getDefaultHeaderRow() {
  6194. return header.getDefaultRow();
  6195. }
  6196. /**
  6197. * Gets the row count for the header section.
  6198. *
  6199. * @return row count
  6200. */
  6201. public int getHeaderRowCount() {
  6202. return header.getRowCount();
  6203. }
  6204. /**
  6205. * Adds a new row at the top of the header section.
  6206. *
  6207. * @return the new row
  6208. * @see #appendHeaderRow()
  6209. * @see #addHeaderRowAt(int)
  6210. * @see #removeHeaderRow(HeaderRow)
  6211. * @see #removeHeaderRow(int)
  6212. */
  6213. public HeaderRow prependHeaderRow() {
  6214. return header.prependRow();
  6215. }
  6216. /**
  6217. * Removes the given row from the header section.
  6218. *
  6219. * @param row
  6220. * the row to be removed
  6221. *
  6222. * @throws IllegalArgumentException
  6223. * if the row does not exist in this section
  6224. * @see #removeHeaderRow(int)
  6225. * @see #addHeaderRowAt(int)
  6226. * @see #appendHeaderRow()
  6227. * @see #prependHeaderRow()
  6228. */
  6229. public void removeHeaderRow(HeaderRow row) {
  6230. header.removeRow(row);
  6231. }
  6232. /**
  6233. * Removes the row at the given position from the header section.
  6234. *
  6235. * @param rowIndex
  6236. * the position of the row
  6237. *
  6238. * @throws IllegalArgumentException
  6239. * if no row exists at given index
  6240. * @see #removeHeaderRow(HeaderRow)
  6241. * @see #addHeaderRowAt(int)
  6242. * @see #appendHeaderRow()
  6243. * @see #prependHeaderRow()
  6244. */
  6245. public void removeHeaderRow(int rowIndex) {
  6246. header.removeRow(rowIndex);
  6247. }
  6248. /**
  6249. * Sets the default row of the header. The default row is a special header
  6250. * row providing a user interface for sorting columns.
  6251. * <p>
  6252. * Note: Setting the default header row will reset all cell contents to
  6253. * Column defaults.
  6254. *
  6255. * @param row
  6256. * the new default row, or null for no default row
  6257. *
  6258. * @throws IllegalArgumentException
  6259. * header does not contain the row
  6260. */
  6261. public void setDefaultHeaderRow(HeaderRow row) {
  6262. header.setDefaultRow(row);
  6263. }
  6264. /**
  6265. * Sets the visibility of the header section.
  6266. *
  6267. * @param visible
  6268. * true to show header section, false to hide
  6269. */
  6270. public void setHeaderVisible(boolean visible) {
  6271. header.setVisible(visible);
  6272. }
  6273. /**
  6274. * Returns the visibility of the header section.
  6275. *
  6276. * @return true if visible, false otherwise.
  6277. */
  6278. public boolean isHeaderVisible() {
  6279. return header.isVisible();
  6280. }
  6281. /* Grid Footers */
  6282. /**
  6283. * Returns the footer section of this grid. The default footer is empty.
  6284. *
  6285. * @return the footer
  6286. */
  6287. protected Footer getFooter() {
  6288. return footer;
  6289. }
  6290. /**
  6291. * Gets the footer row at given index.
  6292. *
  6293. * @param rowIndex
  6294. * 0 based index for row. Counted from top to bottom
  6295. * @return footer row at given index
  6296. * @throws IllegalArgumentException
  6297. * if no row exists at given index
  6298. */
  6299. public FooterRow getFooterRow(int rowIndex) {
  6300. return footer.getRow(rowIndex);
  6301. }
  6302. /**
  6303. * Inserts a new row at the given position to the footer section. Shifts the
  6304. * row currently at that position and any subsequent rows down (adds one to
  6305. * their indices).
  6306. *
  6307. * @param index
  6308. * the position at which to insert the row
  6309. * @return the new row
  6310. *
  6311. * @throws IllegalArgumentException
  6312. * if the index is less than 0 or greater than row count
  6313. * @see #appendFooterRow()
  6314. * @see #prependFooterRow()
  6315. * @see #removeFooterRow(FooterRow)
  6316. * @see #removeFooterRow(int)
  6317. */
  6318. public FooterRow addFooterRowAt(int index) {
  6319. return footer.addRowAt(index);
  6320. }
  6321. /**
  6322. * Adds a new row at the bottom of the footer section.
  6323. *
  6324. * @return the new row
  6325. * @see #prependFooterRow()
  6326. * @see #addFooterRowAt(int)
  6327. * @see #removeFooterRow(FooterRow)
  6328. * @see #removeFooterRow(int)
  6329. */
  6330. public FooterRow appendFooterRow() {
  6331. return footer.appendRow();
  6332. }
  6333. /**
  6334. * Gets the row count for the footer.
  6335. *
  6336. * @return row count
  6337. */
  6338. public int getFooterRowCount() {
  6339. return footer.getRowCount();
  6340. }
  6341. /**
  6342. * Adds a new row at the top of the footer section.
  6343. *
  6344. * @return the new row
  6345. * @see #appendFooterRow()
  6346. * @see #addFooterRowAt(int)
  6347. * @see #removeFooterRow(FooterRow)
  6348. * @see #removeFooterRow(int)
  6349. */
  6350. public FooterRow prependFooterRow() {
  6351. return footer.prependRow();
  6352. }
  6353. /**
  6354. * Removes the given row from the footer section.
  6355. *
  6356. * @param row
  6357. * the row to be removed
  6358. *
  6359. * @throws IllegalArgumentException
  6360. * if the row does not exist in this section
  6361. * @see #removeFooterRow(int)
  6362. * @see #addFooterRowAt(int)
  6363. * @see #appendFooterRow()
  6364. * @see #prependFooterRow()
  6365. */
  6366. public void removeFooterRow(FooterRow row) {
  6367. footer.removeRow(row);
  6368. }
  6369. /**
  6370. * Removes the row at the given position from the footer section.
  6371. *
  6372. * @param rowIndex
  6373. * the position of the row
  6374. *
  6375. * @throws IllegalArgumentException
  6376. * if no row exists at given index
  6377. * @see #removeFooterRow(FooterRow)
  6378. * @see #addFooterRowAt(int)
  6379. * @see #appendFooterRow()
  6380. * @see #prependFooterRow()
  6381. */
  6382. public void removeFooterRow(int rowIndex) {
  6383. footer.removeRow(rowIndex);
  6384. }
  6385. /**
  6386. * Sets the visibility of the footer section.
  6387. *
  6388. * @param visible
  6389. * true to show footer section, false to hide
  6390. */
  6391. public void setFooterVisible(boolean visible) {
  6392. footer.setVisible(visible);
  6393. }
  6394. /**
  6395. * Returns the visibility of the footer section.
  6396. *
  6397. * @return true if visible, false otherwise.
  6398. */
  6399. public boolean isFooterVisible() {
  6400. return footer.isVisible();
  6401. }
  6402. public Editor<T> getEditor() {
  6403. return editor;
  6404. }
  6405. /**
  6406. * Gets the {@link Escalator} used by this Grid instance.
  6407. *
  6408. * @return the escalator instance, never <code>null</code>
  6409. */
  6410. public Escalator getEscalator() {
  6411. return escalator;
  6412. }
  6413. /**
  6414. * {@inheritDoc}
  6415. * <p>
  6416. * <em>Note:</em> This method will change the widget's size in the browser
  6417. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  6418. *
  6419. * @see #setHeightMode(HeightMode)
  6420. */
  6421. @Override
  6422. public void setHeight(String height) {
  6423. escalator.setHeight(height);
  6424. }
  6425. @Override
  6426. public void setWidth(String width) {
  6427. escalator.setWidth(width);
  6428. }
  6429. /**
  6430. * Sets the data source used by this grid.
  6431. *
  6432. * @param dataSource
  6433. * the data source to use, not null
  6434. * @throws IllegalArgumentException
  6435. * if <code>dataSource</code> is <code>null</code>
  6436. */
  6437. public void setDataSource(final DataSource<T> dataSource)
  6438. throws IllegalArgumentException {
  6439. if (dataSource == null) {
  6440. throw new IllegalArgumentException("dataSource can't be null.");
  6441. }
  6442. if (changeHandler != null) {
  6443. changeHandler.remove();
  6444. changeHandler = null;
  6445. }
  6446. this.dataSource = dataSource;
  6447. changeHandler = dataSource
  6448. .addDataChangeHandler(new DataChangeHandler() {
  6449. @Override
  6450. public void dataUpdated(int firstIndex, int numberOfItems) {
  6451. escalator.getBody().refreshRows(firstIndex,
  6452. numberOfItems);
  6453. }
  6454. @Override
  6455. public void dataRemoved(int firstIndex, int numberOfItems) {
  6456. for (int i = 0; i < numberOfItems; ++i) {
  6457. visibleDetails.remove(firstIndex + i);
  6458. }
  6459. escalator.getBody().removeRows(firstIndex,
  6460. numberOfItems);
  6461. Range removed = Range.withLength(firstIndex,
  6462. numberOfItems);
  6463. cellFocusHandler.rowsRemovedFromBody(removed);
  6464. }
  6465. @Override
  6466. public void dataAdded(int firstIndex, int numberOfItems) {
  6467. escalator.getBody().insertRows(firstIndex,
  6468. numberOfItems);
  6469. Range added = Range.withLength(firstIndex,
  6470. numberOfItems);
  6471. cellFocusHandler.rowsAddedToBody(added);
  6472. }
  6473. @Override
  6474. public void dataAvailable(int firstIndex,
  6475. int numberOfItems) {
  6476. currentDataAvailable = Range.withLength(firstIndex,
  6477. numberOfItems);
  6478. if (recalculateColumnWidthsNeeded) {
  6479. // Ensure that cache has actually been populated or
  6480. // all rows removed, otherwise wait for next call.
  6481. if (numberOfItems > 0
  6482. || getDataSource().size() == 0) {
  6483. recalculateColumnWidths();
  6484. recalculateColumnWidthsNeeded = false;
  6485. }
  6486. }
  6487. fireEvent(new DataAvailableEvent(currentDataAvailable));
  6488. }
  6489. @Override
  6490. public void resetDataAndSize(int newSize) {
  6491. // It might take a while for new data to arrive,
  6492. // clear the record of cached rows.
  6493. currentDataAvailable = Range.emptyRange();
  6494. RowContainer body = escalator.getBody();
  6495. int oldSize = body.getRowCount();
  6496. if (newSize > oldSize) {
  6497. if (oldSize == 0 && !isHeaderVisible()) {
  6498. // Fixes framework/issues/11607
  6499. // Need to recalculate column widths when the
  6500. // first row is added to a non-header grid,
  6501. // otherwise the checkbox will be aligned in a
  6502. // wrong place. Wait until the cache has been
  6503. // populated before making the call.
  6504. recalculateColumnWidthsNeeded = true;
  6505. }
  6506. body.insertRows(oldSize, newSize - oldSize);
  6507. cellFocusHandler.rowsAddedToBody(Range
  6508. .withLength(oldSize, newSize - oldSize));
  6509. } else if (newSize < oldSize) {
  6510. body.removeRows(newSize, oldSize - newSize);
  6511. cellFocusHandler.rowsRemovedFromBody(Range
  6512. .withLength(newSize, oldSize - newSize));
  6513. }
  6514. if (newSize > 0) {
  6515. Range visibleRowRange = escalator
  6516. .getVisibleRowRange();
  6517. dataSource.ensureAvailability(
  6518. visibleRowRange.getStart(),
  6519. visibleRowRange.length());
  6520. } else {
  6521. // We won't expect any data more data updates, so
  6522. // just make the bookkeeping happy.
  6523. dataAvailable(0, 0);
  6524. }
  6525. assert body.getRowCount() == newSize;
  6526. }
  6527. });
  6528. int previousRowCount = escalator.getBody().getRowCount();
  6529. if (previousRowCount != 0) {
  6530. escalator.getBody().removeRows(0, previousRowCount);
  6531. }
  6532. setEscalatorSizeFromDataSource();
  6533. }
  6534. private void setEscalatorSizeFromDataSource() {
  6535. assert escalator.getBody().getRowCount() == 0;
  6536. int size = dataSource.size();
  6537. if (size > 0) {
  6538. escalator.getBody().insertRows(0, size);
  6539. }
  6540. }
  6541. /**
  6542. * Gets the {@Link DataSource} for this Grid.
  6543. *
  6544. * @return the data source used by this grid
  6545. */
  6546. public DataSource<T> getDataSource() {
  6547. return dataSource;
  6548. }
  6549. /**
  6550. * Sets the number of frozen columns in this grid. Setting the count to 0
  6551. * means that no data columns will be frozen, but the built-in selection
  6552. * checkbox column will still be frozen if it's in use. Setting the count to
  6553. * -1 will also disable the selection column.
  6554. * <p>
  6555. * The default value is 0.
  6556. *
  6557. * @param numberOfColumns
  6558. * the number of columns that should be frozen
  6559. *
  6560. * @throws IllegalArgumentException
  6561. * if the column count is < -1 or > the number of visible
  6562. * columns
  6563. */
  6564. public void setFrozenColumnCount(int numberOfColumns) {
  6565. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  6566. throw new IllegalArgumentException(
  6567. "count must be between -1 and the current number of columns ("
  6568. + getColumnCount() + ")");
  6569. }
  6570. frozenColumnCount = numberOfColumns;
  6571. updateFrozenColumns();
  6572. }
  6573. private void updateFrozenColumns() {
  6574. int visibleFrozenColumnCount = getVisibleFrozenColumnCount();
  6575. ColumnConfiguration columnConfiguration = escalator
  6576. .getColumnConfiguration();
  6577. if (columnConfiguration.getColumnCount() < visibleFrozenColumnCount) {
  6578. // new columns may not have got added yet, delay and check the
  6579. // correct count again
  6580. Scheduler.get().scheduleFinally(() -> columnConfiguration
  6581. .setFrozenColumnCount(getVisibleFrozenColumnCount()));
  6582. } else {
  6583. columnConfiguration.setFrozenColumnCount(visibleFrozenColumnCount);
  6584. }
  6585. }
  6586. private int getVisibleFrozenColumnCount() {
  6587. int numberOfColumns = getFrozenColumnCount();
  6588. // for the escalator the hidden columns are not in the frozen column
  6589. // count, but for grid they are. thus need to convert the index
  6590. int limit = getFrozenColumnCount();
  6591. if (getSelectionColumn().isPresent()) {
  6592. // If the grid is in MultiSelect mode, getColumn(0) in the following
  6593. // for loop returns the selection column. Accordingly, verifying
  6594. // which frozen columns are visible if the selection column is
  6595. // present should take this fact into account.
  6596. limit++;
  6597. }
  6598. for (int i = 0; i < limit; i++) {
  6599. if (i >= getColumnCount() || getColumn(i).isHidden()) {
  6600. numberOfColumns--;
  6601. }
  6602. }
  6603. if (numberOfColumns == -1) {
  6604. numberOfColumns = 0;
  6605. } else if (selectionColumn != null) {
  6606. numberOfColumns++;
  6607. }
  6608. return numberOfColumns;
  6609. }
  6610. /**
  6611. * Gets the number of frozen columns in this grid. 0 means that no data
  6612. * columns will be frozen, but the built-in selection checkbox column will
  6613. * still be frozen if it's in use. -1 means that not even the selection
  6614. * column is frozen.
  6615. * <p>
  6616. * <em>NOTE:</em> This includes {@link Column#isHidden() hidden columns} in
  6617. * the count.
  6618. *
  6619. * @return the number of frozen columns
  6620. */
  6621. public int getFrozenColumnCount() {
  6622. return frozenColumnCount;
  6623. }
  6624. public HandlerRegistration addRowVisibilityChangeHandler(
  6625. RowVisibilityChangeHandler handler) {
  6626. /*
  6627. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  6628. * concept is too abstract. e.g. the event needs to be re-sent when the
  6629. * widget is resized.
  6630. */
  6631. return escalator.addRowVisibilityChangeHandler(handler);
  6632. }
  6633. /**
  6634. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  6635. * <p>
  6636. * If the details for that row are visible, those will be taken into account
  6637. * as well.
  6638. *
  6639. * @param rowIndex
  6640. * zero-based index of the row to scroll to.
  6641. * @throws IllegalArgumentException
  6642. * if rowIndex is below zero, or above the maximum value
  6643. * supported by the data source.
  6644. */
  6645. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  6646. scrollToRow(rowIndex, ScrollDestination.ANY,
  6647. GridConstants.DEFAULT_PADDING);
  6648. }
  6649. /**
  6650. * Scrolls to a certain row, using user-specified scroll destination.
  6651. * <p>
  6652. * If the details for that row are visible, those will be taken into account
  6653. * as well.
  6654. *
  6655. * @param rowIndex
  6656. * zero-based index of the row to scroll to.
  6657. * @param destination
  6658. * desired destination placement of scrolled-to-row. See
  6659. * {@link ScrollDestination} for more information.
  6660. * @throws IllegalArgumentException
  6661. * if rowIndex is below zero, or above the maximum value
  6662. * supported by the data source.
  6663. */
  6664. public void scrollToRow(int rowIndex, ScrollDestination destination)
  6665. throws IllegalArgumentException {
  6666. scrollToRow(rowIndex, destination,
  6667. destination == ScrollDestination.MIDDLE ? 0
  6668. : GridConstants.DEFAULT_PADDING);
  6669. }
  6670. /**
  6671. * Helper method for making sure desired row is visible and it is properly
  6672. * rendered.
  6673. *
  6674. * @param rowIndex
  6675. * the row to look for
  6676. * @param destination
  6677. * the desired scroll destination
  6678. * @param callback
  6679. * the callback command to execute when row is available
  6680. * @since 8.4
  6681. */
  6682. public void scrollToRow(int rowIndex, ScrollDestination destination,
  6683. Runnable callback) {
  6684. waitUntilVisible(rowIndex, destination, callback);
  6685. }
  6686. /**
  6687. * Helper method for making sure desired row is visible and it is properly
  6688. * rendered.
  6689. *
  6690. * @param rowIndex
  6691. * the row to look for
  6692. * @param whenRendered
  6693. * the callback command to execute when row is available
  6694. * @since 8.4
  6695. */
  6696. public void scrollToRow(int rowIndex, Runnable whenRendered) {
  6697. scrollToRow(rowIndex, ScrollDestination.ANY, whenRendered);
  6698. }
  6699. /**
  6700. * Scrolls to a certain row using only user-specified parameters.
  6701. * <p>
  6702. * If the details for that row are visible, those will be taken into account
  6703. * as well.
  6704. *
  6705. * @param rowIndex
  6706. * zero-based index of the row to scroll to.
  6707. * @param destination
  6708. * desired destination placement of scrolled-to-row. See
  6709. * {@link ScrollDestination} for more information.
  6710. * @param paddingPx
  6711. * number of pixels to overscroll. Behavior depends on
  6712. * destination.
  6713. * @throws IllegalArgumentException
  6714. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6715. * and padding is nonzero, because having a padding on a
  6716. * centered row is undefined behavior, or if rowIndex is below
  6717. * zero or above the row count of the data source.
  6718. */
  6719. private void scrollToRow(int rowIndex, ScrollDestination destination,
  6720. int paddingPx) throws IllegalArgumentException {
  6721. int maxsize = escalator.getBody().getRowCount() - 1;
  6722. if (rowIndex < 0) {
  6723. throw new IllegalArgumentException(
  6724. "Row index (" + rowIndex + ") is below zero!");
  6725. }
  6726. if (rowIndex > maxsize) {
  6727. throw new IllegalArgumentException("Row index (" + rowIndex
  6728. + ") is above maximum (" + maxsize + ")!");
  6729. }
  6730. escalator.scrollToRowAndSpacer(rowIndex, destination, paddingPx);
  6731. }
  6732. /**
  6733. * Helper method for scrolling and making sure row is visible.
  6734. *
  6735. * @param rowIndex
  6736. * the row index to make visible
  6737. * @param destination
  6738. * the desired scroll destination
  6739. * @param whenVisible
  6740. * the callback method to call when row is visible
  6741. */
  6742. private void waitUntilVisible(int rowIndex, ScrollDestination destination,
  6743. Runnable whenVisible) {
  6744. boolean waitForCache = false;
  6745. if (getDataSource().getRow(rowIndex) == null) {
  6746. // not yet in cache, wait for this to change
  6747. waitForCache = true;
  6748. Reference<Registration> registration = new Reference<>();
  6749. registration.set(getDataSource()
  6750. .addDataChangeHandler(new DataChangeHandler() {
  6751. @Override
  6752. public void resetDataAndSize(int estimatedNewDataSize) {
  6753. // data set changed, cancel the operation
  6754. registration.get().remove();
  6755. }
  6756. @Override
  6757. public void dataUpdated(int firstRowIndex,
  6758. int numberOfRows) {
  6759. // NOP
  6760. }
  6761. @Override
  6762. public void dataRemoved(int firstRowIndex,
  6763. int numberOfRows) {
  6764. // data set changed, cancel the operation
  6765. registration.get().remove();
  6766. }
  6767. @Override
  6768. public void dataAvailable(int firstRowIndex,
  6769. int numberOfRows) {
  6770. // if new available range contains the row,
  6771. // try again
  6772. if (Range.withLength(firstRowIndex, numberOfRows)
  6773. .contains(rowIndex)) {
  6774. registration.get().remove();
  6775. waitUntilVisible(rowIndex, destination,
  6776. whenVisible);
  6777. }
  6778. }
  6779. @Override
  6780. public void dataAdded(int firstRowIndex,
  6781. int numberOfRows) {
  6782. // data set changed, cancel the operation
  6783. registration.get().remove();
  6784. }
  6785. }));
  6786. }
  6787. scrollToRow(rowIndex, destination);
  6788. if (!waitForCache) {
  6789. // all necessary adjustments done, time to perform
  6790. whenVisible.run();
  6791. }
  6792. }
  6793. /**
  6794. * Scrolls to the beginning of the very first row.
  6795. */
  6796. public void scrollToStart() {
  6797. if (getEscalator().getBody().getRowCount() > 0) {
  6798. scrollToRow(0, ScrollDestination.START);
  6799. }
  6800. }
  6801. /**
  6802. * Scrolls to the end of the very last row.
  6803. */
  6804. public void scrollToEnd() {
  6805. if (getEscalator().getBody().getRowCount() > 0) {
  6806. scrollToRow(escalator.getBody().getRowCount() - 1,
  6807. ScrollDestination.END);
  6808. }
  6809. }
  6810. /**
  6811. * Sets the vertical scroll offset.
  6812. *
  6813. * @param px
  6814. * the number of pixels this grid should be scrolled down
  6815. */
  6816. public void setScrollTop(double px) {
  6817. escalator.setScrollTop(px);
  6818. }
  6819. /**
  6820. * Gets the vertical scroll offset.
  6821. *
  6822. * @return the number of pixels this grid is scrolled down
  6823. */
  6824. public double getScrollTop() {
  6825. return escalator.getScrollTop();
  6826. }
  6827. /**
  6828. * Sets the horizontal scroll offset.
  6829. *
  6830. * @since 7.5.0
  6831. * @param px
  6832. * the number of pixels this grid should be scrolled right
  6833. */
  6834. public void setScrollLeft(double px) {
  6835. escalator.setScrollLeft(px);
  6836. }
  6837. /**
  6838. * Gets the horizontal scroll offset.
  6839. *
  6840. * @return the number of pixels this grid is scrolled to the right
  6841. */
  6842. public double getScrollLeft() {
  6843. return escalator.getScrollLeft();
  6844. }
  6845. /**
  6846. * Returns the height of the scrollable area in pixels.
  6847. *
  6848. * @since 7.5.0
  6849. * @return the height of the scrollable area in pixels
  6850. */
  6851. public double getScrollHeight() {
  6852. return escalator.getScrollHeight();
  6853. }
  6854. /**
  6855. * Returns the width of the scrollable area in pixels.
  6856. *
  6857. * @since 7.5.0
  6858. * @return the width of the scrollable area in pixels.
  6859. */
  6860. public double getScrollWidth() {
  6861. return escalator.getScrollWidth();
  6862. }
  6863. private static final Logger getLogger() {
  6864. return Logger.getLogger(Grid.class.getName());
  6865. }
  6866. /**
  6867. * Sets the number of rows that should be visible in Grid's body, while
  6868. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6869. * <p>
  6870. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  6871. * remembered, and applied once the mode is applied.
  6872. *
  6873. * @param rows
  6874. * The height in terms of number of rows displayed in Grid's
  6875. * body. If Grid doesn't contain enough rows, white space is
  6876. * displayed instead.
  6877. * @throws IllegalArgumentException
  6878. * if {@code rows} is zero or less
  6879. * @throws IllegalArgumentException
  6880. * if {@code rows} is {@link Double#isInifinite(double)
  6881. * infinite}
  6882. * @throws IllegalArgumentException
  6883. * if {@code rows} is {@link Double#isNaN(double) NaN}
  6884. *
  6885. * @see #setHeightMode(HeightMode)
  6886. */
  6887. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6888. escalator.setHeightByRows(rows);
  6889. }
  6890. /**
  6891. * Gets the amount of rows in Grid's body that are shown, while
  6892. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6893. * <p>
  6894. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  6895. *
  6896. * @return the amount of rows that should be shown in Grid's body, while in
  6897. * {@link HeightMode#ROW}.
  6898. * @see #setHeightByRows(double)
  6899. */
  6900. public double getHeightByRows() {
  6901. return escalator.getHeightByRows();
  6902. }
  6903. /**
  6904. * Defines the mode in which the Grid widget's height is calculated.
  6905. * <p>
  6906. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  6907. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  6908. * <p>
  6909. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  6910. * will display as many rows as {@link #getHeightByRows()} defines.
  6911. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  6912. * will resize itself to still display the required amount of rows in its
  6913. * body. It also takes the horizontal scrollbar into account.
  6914. *
  6915. * @param heightMode
  6916. * the mode in to which Grid should be set
  6917. */
  6918. public void setHeightMode(HeightMode heightMode) {
  6919. /*
  6920. * This method is a workaround for the fact that Vaadin re-applies
  6921. * widget dimensions (height/width) on each state change event. The
  6922. * original design was to have setHeight an setHeightByRow be equals,
  6923. * and whichever was called the latest was considered in effect.
  6924. *
  6925. * But, because of Vaadin always calling setHeight on the widget, this
  6926. * approach doesn't work.
  6927. */
  6928. escalator.setHeightMode(heightMode);
  6929. }
  6930. /**
  6931. * Returns the current {@link HeightMode} the Grid is in.
  6932. * <p>
  6933. * Defaults to {@link HeightMode#CSS}.
  6934. *
  6935. * @return the current HeightMode
  6936. */
  6937. public HeightMode getHeightMode() {
  6938. return escalator.getHeightMode();
  6939. }
  6940. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  6941. Set<String> events = new HashSet<>();
  6942. if (renderer instanceof ComplexRenderer) {
  6943. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  6944. .getConsumedEvents();
  6945. if (consumedEvents != null) {
  6946. events.addAll(consumedEvents);
  6947. }
  6948. }
  6949. return events;
  6950. }
  6951. @Override
  6952. public void onBrowserEvent(Event event) {
  6953. if (!isEnabled()) {
  6954. return;
  6955. }
  6956. String eventType = event.getType();
  6957. if (eventType.equals(BrowserEvents.FOCUS)
  6958. || eventType.equals(BrowserEvents.BLUR)) {
  6959. super.onBrowserEvent(event);
  6960. return;
  6961. }
  6962. EventTarget target = event.getEventTarget();
  6963. if (!Element.is(target) || isOrContainsInSpacer(Element.as(target))) {
  6964. return;
  6965. }
  6966. Element element = Element.as(target);
  6967. RowContainer container = escalator.findRowContainer(element);
  6968. Cell cell;
  6969. if (container == null) {
  6970. if (eventType.equals(BrowserEvents.KEYDOWN)
  6971. || eventType.equals(BrowserEvents.KEYUP)
  6972. || eventType.equals(BrowserEvents.KEYPRESS)) {
  6973. cell = cellFocusHandler.getFocusedCell();
  6974. container = cellFocusHandler.containerWithFocus;
  6975. } else {
  6976. // Click might be in an editor cell, should still map.
  6977. if (editor.editorOverlay != null
  6978. && editor.editorOverlay.isOrHasChild(element)) {
  6979. container = escalator.getBody();
  6980. int rowIndex = editor.getRow();
  6981. int colIndex = editor.getElementColumn(element);
  6982. if (colIndex < 0) {
  6983. // Click in editor, but not for any column.
  6984. return;
  6985. }
  6986. try {
  6987. TableCellElement cellElement = container
  6988. .getRowElement(rowIndex).getCells()
  6989. .getItem(colIndex);
  6990. cell = new Cell(rowIndex, colIndex, cellElement);
  6991. } catch (IllegalStateException exception) {
  6992. // IllegalStateException may occur if user has scrolled Grid so
  6993. // that Escalator has updated, and row under Editor is no longer
  6994. // there
  6995. return;
  6996. }
  6997. } else {
  6998. if (escalator.getElement().isOrHasChild(element)) {
  6999. eventCell.set(new Cell(-1, -1, null), Section.BODY);
  7000. // Fire native events.
  7001. super.onBrowserEvent(event);
  7002. }
  7003. return;
  7004. }
  7005. }
  7006. } else {
  7007. cell = container.getCell(element);
  7008. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  7009. cellOnPrevMouseDown = cell;
  7010. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  7011. /*
  7012. * Chrome has an interesting idea on click targets (see
  7013. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  7014. * the mousedown target as the click target.
  7015. */
  7016. cell = cellOnPrevMouseDown;
  7017. }
  7018. }
  7019. if (cell == null) {
  7020. getLogger().log(Level.WARNING,
  7021. "received " + eventType + "-event with a null cell target");
  7022. return;
  7023. }
  7024. eventCell.set(cell, getSectionFromContainer(container));
  7025. GridEvent<T> gridEvent = new GridEvent<>(event, eventCell);
  7026. for (GridEventHandler<T> handler : browserEventHandlers) {
  7027. handler.onEvent(gridEvent);
  7028. }
  7029. }
  7030. private Section getSectionFromContainer(RowContainer container) {
  7031. assert container != null : "RowContainer should not be null";
  7032. if (container == escalator.getBody()) {
  7033. return Section.BODY;
  7034. } else if (container == escalator.getFooter()) {
  7035. return Section.FOOTER;
  7036. } else if (container == escalator.getHeader()) {
  7037. return Section.HEADER;
  7038. }
  7039. assert false : "RowContainer was not header, footer or body.";
  7040. return null;
  7041. }
  7042. private boolean isOrContainsInSpacer(Node node) {
  7043. Node n = node;
  7044. while (n != null && n != getElement()) {
  7045. boolean isElement = Element.is(n);
  7046. if (isElement) {
  7047. String className = Element.as(n).getClassName();
  7048. // Also check whether className is indeed a string. For
  7049. // SVGElement it may be of type SVGAnimatedString.
  7050. // https://developer.mozilla.org/en-US/docs/Web/API/Element/className#Notes
  7051. if (WidgetUtil.isString(className) && className
  7052. .contains(getStylePrimaryName() + "-spacer")) {
  7053. return true;
  7054. }
  7055. }
  7056. n = n.getParentNode();
  7057. }
  7058. return false;
  7059. }
  7060. private boolean isElementInChildWidget(Element e) {
  7061. Widget w = WidgetUtil.findWidget(e);
  7062. if (w == this) {
  7063. return false;
  7064. }
  7065. /*
  7066. * If e is directly inside this grid, but the grid is wrapped in a
  7067. * Composite, findWidget is not going to find this, only the wrapper.
  7068. * Thus we need to check its parents to see if we encounter this; if we
  7069. * don't, the found widget is actually a parent of this, so we should
  7070. * return false.
  7071. */
  7072. while (w != null && w != this) {
  7073. w = w.getParent();
  7074. }
  7075. return w != null;
  7076. }
  7077. private class EditorEventHandler implements GridEventHandler<T> {
  7078. @Override
  7079. public void onEvent(GridEvent<T> event) {
  7080. if (!isEditorEnabled()) {
  7081. return;
  7082. }
  7083. Widget widget;
  7084. if (editor.focusedColumnIndexDOM < 0) {
  7085. widget = null;
  7086. } else {
  7087. widget = editor.getWidget(
  7088. getVisibleColumn(editor.focusedColumnIndexDOM));
  7089. }
  7090. EditorDomEvent<T> editorEvent = new EditorDomEvent<>(
  7091. event.getDomEvent(), event.getCell(), widget);
  7092. event.setHandled(
  7093. getEditor().getEventHandler().handleEvent(editorEvent));
  7094. }
  7095. };
  7096. private class SuperEventHandler implements GridEventHandler<T> {
  7097. @Override
  7098. public void onEvent(GridEvent<T> event) {
  7099. if (event.isHandled()) {
  7100. return;
  7101. }
  7102. Grid.super.onBrowserEvent(event.getDomEvent());
  7103. }
  7104. };
  7105. private abstract class AbstractGridEventHandler
  7106. implements GridEventHandler<T> {
  7107. @Override
  7108. public void onEvent(GridEvent<T> event) {
  7109. if (event.isHandled()) {
  7110. return;
  7111. }
  7112. event.setHandled(isElementInChildWidget(
  7113. Element.as(event.getDomEvent().getEventTarget())));
  7114. }
  7115. };
  7116. private class RendererEventHandler extends AbstractGridEventHandler {
  7117. @Override
  7118. public void onEvent(GridEvent<T> event) {
  7119. super.onEvent(event);
  7120. if (event.isHandled()) {
  7121. return;
  7122. }
  7123. if (!event.getCell().isBody()) {
  7124. return;
  7125. }
  7126. Column<?, T> gridColumn = event.getCell().getColumn();
  7127. boolean enterKey = event.getDomEvent().getType()
  7128. .equals(BrowserEvents.KEYDOWN)
  7129. && event.getDomEvent().getKeyCode() == KeyCodes.KEY_ENTER;
  7130. boolean doubleClick = event.getDomEvent().getType()
  7131. .equals(BrowserEvents.DBLCLICK);
  7132. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  7133. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  7134. .getRenderer();
  7135. if (cplxRenderer.getConsumedEvents()
  7136. .contains(event.getDomEvent().getType())) {
  7137. if (cplxRenderer.onBrowserEvent(event.getCell(),
  7138. event.getDomEvent())) {
  7139. event.setHandled(true);
  7140. }
  7141. }
  7142. // Calls onActivate if KeyDown and Enter or double click
  7143. if ((enterKey || doubleClick)
  7144. && cplxRenderer.onActivate(event.getCell())) {
  7145. event.setHandled(true);
  7146. }
  7147. }
  7148. }
  7149. };
  7150. private class CellFocusEventHandler extends AbstractGridEventHandler {
  7151. @Override
  7152. public void onEvent(GridEvent<T> event) {
  7153. super.onEvent(event);
  7154. if (event.isHandled()) {
  7155. return;
  7156. }
  7157. Collection<String> navigation = cellFocusHandler
  7158. .getNavigationEvents();
  7159. if (navigation.contains(event.getDomEvent().getType())) {
  7160. cellFocusHandler.handleNavigationEvent(event.getDomEvent(),
  7161. event.getCell());
  7162. }
  7163. }
  7164. };
  7165. private class HeaderCellDragStartHandler extends AbstractGridEventHandler {
  7166. @Override
  7167. public void onEvent(GridEvent<T> event) {
  7168. super.onEvent(event);
  7169. if (event.isHandled()) {
  7170. return;
  7171. }
  7172. if (!isColumnReorderingAllowed()) {
  7173. return;
  7174. }
  7175. if (!event.getCell().isHeader()) {
  7176. return;
  7177. }
  7178. int offset = 0; // apply offset depending on selection column, see
  7179. // #10546
  7180. if (getSelectionColumn().isPresent()) {
  7181. offset = -1;
  7182. }
  7183. if (event.getCell().getColumnIndex()
  7184. + offset < getFrozenColumnCount()) {
  7185. return;
  7186. }
  7187. if (event.getDomEvent().getTypeInt() == Event.ONMOUSEDOWN
  7188. && event.getDomEvent()
  7189. .getButton() == NativeEvent.BUTTON_LEFT
  7190. || event.getDomEvent().getTypeInt() == Event.ONTOUCHSTART) {
  7191. dndHandler.onDragStartOnDraggableElement(event.getDomEvent(),
  7192. headerCellDndCallback);
  7193. event.getDomEvent().preventDefault();
  7194. event.getDomEvent().stopPropagation();
  7195. // fixes https://github.com/vaadin/framework/issues/8632
  7196. // don't mark the event as handled, in order for the next
  7197. // handler in the handler chain (HeaderDefaultRowEventHandler)
  7198. // to be able to receive it. This should be safe since the next
  7199. // handlers in the chain (RendererEventHandler and
  7200. // CellFocusEventHandler) do not react to header touches/clicks.
  7201. // event.setHandled(true);
  7202. }
  7203. }
  7204. };
  7205. private class HeaderDefaultRowEventHandler
  7206. extends AbstractGridEventHandler {
  7207. private Point rowEventTouchStartingPoint;
  7208. @Override
  7209. public void onEvent(GridEvent<T> event) {
  7210. super.onEvent(event);
  7211. if (event.isHandled()) {
  7212. return;
  7213. }
  7214. if (!event.getCell().isHeader()) {
  7215. return;
  7216. }
  7217. if (!getHeader().getRow(event.getCell().getRowIndex())
  7218. .isDefault()) {
  7219. return;
  7220. }
  7221. if (!event.getCell().getColumn().isSortable()) {
  7222. // Only handle sorting events if the column is sortable
  7223. return;
  7224. }
  7225. if (BrowserEvents.MOUSEDOWN.equals(event.getDomEvent().getType())
  7226. && event.getDomEvent().getShiftKey()) {
  7227. // Don't select text when shift clicking on a header.
  7228. event.getDomEvent().preventDefault();
  7229. }
  7230. if (BrowserEvents.TOUCHSTART
  7231. .equals(event.getDomEvent().getType())) {
  7232. if (event.getDomEvent().getTouches().length() > 1) {
  7233. return;
  7234. }
  7235. event.getDomEvent().preventDefault();
  7236. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  7237. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  7238. touch.getClientY());
  7239. sorter.awaitForTouchEnd(GridConstants.LONG_TAP_DELAY);
  7240. event.setHandled(true);
  7241. } else if (BrowserEvents.TOUCHMOVE
  7242. .equals(event.getDomEvent().getType())) {
  7243. if (event.getDomEvent().getTouches().length() > 1) {
  7244. return;
  7245. }
  7246. if (rowEventTouchStartingPoint == null) {
  7247. return;
  7248. }
  7249. event.getDomEvent().preventDefault();
  7250. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  7251. double diffX = Math.abs(
  7252. touch.getClientX() - rowEventTouchStartingPoint.getX());
  7253. double diffY = Math.abs(
  7254. touch.getClientY() - rowEventTouchStartingPoint.getY());
  7255. // Cancel long tap if finger strays too far from
  7256. // starting point
  7257. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  7258. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  7259. sorter.cancelAwaitForTouchEnd();
  7260. }
  7261. event.setHandled(true);
  7262. } else if (BrowserEvents.TOUCHEND
  7263. .equals(event.getDomEvent().getType())) {
  7264. if (event.getDomEvent().getTouches().length() > 1) {
  7265. return;
  7266. }
  7267. if (rowEventTouchStartingPoint == null) {
  7268. return;
  7269. }
  7270. sorter.onTouchEnd();
  7271. event.setHandled(true);
  7272. } else if (BrowserEvents.TOUCHCANCEL
  7273. .equals(event.getDomEvent().getType())) {
  7274. if (event.getDomEvent().getTouches().length() > 1) {
  7275. return;
  7276. }
  7277. sorter.cancelAwaitForTouchEnd();
  7278. event.setHandled(true);
  7279. } else if (BrowserEvents.CLICK
  7280. .equals(event.getDomEvent().getType())) {
  7281. sorter.sort(event.getCell().getColumn(),
  7282. event.getDomEvent().getShiftKey());
  7283. }
  7284. }
  7285. };
  7286. @Override
  7287. @SuppressWarnings("deprecation")
  7288. public com.google.gwt.user.client.Element getSubPartElement(
  7289. String subPart) {
  7290. /*
  7291. * handles details[] (translated to spacer[] for Escalator), cell[],
  7292. * header[] and footer[]
  7293. */
  7294. // "#header[0][0]/DRAGhANDLE"
  7295. Element escalatorElement = escalator.getSubPartElement(
  7296. subPart.replaceFirst("^details\\[", "spacer["));
  7297. if (escalatorElement != null) {
  7298. int detailIdx = subPart.indexOf("/");
  7299. if (detailIdx > 0) {
  7300. String detail = subPart.substring(detailIdx + 1);
  7301. getLogger().severe("Looking up detail from index " + detailIdx
  7302. + " onward: \"" + detail + "\"");
  7303. if (detail.equalsIgnoreCase("content")) {
  7304. // XXX: Fix this to look up by class name!
  7305. return DOM.asOld(Element.as(escalatorElement.getChild(0)));
  7306. }
  7307. if (detail.equalsIgnoreCase("draghandle")) {
  7308. // XXX: Fix this to look up by class name!
  7309. return DOM.asOld(Element.as(escalatorElement.getChild(1)));
  7310. }
  7311. }
  7312. return DOM.asOld(escalatorElement);
  7313. }
  7314. SubPartArguments args = SubPartArguments.create(subPart);
  7315. Element editor = getSubPartElementEditor(args);
  7316. if (editor != null) {
  7317. return DOM.asOld(editor);
  7318. }
  7319. return null;
  7320. }
  7321. private Element getSubPartElementEditor(SubPartArguments args) {
  7322. if (!args.getType().equalsIgnoreCase("editor")
  7323. || editor.getState() != State.ACTIVE) {
  7324. return null;
  7325. }
  7326. if (args.getIndicesLength() == 0) {
  7327. return editor.editorOverlay;
  7328. } else if (args.getIndicesLength() == 1) {
  7329. int index = args.getIndex(0);
  7330. if (index >= columns.size()) {
  7331. return null;
  7332. }
  7333. escalator.scrollToColumn(index, ScrollDestination.ANY, 0);
  7334. Widget widget = editor.getWidget(columns.get(index));
  7335. if (widget != null) {
  7336. return widget.getElement();
  7337. }
  7338. // No widget for the column.
  7339. return null;
  7340. }
  7341. return null;
  7342. }
  7343. @Override
  7344. @SuppressWarnings("deprecation")
  7345. public String getSubPartName(
  7346. com.google.gwt.user.client.Element subElement) {
  7347. String escalatorStructureName = escalator.getSubPartName(subElement);
  7348. if (escalatorStructureName != null) {
  7349. return escalatorStructureName.replaceFirst("^spacer", "details");
  7350. }
  7351. String editorName = getSubPartNameEditor(subElement);
  7352. if (editorName != null) {
  7353. return editorName;
  7354. }
  7355. return null;
  7356. }
  7357. private String getSubPartNameEditor(Element subElement) {
  7358. if (editor.getState() != State.ACTIVE
  7359. || !editor.editorOverlay.isOrHasChild(subElement)) {
  7360. return null;
  7361. }
  7362. int i = 0;
  7363. for (Column<?, T> column : columns) {
  7364. if (editor.getWidget(column).getElement()
  7365. .isOrHasChild(subElement)) {
  7366. return "editor[" + i + "]";
  7367. }
  7368. ++i;
  7369. }
  7370. return "editor";
  7371. }
  7372. private void setSelectColumnRenderer(
  7373. final Renderer<Boolean> selectColumnRenderer) {
  7374. if (this.selectColumnRenderer == selectColumnRenderer) {
  7375. return;
  7376. }
  7377. if (this.selectColumnRenderer != null) {
  7378. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  7379. // End of Life for the old selection column renderer.
  7380. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  7381. }
  7382. // Clear field so frozen column logic in the remove method knows
  7383. // what to do
  7384. Column<?, T> colToRemove = selectionColumn;
  7385. selectionColumn = null;
  7386. removeColumnSkipSelectionColumnCheck(colToRemove);
  7387. cellFocusHandler.offsetRangeBy(-1);
  7388. }
  7389. this.selectColumnRenderer = selectColumnRenderer;
  7390. if (selectColumnRenderer != null) {
  7391. cellFocusHandler.offsetRangeBy(1);
  7392. selectionColumn = new SelectionColumn(selectColumnRenderer);
  7393. addColumnsSkipSelectionColumnCheck(
  7394. Collections.singleton(selectionColumn), 0);
  7395. selectionColumn.initDone();
  7396. } else {
  7397. selectionColumn = null;
  7398. requestRefreshBody();
  7399. }
  7400. updateFrozenColumns();
  7401. }
  7402. /**
  7403. * Sets the current selection model.
  7404. *
  7405. * @param selectionModel
  7406. * a selection model implementation.
  7407. * @throws IllegalArgumentException
  7408. * if selection model argument is null
  7409. */
  7410. public void setSelectionModel(SelectionModel<T> selectionModel) {
  7411. if (selectionModel == null) {
  7412. throw new IllegalArgumentException("Selection model can't be null");
  7413. }
  7414. this.selectionModel = selectionModel;
  7415. if (selectionModel instanceof SelectionModelWithSelectionColumn) {
  7416. setSelectColumnRenderer(
  7417. ((SelectionModelWithSelectionColumn) selectionModel)
  7418. .getRenderer());
  7419. } else {
  7420. setSelectColumnRenderer(null);
  7421. }
  7422. if (this.selectionModel.isMultiSelectionAllowed()) {
  7423. escalator.getTable().setAttribute("aria-multiselectable", "true");
  7424. } else if (this.selectionModel.isSelectionAllowed()) {
  7425. escalator.getTable().setAttribute("aria-multiselectable", "false");
  7426. } else {
  7427. escalator.getTable().removeAttribute("aria-multiselectable");
  7428. }
  7429. // Refresh rendered rows to update selection, if it has changed
  7430. requestRefreshBody();
  7431. }
  7432. /**
  7433. * Gets a reference to the current selection model.
  7434. *
  7435. * @return the currently used SelectionModel instance.
  7436. */
  7437. public SelectionModel<T> getSelectionModel() {
  7438. return selectionModel;
  7439. }
  7440. /**
  7441. * Returns if a row is selected.
  7442. *
  7443. * @param row
  7444. * a row object
  7445. * @return {@code true}, if the current selection model considers the
  7446. * provided row object selected.
  7447. */
  7448. public boolean isSelected(T row) {
  7449. return selectionModel.isSelected(row);
  7450. }
  7451. /**
  7452. * Selects a row using the current selection model.
  7453. * <p>
  7454. * Only selection models implementing {@link SelectionModel.Single} and
  7455. * {@link SelectionModel.Multi} are supported; for anything else, an
  7456. * exception will be thrown.
  7457. *
  7458. * @param row
  7459. * a row object
  7460. * @throws IllegalStateException
  7461. * if the current selection model is not an instance of
  7462. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7463. */
  7464. public void select(T row) {
  7465. if (getSelectionModel().isSelectionAllowed()) {
  7466. getSelectionModel().select(row);
  7467. }
  7468. }
  7469. /**
  7470. * Deselects a row using the current selection model.
  7471. * <p>
  7472. * Only selection models implementing {@link SelectionModel.Single} and
  7473. * {@link SelectionModel.Multi} are supported; for anything else, an
  7474. * exception will be thrown.
  7475. *
  7476. * @param row
  7477. * a row object
  7478. * @throws IllegalStateException
  7479. * if the current selection model is not an instance of
  7480. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7481. */
  7482. public void deselect(T row) {
  7483. if (getSelectionModel().isSelectionAllowed()) {
  7484. getSelectionModel().deselect(row);
  7485. }
  7486. }
  7487. /**
  7488. * Deselects all rows using the current selection model.
  7489. *
  7490. * @throws IllegalStateException
  7491. * if the current selection model is not an instance of
  7492. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7493. */
  7494. public void deselectAll() {
  7495. getSelectionModel().deselectAll();
  7496. }
  7497. @Override
  7498. public HandlerRegistration addSelectionHandler(
  7499. final SelectionHandler<T> handler) {
  7500. return addHandler(handler, SelectionEvent.getType());
  7501. }
  7502. /**
  7503. * Sets the current sort order using the fluid Sort API. Read the
  7504. * documentation for {@link Sort} for more information.
  7505. *
  7506. * @param s
  7507. * a sort instance
  7508. */
  7509. public void sort(Sort s) {
  7510. setSortOrder(s.build());
  7511. }
  7512. /**
  7513. * Sorts the Grid data in ascending order along one column.
  7514. *
  7515. * @param column
  7516. * a grid column reference
  7517. */
  7518. public <C> void sort(Column<C, T> column) {
  7519. sort(column, SortDirection.ASCENDING);
  7520. }
  7521. /**
  7522. * Sorts the Grid data along one column.
  7523. *
  7524. * @param column
  7525. * a grid column reference
  7526. * @param direction
  7527. * a sort direction value
  7528. */
  7529. public <C> void sort(Column<C, T> column, SortDirection direction) {
  7530. sort(Sort.by(column, direction));
  7531. }
  7532. /**
  7533. * Sets the sort order to use. Setting this causes the Grid to re-sort
  7534. * itself.
  7535. *
  7536. * @param order
  7537. * a sort order list. If set to null, the sort order is cleared.
  7538. */
  7539. public void setSortOrder(List<SortOrder> order) {
  7540. setSortOrder(order, false);
  7541. }
  7542. /**
  7543. * Clears the sort order and indicators without re-sorting.
  7544. */
  7545. private void clearSortOrder() {
  7546. sortOrder.clear();
  7547. refreshHeader();
  7548. }
  7549. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  7550. if (order != sortOrder) {
  7551. sortOrder.clear();
  7552. if (order != null) {
  7553. sortOrder.addAll(order);
  7554. }
  7555. }
  7556. sort(userOriginated);
  7557. }
  7558. /**
  7559. * Get a copy of the current sort order array.
  7560. *
  7561. * @return a copy of the current sort order array
  7562. */
  7563. public List<SortOrder> getSortOrder() {
  7564. return Collections.unmodifiableList(sortOrder);
  7565. }
  7566. /**
  7567. * Finds the sorting order for this column
  7568. */
  7569. private SortOrder getSortOrder(Column<?, ?> column) {
  7570. for (SortOrder order : getSortOrder()) {
  7571. if (order.getColumn() == column) {
  7572. return order;
  7573. }
  7574. }
  7575. return null;
  7576. }
  7577. /**
  7578. * Register a GWT event handler for a sorting event. This handler gets
  7579. * called whenever this Grid needs its data source to provide data sorted in
  7580. * a specific order.
  7581. *
  7582. * @param handler
  7583. * a sort event handler
  7584. * @return the registration for the event
  7585. */
  7586. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  7587. return addHandler(handler, SortEvent.getType());
  7588. }
  7589. /**
  7590. * Register a GWT event handler for a select all event. This handler gets
  7591. * called whenever Grid needs all rows selected.
  7592. * <p>
  7593. * In case the select all checkbox is not visible in the
  7594. * {@link SelectionColumn}, it will be come visible after adding the
  7595. * handler.
  7596. *
  7597. * @param handler
  7598. * a select all event handler
  7599. * @return the registration for the event
  7600. */
  7601. public HandlerRegistration addSelectAllHandler(
  7602. SelectAllHandler<T> handler) {
  7603. HandlerRegistration registration = addHandler(handler,
  7604. SelectAllEvent.getType());
  7605. return registration;
  7606. }
  7607. /**
  7608. * Register a GWT event handler for a data available event. This handler
  7609. * gets called whenever the {@link DataSource} for this Grid has new data
  7610. * available.
  7611. * <p>
  7612. * This handle will be fired with the current available data after
  7613. * registration is done.
  7614. *
  7615. * @param handler
  7616. * a data available event handler
  7617. * @return the registration for the event
  7618. */
  7619. public HandlerRegistration addDataAvailableHandler(
  7620. final DataAvailableHandler handler) {
  7621. // Deferred call to handler with current row range
  7622. Scheduler.get().scheduleFinally(() -> {
  7623. if (!dataSource.isWaitingForData()) {
  7624. handler.onDataAvailable(
  7625. new DataAvailableEvent(currentDataAvailable));
  7626. }
  7627. });
  7628. return addHandler(handler, DataAvailableEvent.TYPE);
  7629. }
  7630. /**
  7631. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  7632. * fired when a KeyDown event occurs while cell focus is in the Body of this
  7633. * Grid.
  7634. *
  7635. * @param handler
  7636. * the key handler to register
  7637. * @return the registration for the event
  7638. */
  7639. public HandlerRegistration addBodyKeyDownHandler(
  7640. BodyKeyDownHandler handler) {
  7641. return addHandler(handler, GridKeyDownEvent.TYPE);
  7642. }
  7643. /**
  7644. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  7645. * fired when a KeyUp event occurs while cell focus is in the Body of this
  7646. * Grid.
  7647. *
  7648. * @param handler
  7649. * the key handler to register
  7650. * @return the registration for the event
  7651. */
  7652. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  7653. return addHandler(handler, GridKeyUpEvent.TYPE);
  7654. }
  7655. /**
  7656. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  7657. * is fired when a KeyPress event occurs while cell focus is in the Body of
  7658. * this Grid.
  7659. *
  7660. * @param handler
  7661. * the key handler to register
  7662. * @return the registration for the event
  7663. */
  7664. public HandlerRegistration addBodyKeyPressHandler(
  7665. BodyKeyPressHandler handler) {
  7666. return addHandler(handler, GridKeyPressEvent.TYPE);
  7667. }
  7668. /**
  7669. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  7670. * is fired when a KeyDown event occurs while cell focus is in the Header of
  7671. * this Grid.
  7672. *
  7673. * @param handler
  7674. * the key handler to register
  7675. * @return the registration for the event
  7676. */
  7677. public HandlerRegistration addHeaderKeyDownHandler(
  7678. HeaderKeyDownHandler handler) {
  7679. return addHandler(handler, GridKeyDownEvent.TYPE);
  7680. }
  7681. /**
  7682. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  7683. * fired when a KeyUp event occurs while cell focus is in the Header of this
  7684. * Grid.
  7685. *
  7686. * @param handler
  7687. * the key handler to register
  7688. * @return the registration for the event
  7689. */
  7690. public HandlerRegistration addHeaderKeyUpHandler(
  7691. HeaderKeyUpHandler handler) {
  7692. return addHandler(handler, GridKeyUpEvent.TYPE);
  7693. }
  7694. /**
  7695. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  7696. * is fired when a KeyPress event occurs while cell focus is in the Header
  7697. * of this Grid.
  7698. *
  7699. * @param handler
  7700. * the key handler to register
  7701. * @return the registration for the event
  7702. */
  7703. public HandlerRegistration addHeaderKeyPressHandler(
  7704. HeaderKeyPressHandler handler) {
  7705. return addHandler(handler, GridKeyPressEvent.TYPE);
  7706. }
  7707. /**
  7708. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  7709. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  7710. * this Grid.
  7711. *
  7712. * @param handler
  7713. * the key handler to register
  7714. * @return the registration for the event
  7715. */
  7716. public HandlerRegistration addFooterKeyDownHandler(
  7717. FooterKeyDownHandler handler) {
  7718. return addHandler(handler, GridKeyDownEvent.TYPE);
  7719. }
  7720. /**
  7721. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  7722. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  7723. * Grid.
  7724. *
  7725. * @param handler
  7726. * the key handler to register
  7727. * @return the registration for the event
  7728. */
  7729. public HandlerRegistration addFooterKeyUpHandler(
  7730. FooterKeyUpHandler handler) {
  7731. return addHandler(handler, GridKeyUpEvent.TYPE);
  7732. }
  7733. /**
  7734. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  7735. * is fired when a KeyPress event occurs while cell focus is in the Footer
  7736. * of this Grid.
  7737. *
  7738. * @param handler
  7739. * the key handler to register
  7740. * @return the registration for the event
  7741. */
  7742. public HandlerRegistration addFooterKeyPressHandler(
  7743. FooterKeyPressHandler handler) {
  7744. return addHandler(handler, GridKeyPressEvent.TYPE);
  7745. }
  7746. /**
  7747. * Register a BodyClickHandler to this Grid. The event for this handler is
  7748. * fired when a Click event occurs in the Body of this Grid.
  7749. *
  7750. * @param handler
  7751. * the click handler to register
  7752. * @return the registration for the event
  7753. */
  7754. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  7755. return addHandler(handler, GridClickEvent.TYPE);
  7756. }
  7757. /**
  7758. * Register a HeaderClickHandler to this Grid. The event for this handler is
  7759. * fired when a Click event occurs in the Header of this Grid.
  7760. *
  7761. * @param handler
  7762. * the click handler to register
  7763. * @return the registration for the event
  7764. */
  7765. public HandlerRegistration addHeaderClickHandler(
  7766. HeaderClickHandler handler) {
  7767. return addHandler(handler, GridClickEvent.TYPE);
  7768. }
  7769. /**
  7770. * Register a FooterClickHandler to this Grid. The event for this handler is
  7771. * fired when a Click event occurs in the Footer of this Grid.
  7772. *
  7773. * @param handler
  7774. * the click handler to register
  7775. * @return the registration for the event
  7776. */
  7777. public HandlerRegistration addFooterClickHandler(
  7778. FooterClickHandler handler) {
  7779. return addHandler(handler, GridClickEvent.TYPE);
  7780. }
  7781. /**
  7782. * Register a BodyDoubleClickHandler to this Grid. The event for this
  7783. * handler is fired when a double click event occurs in the Body of this
  7784. * Grid.
  7785. *
  7786. * @param handler
  7787. * the double click handler to register
  7788. * @return the registration for the event
  7789. */
  7790. public HandlerRegistration addBodyDoubleClickHandler(
  7791. BodyDoubleClickHandler handler) {
  7792. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7793. }
  7794. /**
  7795. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  7796. * handler is fired when a double click event occurs in the Header of this
  7797. * Grid.
  7798. *
  7799. * @param handler
  7800. * the double click handler to register
  7801. * @return the registration for the event
  7802. */
  7803. public HandlerRegistration addHeaderDoubleClickHandler(
  7804. HeaderDoubleClickHandler handler) {
  7805. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7806. }
  7807. /**
  7808. * Register a FooterDoubleClickHandler to this Grid. The event for this
  7809. * handler is fired when a double click event occurs in the Footer of this
  7810. * Grid.
  7811. *
  7812. * @param handler
  7813. * the double click handler to register
  7814. * @return the registration for the event
  7815. */
  7816. public HandlerRegistration addFooterDoubleClickHandler(
  7817. FooterDoubleClickHandler handler) {
  7818. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7819. }
  7820. /**
  7821. * Register a column reorder handler to this Grid. The event for this
  7822. * handler is fired when the Grid's columns are reordered.
  7823. *
  7824. * @since 7.5.0
  7825. * @param handler
  7826. * the handler for the event
  7827. * @return the registration for the event
  7828. */
  7829. public HandlerRegistration addColumnReorderHandler(
  7830. ColumnReorderHandler<T> handler) {
  7831. return addHandler(handler, ColumnReorderEvent.getType());
  7832. }
  7833. /**
  7834. * Register a column visibility change handler to this Grid. The event for
  7835. * this handler is fired when the Grid's columns change visibility.
  7836. *
  7837. * @since 7.5.0
  7838. * @param handler
  7839. * the handler for the event
  7840. * @return the registration for the event
  7841. */
  7842. public HandlerRegistration addColumnVisibilityChangeHandler(
  7843. ColumnVisibilityChangeHandler<T> handler) {
  7844. return addHandler(handler, ColumnVisibilityChangeEvent.getType());
  7845. }
  7846. /**
  7847. * Register a column resize handler to this Grid. The event for this handler
  7848. * is fired when the Grid's columns are resized.
  7849. *
  7850. * @since 7.6
  7851. * @param handler
  7852. * the handler for the event
  7853. * @return the registration for the event
  7854. */
  7855. public HandlerRegistration addColumnResizeHandler(
  7856. ColumnResizeHandler<T> handler) {
  7857. return addHandler(handler, ColumnResizeEvent.getType());
  7858. }
  7859. /**
  7860. * Register a enabled status change handler to this Grid. The event for this
  7861. * handler is fired when the Grid changes from disabled to enabled and
  7862. * vice-versa.
  7863. *
  7864. * @param handler
  7865. * the handler for the event
  7866. * @return the registration for the event
  7867. */
  7868. public HandlerRegistration addEnabledHandler(GridEnabledHandler handler) {
  7869. return addHandler(handler, GridEnabledEvent.TYPE);
  7870. }
  7871. /**
  7872. * Register a selection allowed status change handler to this Grid. The
  7873. * event for this handler is fired when the Grid changes selection allowed
  7874. * state.
  7875. *
  7876. * @param handler
  7877. * the handler for the event
  7878. * @return the registration for the event
  7879. */
  7880. public HandlerRegistration addSelectionAllowedHandler(
  7881. GridSelectionAllowedHandler handler) {
  7882. return addHandler(handler, GridSelectionAllowedEvent.TYPE);
  7883. }
  7884. public HandlerRegistration addRowHeightChangedHandler(
  7885. RowHeightChangedHandler handler) {
  7886. return escalator.addHandler(handler, RowHeightChangedEvent.TYPE);
  7887. }
  7888. /**
  7889. * Adds a spacer visibility changed handler to the underlying escalator.
  7890. *
  7891. * @param handler
  7892. * the handler to be called when a spacer's visibility changes
  7893. * @return the registration object with which the handler can be removed
  7894. * @since 8.3.2
  7895. */
  7896. public HandlerRegistration addSpacerVisibilityChangedHandler(
  7897. SpacerVisibilityChangedHandler handler) {
  7898. return escalator.addHandler(handler, SpacerVisibilityChangedEvent.TYPE);
  7899. }
  7900. /**
  7901. * Adds a spacer index changed handler to the underlying escalator.
  7902. *
  7903. * @param handler
  7904. * the handler to be called when a spacer's index changes
  7905. * @return the registration object with which the handler can be removed
  7906. * @since 8.9
  7907. */
  7908. public HandlerRegistration addSpacerIndexChangedHandler(
  7909. SpacerIndexChangedHandler handler) {
  7910. return escalator.addHandler(handler, SpacerIndexChangedEvent.TYPE);
  7911. }
  7912. /**
  7913. * Adds a low-level DOM event handler to this Grid. The handler is inserted
  7914. * into the given position in the list of handlers. The handlers are invoked
  7915. * in order. If the
  7916. * {@link GridEventHandler#onEvent(Event, EventCellReference) onEvent}
  7917. * method of a handler returns true, subsequent handlers are not invoked.
  7918. *
  7919. * @param index
  7920. * the index to insert the handler to
  7921. * @param handler
  7922. * the handler to add
  7923. */
  7924. public void addBrowserEventHandler(int index, GridEventHandler<T> handler) {
  7925. browserEventHandlers.add(index, handler);
  7926. }
  7927. /**
  7928. * Apply sorting to data source.
  7929. */
  7930. private void sort(boolean userOriginated) {
  7931. refreshHeader();
  7932. fireEvent(new SortEvent<>(this, Collections.unmodifiableList(sortOrder),
  7933. userOriginated));
  7934. }
  7935. private int getLastVisibleRowIndex() {
  7936. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  7937. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  7938. Element lastRow;
  7939. do {
  7940. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  7941. } while (lastRow.getAbsoluteTop() > footerTop);
  7942. return lastRowIndex;
  7943. }
  7944. private int getFirstVisibleRowIndex() {
  7945. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  7946. int headerBottom = escalator.getHeader().getElement()
  7947. .getAbsoluteBottom();
  7948. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  7949. while (firstRow.getAbsoluteBottom() < headerBottom) {
  7950. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  7951. }
  7952. return firstRowIndex;
  7953. }
  7954. /**
  7955. * Adds a scroll handler to this grid.
  7956. *
  7957. * @param handler
  7958. * the scroll handler to add
  7959. * @return a handler registration for the registered scroll handler
  7960. */
  7961. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7962. return addHandler(handler, ScrollEvent.TYPE);
  7963. }
  7964. @Override
  7965. public boolean isWorkPending() {
  7966. return escalator.isWorkPending() || dataSource.isWaitingForData()
  7967. || autoColumnWidthsRecalculator.isScheduled()
  7968. || editor.isWorkPending();
  7969. }
  7970. /**
  7971. * Returns whether columns can be reordered with drag and drop.
  7972. *
  7973. * @since 7.5.0
  7974. * @return <code>true</code> if columns can be reordered, false otherwise
  7975. */
  7976. public boolean isColumnReorderingAllowed() {
  7977. return columnReorderingAllowed;
  7978. }
  7979. /**
  7980. * Sets whether column reordering with drag and drop is allowed or not.
  7981. *
  7982. * @since 7.5.0
  7983. * @param columnReorderingAllowed
  7984. * specifies whether column reordering is allowed
  7985. */
  7986. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  7987. this.columnReorderingAllowed = columnReorderingAllowed;
  7988. }
  7989. /**
  7990. * Sets a new column order for the grid. All columns which are not ordered
  7991. * here will remain in the order they were before as the last columns of
  7992. * grid.
  7993. *
  7994. * @param orderedColumns
  7995. * array of columns in wanted order
  7996. */
  7997. public void setColumnOrder(Column<?, T>... orderedColumns) {
  7998. setColumnOrder(false, orderedColumns);
  7999. }
  8000. private void setColumnOrder(boolean isUserOriginated,
  8001. Column<?, T>... orderedColumns) {
  8002. List<Column<?, T>> newOrder = new ArrayList<>();
  8003. if (selectionColumn != null) {
  8004. newOrder.add(selectionColumn);
  8005. }
  8006. int i = 0;
  8007. for (Column<?, T> column : orderedColumns) {
  8008. if (columns.contains(column)) {
  8009. newOrder.add(column);
  8010. ++i;
  8011. } else {
  8012. throw new IllegalArgumentException("Given column at index " + i
  8013. + " does not exist in Grid");
  8014. }
  8015. }
  8016. if (columns.size() != newOrder.size()) {
  8017. columns.stream().filter(col -> !newOrder.contains(col))
  8018. .forEach(newOrder::add);
  8019. }
  8020. if (columns.equals(newOrder)) {
  8021. // No changes in order.
  8022. return;
  8023. }
  8024. // Prepare event for firing
  8025. ColumnReorderEvent<T> event = new ColumnReorderEvent<>(columns,
  8026. newOrder, isUserOriginated);
  8027. // Trigger ComplexRenderer.destroy for old content
  8028. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  8029. conf.removeColumns(0, conf.getColumnCount());
  8030. // Update the order
  8031. columns = newOrder;
  8032. // Do ComplexRenderer.init and render new content
  8033. conf.insertColumns(0, getVisibleColumns().size());
  8034. // Number of frozen columns should be kept same #16901
  8035. updateFrozenColumns();
  8036. // Update column widths.
  8037. for (Column<?, T> column : columns) {
  8038. column.reapplyWidth();
  8039. }
  8040. // Recalculate all the colspans
  8041. for (HeaderRow row : header.getRows()) {
  8042. row.calculateColspans();
  8043. }
  8044. for (FooterRow row : footer.getRows()) {
  8045. row.calculateColspans();
  8046. }
  8047. columnHider.updateTogglesOrder();
  8048. fireEvent(event);
  8049. }
  8050. /**
  8051. * Sets the style generator that is used for generating styles for cells.
  8052. *
  8053. * @param cellStyleGenerator
  8054. * the cell style generator to set, or <code>null</code> to
  8055. * remove a previously set generator
  8056. */
  8057. public void setCellStyleGenerator(
  8058. CellStyleGenerator<T> cellStyleGenerator) {
  8059. this.cellStyleGenerator = cellStyleGenerator;
  8060. requestRefreshBody();
  8061. }
  8062. /**
  8063. * Gets the style generator that is used for generating styles for cells.
  8064. *
  8065. * @return the cell style generator, or <code>null</code> if no generator is
  8066. * set
  8067. */
  8068. public CellStyleGenerator<T> getCellStyleGenerator() {
  8069. return cellStyleGenerator;
  8070. }
  8071. /**
  8072. * Sets the style generator that is used for generating styles for rows.
  8073. *
  8074. * @param rowStyleGenerator
  8075. * the row style generator to set, or <code>null</code> to remove
  8076. * a previously set generator
  8077. */
  8078. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  8079. this.rowStyleGenerator = rowStyleGenerator;
  8080. requestRefreshBody();
  8081. }
  8082. /**
  8083. * Gets the style generator that is used for generating styles for rows.
  8084. *
  8085. * @return the row style generator, or <code>null</code> if no generator is
  8086. * set
  8087. */
  8088. public RowStyleGenerator<T> getRowStyleGenerator() {
  8089. return rowStyleGenerator;
  8090. }
  8091. private static void setCustomStyleName(Element element, String styleName) {
  8092. assert element != null;
  8093. String oldStyleName = element
  8094. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  8095. if (!SharedUtil.equals(oldStyleName, styleName)) {
  8096. if (oldStyleName != null && !oldStyleName.isEmpty()) {
  8097. element.removeClassName(oldStyleName);
  8098. }
  8099. if (styleName != null && !styleName.isEmpty()) {
  8100. element.addClassName(styleName);
  8101. }
  8102. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  8103. }
  8104. }
  8105. /**
  8106. * Opens the editor over the row with the given index.
  8107. *
  8108. * @param rowIndex
  8109. * the index of the row to be edited
  8110. *
  8111. * @throws IllegalStateException
  8112. * if the editor is not enabled
  8113. * @throws IllegalStateException
  8114. * if the editor is already in edit mode
  8115. */
  8116. public void editRow(int rowIndex) {
  8117. editor.editRow(rowIndex);
  8118. }
  8119. /**
  8120. * Returns whether the editor is currently open on some row.
  8121. *
  8122. * @return {@code true} if the editor is active, {@code false} otherwise.
  8123. */
  8124. public boolean isEditorActive() {
  8125. return editor.getState() != State.INACTIVE;
  8126. }
  8127. /**
  8128. * Saves any unsaved changes in the editor to the data source.
  8129. *
  8130. * @throws IllegalStateException
  8131. * if the editor is not enabled
  8132. * @throws IllegalStateException
  8133. * if the editor is not in edit mode
  8134. */
  8135. public void saveEditor() {
  8136. editor.save();
  8137. }
  8138. /**
  8139. * Cancels the currently active edit and hides the editor. Any changes that
  8140. * are not {@link #saveEditor() saved} are lost.
  8141. *
  8142. * @throws IllegalStateException
  8143. * if the editor is not enabled
  8144. * @throws IllegalStateException
  8145. * if the editor is not in edit mode
  8146. */
  8147. public void cancelEditor() {
  8148. editor.cancel();
  8149. }
  8150. /**
  8151. * Returns the handler responsible for binding data and editor widgets to
  8152. * the editor.
  8153. *
  8154. * @return the editor handler or null if not set
  8155. */
  8156. public EditorHandler<T> getEditorHandler() {
  8157. return editor.getHandler();
  8158. }
  8159. /**
  8160. * Sets the handler responsible for binding data and editor widgets to the
  8161. * editor.
  8162. *
  8163. * @param handler
  8164. * the new editor handler
  8165. *
  8166. * @throws IllegalStateException
  8167. * if the editor is currently in edit mode
  8168. */
  8169. public void setEditorHandler(EditorHandler<T> handler) {
  8170. editor.setHandler(handler);
  8171. }
  8172. /**
  8173. * Returns the enabled state of the editor.
  8174. *
  8175. * @return true if editing is enabled, false otherwise
  8176. */
  8177. public boolean isEditorEnabled() {
  8178. return editor.isEnabled();
  8179. }
  8180. /**
  8181. * Sets the enabled state of the editor.
  8182. *
  8183. * @param enabled
  8184. * true to enable editing, false to disable
  8185. *
  8186. * @throws IllegalStateException
  8187. * if in edit mode and trying to disable
  8188. * @throws IllegalStateException
  8189. * if the editor handler is not set
  8190. */
  8191. public void setEditorEnabled(boolean enabled) {
  8192. editor.setEnabled(enabled);
  8193. }
  8194. /**
  8195. * Returns the editor widget associated with the given column. If the editor
  8196. * is not active, returns null.
  8197. *
  8198. * @param column
  8199. * the column
  8200. * @return the widget if the editor is open, null otherwise
  8201. */
  8202. public Widget getEditorWidget(Column<?, T> column) {
  8203. return editor.getWidget(column);
  8204. }
  8205. /**
  8206. * Sets the caption on the save button in the Grid editor.
  8207. *
  8208. * @param saveCaption
  8209. * the caption to set
  8210. * @throws IllegalArgumentException
  8211. * if {@code saveCaption} is {@code null}
  8212. */
  8213. public void setEditorSaveCaption(String saveCaption)
  8214. throws IllegalArgumentException {
  8215. editor.setSaveCaption(saveCaption);
  8216. }
  8217. /**
  8218. * Gets the current caption on the save button in the Grid editor.
  8219. *
  8220. * @return the current caption on the save button
  8221. */
  8222. public String getEditorSaveCaption() {
  8223. return editor.getSaveCaption();
  8224. }
  8225. /**
  8226. * Sets the caption on the cancel button in the Grid editor.
  8227. *
  8228. * @param cancelCaption
  8229. * the caption to set
  8230. * @throws IllegalArgumentException
  8231. * if {@code cancelCaption} is {@code null}
  8232. */
  8233. public void setEditorCancelCaption(String cancelCaption)
  8234. throws IllegalArgumentException {
  8235. editor.setCancelCaption(cancelCaption);
  8236. }
  8237. /**
  8238. * Gets the caption on the cancel button in the Grid editor.
  8239. *
  8240. * @return the current caption on the cancel button
  8241. */
  8242. public String getEditorCancelCaption() {
  8243. return editor.getCancelCaption();
  8244. }
  8245. @Override
  8246. protected void onAttach() {
  8247. super.onAttach();
  8248. // Grid was just attached to DOM. Column widths should be
  8249. // calculated.
  8250. recalculateColumnWidths();
  8251. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  8252. setEscalatorSizeFromDataSource();
  8253. }
  8254. for (int row : reattachVisibleDetails) {
  8255. setDetailsVisible(row, true);
  8256. }
  8257. reattachVisibleDetails.clear();
  8258. }
  8259. @Override
  8260. protected void onDetach() {
  8261. Set<Integer> details = new HashSet<>(visibleDetails);
  8262. reattachVisibleDetails.clear();
  8263. reattachVisibleDetails.addAll(details);
  8264. for (int row : details) {
  8265. setDetailsVisible(row, false);
  8266. }
  8267. super.onDetach();
  8268. }
  8269. @Override
  8270. public void onResize() {
  8271. super.onResize();
  8272. /*
  8273. * Delay calculation to be deferred so Escalator can do it's magic.
  8274. */
  8275. Scheduler.get().scheduleFinally(() -> {
  8276. if (escalator
  8277. .getInnerWidth() != autoColumnWidthsRecalculator.lastCalculatedInnerWidth) {
  8278. recalculateColumnWidths();
  8279. }
  8280. // Vertical resizing could make editor positioning invalid so it
  8281. // needs to be recalculated on resize
  8282. if (isEditorActive()) {
  8283. editor.updateVerticalScrollPosition();
  8284. }
  8285. // if there is a resize, we need to refresh the body to avoid an
  8286. // off-by-one error which occurs when the user scrolls all the
  8287. // way to the bottom.
  8288. refreshBody();
  8289. });
  8290. }
  8291. /**
  8292. * Grid does not support adding Widgets this way.
  8293. * <p>
  8294. * This method is implemented only because removing widgets from Grid (added
  8295. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  8296. *
  8297. * @param w
  8298. * irrelevant
  8299. * @throws UnsupportedOperationException
  8300. * always
  8301. */
  8302. @Override
  8303. @Deprecated
  8304. public void add(Widget w) {
  8305. throw new UnsupportedOperationException(
  8306. "Cannot add widgets to Grid with this method");
  8307. }
  8308. /**
  8309. * Grid does not support clearing Widgets this way.
  8310. * <p>
  8311. * This method is implemented only because removing widgets from Grid (added
  8312. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  8313. *
  8314. * @throws UnsupportedOperationException
  8315. * always
  8316. */
  8317. @Override
  8318. @Deprecated
  8319. public void clear() {
  8320. throw new UnsupportedOperationException(
  8321. "Cannot clear widgets from Grid this way");
  8322. }
  8323. /**
  8324. * Grid does not support iterating through Widgets this way.
  8325. * <p>
  8326. * This method is implemented only because removing widgets from Grid (added
  8327. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  8328. *
  8329. * @return never
  8330. * @throws UnsupportedOperationException
  8331. * always
  8332. */
  8333. @Override
  8334. @Deprecated
  8335. public Iterator<Widget> iterator() {
  8336. throw new UnsupportedOperationException(
  8337. "Cannot iterate through widgets in Grid this way");
  8338. }
  8339. /**
  8340. * Grid does not support removing Widgets this way.
  8341. * <p>
  8342. * This method is implemented only because removing widgets from Grid (added
  8343. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  8344. *
  8345. * @return always <code>false</code>
  8346. */
  8347. @Override
  8348. @Deprecated
  8349. public boolean remove(Widget w) {
  8350. /*
  8351. * This is the method that is the sole reason to have Grid implement
  8352. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  8353. * corresponding Widget will call removeFromParent() on itself. GWT will
  8354. * check there that its parent (i.e. Grid) implements HasWidgets, and
  8355. * will call this remove(Widget) method.
  8356. *
  8357. * tl;dr: all this song and dance to make sure GWT's sanity checks
  8358. * aren't triggered, even though they effectively do nothing interesting
  8359. * from Grid's perspective.
  8360. */
  8361. return false;
  8362. }
  8363. /**
  8364. * Accesses the package private method Widget#setParent()
  8365. *
  8366. * @param widget
  8367. * The widget to access
  8368. * @param parent
  8369. * The parent to set
  8370. */
  8371. private static final native void setParent(Widget widget, Grid<?> parent)
  8372. /*-{
  8373. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  8374. }-*/;
  8375. private static final native void onAttach(Widget widget)
  8376. /*-{
  8377. widget.@Widget::onAttach()();
  8378. }-*/;
  8379. private static final native void onDetach(Widget widget)
  8380. /*-{
  8381. widget.@Widget::onDetach()();
  8382. }-*/;
  8383. @Override
  8384. protected void doAttachChildren() {
  8385. if (sidebar.getParent() == this) {
  8386. onAttach(sidebar);
  8387. }
  8388. }
  8389. @Override
  8390. protected void doDetachChildren() {
  8391. if (sidebar.getParent() == this) {
  8392. onDetach(sidebar);
  8393. }
  8394. }
  8395. private void attachWidget(Widget w, Element parent) {
  8396. assert w.getParent() == null;
  8397. parent.appendChild(w.getElement());
  8398. setParent(w, this);
  8399. }
  8400. private void detachWidget(Widget w) {
  8401. assert w.getParent() == this;
  8402. setParent(w, null);
  8403. w.getElement().removeFromParent();
  8404. }
  8405. /**
  8406. * Resets all cached pixel sizes and reads new values from the DOM. This
  8407. * methods should be used e.g. when styles affecting the dimensions of
  8408. * elements in this grid have been changed.
  8409. */
  8410. public void resetSizesFromDom() {
  8411. getEscalator().resetSizesFromDom();
  8412. }
  8413. /**
  8414. * Sets a new details generator for row details.
  8415. * <p>
  8416. * The currently opened row details will be re-rendered.
  8417. *
  8418. * @since 7.5.0
  8419. * @param detailsGenerator
  8420. * the details generator to set
  8421. * @throws IllegalArgumentException
  8422. * if detailsGenerator is <code>null</code>;
  8423. */
  8424. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  8425. throws IllegalArgumentException {
  8426. if (detailsGenerator == null) {
  8427. throw new IllegalArgumentException(
  8428. "Details generator may not be null");
  8429. }
  8430. for (Integer index : visibleDetails) {
  8431. setDetailsVisible(index, false);
  8432. }
  8433. this.detailsGenerator = detailsGenerator;
  8434. // this will refresh all visible spacers
  8435. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  8436. }
  8437. /**
  8438. * Gets the current details generator for row details.
  8439. *
  8440. * @since 7.5.0
  8441. * @return the detailsGenerator the current details generator
  8442. */
  8443. public DetailsGenerator getDetailsGenerator() {
  8444. return detailsGenerator;
  8445. }
  8446. /**
  8447. * Shows or hides the details for a specific row.
  8448. * <p>
  8449. * This method does nothing if trying to set show already-visible details,
  8450. * or hide already-hidden details.
  8451. *
  8452. * @since 7.5.0
  8453. * @param rowIndex
  8454. * the index of the affected row
  8455. * @param visible
  8456. * <code>true</code> to show the details, or <code>false</code>
  8457. * to hide them
  8458. * @see #isDetailsVisible(int)
  8459. */
  8460. public void setDetailsVisible(int rowIndex, boolean visible) {
  8461. if (DetailsGenerator.NULL.equals(detailsGenerator)) {
  8462. return;
  8463. }
  8464. Integer rowIndexInteger = Integer.valueOf(rowIndex);
  8465. /*
  8466. * We want to prevent opening a details row twice, so any subsequent
  8467. * openings (or closings) of details is a NOOP.
  8468. *
  8469. * When a details row is opened, it is given an arbitrary height
  8470. * (because Escalator requires a height upon opening). Only when it's
  8471. * opened, Escalator will ask the generator to generate a widget, which
  8472. * we then can measure. When measured, we correct the initial height by
  8473. * the original height.
  8474. *
  8475. * Without this check, we would override the measured height, and revert
  8476. * back to the initial, arbitrary, height which would most probably be
  8477. * wrong.
  8478. *
  8479. * see GridSpacerUpdater.init for implementation details.
  8480. *
  8481. * The order of operations isn't entirely stable. Sometimes Escalator
  8482. * knows about the spacer visibility updates first and doesn't need
  8483. * updating again but Grid's visibleDetails set still does.
  8484. */
  8485. boolean isVisible = isDetailsVisible(rowIndex);
  8486. boolean isVisibleInEscalator = escalator.getBody()
  8487. .spacerExists(rowIndex);
  8488. if (visible) {
  8489. if (!isVisibleInEscalator) {
  8490. escalator.getBody().setSpacer(rowIndex,
  8491. DETAILS_ROW_INITIAL_HEIGHT);
  8492. }
  8493. if (!isVisible) {
  8494. visibleDetails.add(rowIndexInteger);
  8495. }
  8496. } else {
  8497. if (isVisibleInEscalator) {
  8498. escalator.getBody().setSpacer(rowIndex, -1);
  8499. }
  8500. if (isVisible) {
  8501. visibleDetails.remove(rowIndexInteger);
  8502. }
  8503. }
  8504. }
  8505. /**
  8506. * Check whether the details for a row is visible or not.
  8507. *
  8508. * @since 7.5.0
  8509. * @param rowIndex
  8510. * the index of the row for which to check details
  8511. * @return <code>true</code> if the details for the given row is visible
  8512. * @see #setDetailsVisible(int, boolean)
  8513. */
  8514. public boolean isDetailsVisible(int rowIndex) {
  8515. return visibleDetails.contains(Integer.valueOf(rowIndex));
  8516. }
  8517. /**
  8518. * Update details row height.
  8519. *
  8520. * @since 8.1.3
  8521. * @param rowIndex
  8522. * the index of the row for which to update details height
  8523. * @param height
  8524. * new height of the details row
  8525. */
  8526. public void setDetailsHeight(int rowIndex, double height) {
  8527. escalator.getBody().setSpacer(rowIndex, height);
  8528. }
  8529. /**
  8530. * Requests that the column widths should be recalculated.
  8531. * <p>
  8532. * The actual recalculation is not necessarily done immediately so you
  8533. * cannot rely on the columns being the correct width after the call
  8534. * returns.
  8535. *
  8536. * @since 7.4.1
  8537. */
  8538. public void recalculateColumnWidths() {
  8539. autoColumnWidthsRecalculator.schedule();
  8540. }
  8541. /**
  8542. * Gets the customizable menu bar that is by default used for toggling
  8543. * column hidability. The application developer is allowed to add their
  8544. * custom items to the end of the menu, but should try to avoid modifying
  8545. * the items in the beginning of the menu that control the column hiding if
  8546. * any columns are marked as hidable. A toggle for opening the menu will be
  8547. * displayed whenever the menu contains at least one item.
  8548. *
  8549. * @since 7.5.0
  8550. * @return the menu bar
  8551. */
  8552. public MenuBar getSidebarMenu() {
  8553. return sidebar.menuBar;
  8554. }
  8555. /**
  8556. * Tests whether the sidebar menu is currently open.
  8557. *
  8558. * @since 7.5.0
  8559. * @see #getSidebarMenu()
  8560. * @return <code>true</code> if the sidebar is open; <code>false</code> if
  8561. * it is closed
  8562. */
  8563. public boolean isSidebarOpen() {
  8564. return sidebar.isOpen();
  8565. }
  8566. /**
  8567. * Sets whether the sidebar menu is open.
  8568. *
  8569. *
  8570. * @since 7.5.0
  8571. * @see #getSidebarMenu()
  8572. * @see #isSidebarOpen()
  8573. * @param sidebarOpen
  8574. * <code>true</code> to open the sidebar; <code>false</code> to
  8575. * close it
  8576. */
  8577. public void setSidebarOpen(boolean sidebarOpen) {
  8578. if (sidebarOpen) {
  8579. sidebar.open();
  8580. } else {
  8581. sidebar.close();
  8582. }
  8583. }
  8584. @Override
  8585. public int getTabIndex() {
  8586. return FocusUtil.getTabIndex(this);
  8587. }
  8588. @Override
  8589. public void setAccessKey(char key) {
  8590. FocusUtil.setAccessKey(this, key);
  8591. }
  8592. @Override
  8593. public void setFocus(boolean focused) {
  8594. FocusUtil.setFocus(this, focused);
  8595. }
  8596. @Override
  8597. public void setTabIndex(int index) {
  8598. FocusUtil.setTabIndex(this, index);
  8599. }
  8600. @Override
  8601. public void focus() {
  8602. setFocus(true);
  8603. }
  8604. /**
  8605. * Sets the buffered editor mode.
  8606. *
  8607. * @since 7.6
  8608. * @param editorBuffered
  8609. * <code>true</code> to enable buffered editor,
  8610. * <code>false</code> to disable it
  8611. */
  8612. public void setEditorBuffered(boolean editorBuffered) {
  8613. editor.setBuffered(editorBuffered);
  8614. }
  8615. /**
  8616. * Gets the buffered editor mode.
  8617. *
  8618. * @since 7.6
  8619. * @return <code>true</code> if buffered editor is enabled,
  8620. * <code>false</code> otherwise
  8621. */
  8622. public boolean isEditorBuffered() {
  8623. return editor.isBuffered();
  8624. }
  8625. /**
  8626. * Returns the {@link EventCellReference} for the latest event fired from
  8627. * this Grid.
  8628. * <p>
  8629. * Note: This cell reference will be updated when firing the next event.
  8630. *
  8631. * @since 7.5
  8632. * @return event cell reference
  8633. */
  8634. public EventCellReference<T> getEventCell() {
  8635. return eventCell;
  8636. }
  8637. /**
  8638. * Returns a CellReference for the cell to which the given element belongs
  8639. * to.
  8640. *
  8641. * @since 7.6
  8642. * @param element
  8643. * Element to find from the cell's content.
  8644. * @return CellReference or <code>null</code> if cell was not found.
  8645. */
  8646. public CellReference<T> getCellReference(Element element) {
  8647. RowContainer container = getEscalator().findRowContainer(element);
  8648. if (container != null) {
  8649. Cell cell = container.getCell(element);
  8650. if (cell != null) {
  8651. EventCellReference<T> cellRef = new EventCellReference<>(this);
  8652. cellRef.set(cell, getSectionFromContainer(container));
  8653. return cellRef;
  8654. }
  8655. }
  8656. return null;
  8657. }
  8658. /**
  8659. * Returns the selection column for the grid if the selection model is of
  8660. * type {@link SelectionModelWithSelectionColumn}.
  8661. *
  8662. * @return the select all checkbox, or an empty optional if not in use
  8663. */
  8664. public Optional<SelectionColumn> getSelectionColumn() {
  8665. return Optional.ofNullable(selectionColumn);
  8666. }
  8667. }