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

Grid.java 314KB

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