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

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