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

Grid.java 317KB

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