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

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