You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Grid.java 343KB

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