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

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