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

Grid.java 327KB

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