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

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