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.

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