Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Grid.java 323KB

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