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

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