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

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