Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Grid.java 336KB

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