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

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