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

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