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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.widgets;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Map.Entry;
  28. import java.util.Set;
  29. import java.util.TreeMap;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;
  32. import com.google.gwt.core.client.Scheduler;
  33. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  34. import com.google.gwt.core.shared.GWT;
  35. import com.google.gwt.dom.client.BrowserEvents;
  36. import com.google.gwt.dom.client.DivElement;
  37. import com.google.gwt.dom.client.Element;
  38. import com.google.gwt.dom.client.EventTarget;
  39. import com.google.gwt.dom.client.NativeEvent;
  40. import com.google.gwt.dom.client.Style;
  41. import com.google.gwt.dom.client.Style.Unit;
  42. import com.google.gwt.dom.client.TableCellElement;
  43. import com.google.gwt.dom.client.TableRowElement;
  44. import com.google.gwt.dom.client.TableSectionElement;
  45. import com.google.gwt.dom.client.Touch;
  46. import com.google.gwt.event.dom.client.ClickEvent;
  47. import com.google.gwt.event.dom.client.ClickHandler;
  48. import com.google.gwt.event.dom.client.KeyCodes;
  49. import com.google.gwt.event.dom.client.KeyEvent;
  50. import com.google.gwt.event.dom.client.MouseEvent;
  51. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  52. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  53. import com.google.gwt.event.shared.HandlerRegistration;
  54. import com.google.gwt.touch.client.Point;
  55. import com.google.gwt.user.client.DOM;
  56. import com.google.gwt.user.client.Event;
  57. import com.google.gwt.user.client.Event.NativePreviewEvent;
  58. import com.google.gwt.user.client.Event.NativePreviewHandler;
  59. import com.google.gwt.user.client.Timer;
  60. import com.google.gwt.user.client.ui.Button;
  61. import com.google.gwt.user.client.ui.CheckBox;
  62. import com.google.gwt.user.client.ui.HasEnabled;
  63. import com.google.gwt.user.client.ui.HasWidgets;
  64. import com.google.gwt.user.client.ui.ResizeComposite;
  65. import com.google.gwt.user.client.ui.Widget;
  66. import com.vaadin.client.DeferredWorker;
  67. import com.vaadin.client.WidgetUtil;
  68. import com.vaadin.client.data.DataChangeHandler;
  69. import com.vaadin.client.data.DataSource;
  70. import com.vaadin.client.renderers.ComplexRenderer;
  71. import com.vaadin.client.renderers.Renderer;
  72. import com.vaadin.client.renderers.WidgetRenderer;
  73. import com.vaadin.client.ui.SubPartAware;
  74. import com.vaadin.client.ui.dd.DragAndDropHandler;
  75. import com.vaadin.client.ui.dd.DragAndDropHandler.DragAndDropCallback;
  76. import com.vaadin.client.widget.escalator.Cell;
  77. import com.vaadin.client.widget.escalator.ColumnConfiguration;
  78. import com.vaadin.client.widget.escalator.EscalatorUpdater;
  79. import com.vaadin.client.widget.escalator.FlyweightCell;
  80. import com.vaadin.client.widget.escalator.Row;
  81. import com.vaadin.client.widget.escalator.RowContainer;
  82. import com.vaadin.client.widget.escalator.RowVisibilityChangeEvent;
  83. import com.vaadin.client.widget.escalator.RowVisibilityChangeHandler;
  84. import com.vaadin.client.widget.escalator.ScrollbarBundle.Direction;
  85. import com.vaadin.client.widget.grid.AutoScroller;
  86. import com.vaadin.client.widget.grid.AutoScroller.AutoScrollerCallback;
  87. import com.vaadin.client.widget.grid.AutoScroller.ScrollAxis;
  88. import com.vaadin.client.widget.grid.CellReference;
  89. import com.vaadin.client.widget.grid.CellStyleGenerator;
  90. import com.vaadin.client.widget.grid.DataAvailableEvent;
  91. import com.vaadin.client.widget.grid.DataAvailableHandler;
  92. import com.vaadin.client.widget.grid.EditorHandler;
  93. import com.vaadin.client.widget.grid.EditorHandler.EditorRequest;
  94. import com.vaadin.client.widget.grid.EventCellReference;
  95. import com.vaadin.client.widget.grid.RendererCellReference;
  96. import com.vaadin.client.widget.grid.RowReference;
  97. import com.vaadin.client.widget.grid.RowStyleGenerator;
  98. import com.vaadin.client.widget.grid.events.AbstractGridKeyEventHandler;
  99. import com.vaadin.client.widget.grid.events.AbstractGridMouseEventHandler;
  100. import com.vaadin.client.widget.grid.events.BodyClickHandler;
  101. import com.vaadin.client.widget.grid.events.BodyDoubleClickHandler;
  102. import com.vaadin.client.widget.grid.events.BodyKeyDownHandler;
  103. import com.vaadin.client.widget.grid.events.BodyKeyPressHandler;
  104. import com.vaadin.client.widget.grid.events.BodyKeyUpHandler;
  105. import com.vaadin.client.widget.grid.events.ColumnReorderEvent;
  106. import com.vaadin.client.widget.grid.events.ColumnReorderHandler;
  107. import com.vaadin.client.widget.grid.events.FooterClickHandler;
  108. import com.vaadin.client.widget.grid.events.FooterDoubleClickHandler;
  109. import com.vaadin.client.widget.grid.events.FooterKeyDownHandler;
  110. import com.vaadin.client.widget.grid.events.FooterKeyPressHandler;
  111. import com.vaadin.client.widget.grid.events.FooterKeyUpHandler;
  112. import com.vaadin.client.widget.grid.events.GridClickEvent;
  113. import com.vaadin.client.widget.grid.events.GridDoubleClickEvent;
  114. import com.vaadin.client.widget.grid.events.GridKeyDownEvent;
  115. import com.vaadin.client.widget.grid.events.GridKeyPressEvent;
  116. import com.vaadin.client.widget.grid.events.GridKeyUpEvent;
  117. import com.vaadin.client.widget.grid.events.HeaderClickHandler;
  118. import com.vaadin.client.widget.grid.events.HeaderDoubleClickHandler;
  119. import com.vaadin.client.widget.grid.events.HeaderKeyDownHandler;
  120. import com.vaadin.client.widget.grid.events.HeaderKeyPressHandler;
  121. import com.vaadin.client.widget.grid.events.HeaderKeyUpHandler;
  122. import com.vaadin.client.widget.grid.events.ScrollEvent;
  123. import com.vaadin.client.widget.grid.events.ScrollHandler;
  124. import com.vaadin.client.widget.grid.events.SelectAllEvent;
  125. import com.vaadin.client.widget.grid.events.SelectAllHandler;
  126. import com.vaadin.client.widget.grid.selection.HasSelectionHandlers;
  127. import com.vaadin.client.widget.grid.selection.SelectionEvent;
  128. import com.vaadin.client.widget.grid.selection.SelectionHandler;
  129. import com.vaadin.client.widget.grid.selection.SelectionModel;
  130. import com.vaadin.client.widget.grid.selection.SelectionModel.Multi;
  131. import com.vaadin.client.widget.grid.selection.SelectionModelMulti;
  132. import com.vaadin.client.widget.grid.selection.SelectionModelNone;
  133. import com.vaadin.client.widget.grid.selection.SelectionModelSingle;
  134. import com.vaadin.client.widget.grid.sort.Sort;
  135. import com.vaadin.client.widget.grid.sort.SortEvent;
  136. import com.vaadin.client.widget.grid.sort.SortHandler;
  137. import com.vaadin.client.widget.grid.sort.SortOrder;
  138. import com.vaadin.client.widgets.Escalator.AbstractRowContainer;
  139. import com.vaadin.client.widgets.Grid.Editor.State;
  140. import com.vaadin.client.widgets.Grid.StaticSection.StaticCell;
  141. import com.vaadin.client.widgets.Grid.StaticSection.StaticRow;
  142. import com.vaadin.shared.data.sort.SortDirection;
  143. import com.vaadin.shared.ui.grid.GridConstants;
  144. import com.vaadin.shared.ui.grid.GridStaticCellType;
  145. import com.vaadin.shared.ui.grid.HeightMode;
  146. import com.vaadin.shared.ui.grid.Range;
  147. import com.vaadin.shared.ui.grid.ScrollDestination;
  148. import com.vaadin.shared.util.SharedUtil;
  149. /**
  150. * A data grid view that supports columns and lazy loading of data rows from a
  151. * data source.
  152. *
  153. * <h1>Columns</h1>
  154. * <p>
  155. * Each column in Grid is represented by a {@link Column}. Each
  156. * {@code GridColumn} has a custom implementation for
  157. * {@link Column#getValue(Object)} that gets the row object as an argument, and
  158. * returns the value for that particular column, extracted from the row object.
  159. * <p>
  160. * Each column also has a Renderer. Its function is to take the value that is
  161. * given by the {@code GridColumn} and display it to the user. A simple column
  162. * might have a {@link com.vaadin.client.renderers.TextRenderer TextRenderer}
  163. * that simply takes in a {@code String} and displays it as the cell's content.
  164. * A more complex renderer might be
  165. * {@link com.vaadin.client.renderers.ProgressBarRenderer ProgressBarRenderer}
  166. * that takes in a floating point number, and displays a progress bar instead,
  167. * based on the given number.
  168. * <p>
  169. * <em>See:</em> {@link #addColumn(Column)}, {@link #addColumn(Column, int)} and
  170. * {@link #addColumns(Column...)}. <em>Also</em>
  171. * {@link Column#setRenderer(Renderer)}.
  172. *
  173. * <h1>Data Sources</h1>
  174. * <p>
  175. * Grid gets its data from a {@link DataSource}, providing row objects to Grid
  176. * from a user-defined endpoint. It can be either a local in-memory data source
  177. * (e.g. {@link com.vaadin.client.widget.grid.datasources.ListDataSource
  178. * ListDataSource}) or even a remote one, retrieving data from e.g. a REST API
  179. * (see {@link com.vaadin.client.data.AbstractRemoteDataSource
  180. * AbstractRemoteDataSource}).
  181. *
  182. *
  183. * @param <T>
  184. * The row type of the grid. The row type is the POJO type from where
  185. * the data is retrieved into the column cells.
  186. * @since 7.4
  187. * @author Vaadin Ltd
  188. */
  189. public class Grid<T> extends ResizeComposite implements
  190. HasSelectionHandlers<T>, SubPartAware, DeferredWorker, HasWidgets,
  191. HasEnabled {
  192. /**
  193. * Enum describing different sections of Grid.
  194. */
  195. public enum Section {
  196. HEADER, BODY, FOOTER
  197. }
  198. /**
  199. * Abstract base class for Grid header and footer sections.
  200. *
  201. * @param <ROWTYPE>
  202. * the type of the rows in the section
  203. */
  204. protected abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>> {
  205. /**
  206. * A header or footer cell. Has a simple textual caption.
  207. *
  208. */
  209. static class StaticCell {
  210. private Object content = null;
  211. private int colspan = 1;
  212. private StaticSection<?> section;
  213. private GridStaticCellType type = GridStaticCellType.TEXT;
  214. private String styleName = null;
  215. /**
  216. * Sets the text displayed in this cell.
  217. *
  218. * @param text
  219. * a plain text caption
  220. */
  221. public void setText(String text) {
  222. this.content = text;
  223. this.type = GridStaticCellType.TEXT;
  224. section.requestSectionRefresh();
  225. }
  226. /**
  227. * Returns the text displayed in this cell.
  228. *
  229. * @return the plain text caption
  230. */
  231. public String getText() {
  232. if (type != GridStaticCellType.TEXT) {
  233. throw new IllegalStateException(
  234. "Cannot fetch Text from a cell with type " + type);
  235. }
  236. return (String) content;
  237. }
  238. protected StaticSection<?> getSection() {
  239. assert section != null;
  240. return section;
  241. }
  242. protected void setSection(StaticSection<?> section) {
  243. this.section = section;
  244. }
  245. /**
  246. * Returns the amount of columns the cell spans. By default is 1.
  247. *
  248. * @return The amount of columns the cell spans.
  249. */
  250. public int getColspan() {
  251. return colspan;
  252. }
  253. /**
  254. * Sets the amount of columns the cell spans. Must be more or equal
  255. * to 1. By default is 1.
  256. *
  257. * @param colspan
  258. * the colspan to set
  259. */
  260. public void setColspan(int colspan) {
  261. if (colspan < 1) {
  262. throw new IllegalArgumentException(
  263. "Colspan cannot be less than 1");
  264. }
  265. this.colspan = colspan;
  266. section.requestSectionRefresh();
  267. }
  268. /**
  269. * Returns the html inside the cell.
  270. *
  271. * @throws IllegalStateException
  272. * if trying to retrive HTML from a cell with a type
  273. * other than {@link GridStaticCellType#HTML}.
  274. * @return the html content of the cell.
  275. */
  276. public String getHtml() {
  277. if (type != GridStaticCellType.HTML) {
  278. throw new IllegalStateException(
  279. "Cannot fetch HTML from a cell with type " + type);
  280. }
  281. return (String) content;
  282. }
  283. /**
  284. * Sets the content of the cell to the provided html. All previous
  285. * content is discarded and the cell type is set to
  286. * {@link GridStaticCellType#HTML}.
  287. *
  288. * @param html
  289. * The html content of the cell
  290. */
  291. public void setHtml(String html) {
  292. this.content = html;
  293. this.type = GridStaticCellType.HTML;
  294. section.requestSectionRefresh();
  295. }
  296. /**
  297. * Returns the widget in the cell.
  298. *
  299. * @throws IllegalStateException
  300. * if the cell is not {@link GridStaticCellType#WIDGET}
  301. *
  302. * @return the widget in the cell
  303. */
  304. public Widget getWidget() {
  305. if (type != GridStaticCellType.WIDGET) {
  306. throw new IllegalStateException(
  307. "Cannot fetch Widget from a cell with type " + type);
  308. }
  309. return (Widget) content;
  310. }
  311. /**
  312. * Set widget as the content of the cell. The type of the cell
  313. * becomes {@link GridStaticCellType#WIDGET}. All previous content
  314. * is discarded.
  315. *
  316. * @param widget
  317. * The widget to add to the cell. Should not be
  318. * previously attached anywhere (widget.getParent ==
  319. * null).
  320. */
  321. public void setWidget(Widget widget) {
  322. this.content = widget;
  323. this.type = GridStaticCellType.WIDGET;
  324. section.requestSectionRefresh();
  325. }
  326. /**
  327. * Returns the type of the cell.
  328. *
  329. * @return the type of content the cell contains.
  330. */
  331. public GridStaticCellType getType() {
  332. return type;
  333. }
  334. /**
  335. * Returns the custom style name for this cell.
  336. *
  337. * @return the style name or null if no style name has been set
  338. */
  339. public String getStyleName() {
  340. return styleName;
  341. }
  342. /**
  343. * Sets a custom style name for this cell.
  344. *
  345. * @param styleName
  346. * the style name to set or null to not use any style
  347. * name
  348. */
  349. public void setStyleName(String styleName) {
  350. this.styleName = styleName;
  351. section.requestSectionRefresh();
  352. }
  353. }
  354. /**
  355. * Abstract base class for Grid header and footer rows.
  356. *
  357. * @param <CELLTYPE>
  358. * the type of the cells in the row
  359. */
  360. abstract static class StaticRow<CELLTYPE extends StaticCell> {
  361. private Map<Column<?, ?>, CELLTYPE> cells = new HashMap<Column<?, ?>, CELLTYPE>();
  362. private StaticSection<?> section;
  363. /**
  364. * Map from set of spanned columns to cell meta data.
  365. */
  366. private Map<Set<Column<?, ?>>, CELLTYPE> cellGroups = new HashMap<Set<Column<?, ?>>, CELLTYPE>();
  367. /**
  368. * A custom style name for the row or null if none is set.
  369. */
  370. private String styleName = null;
  371. /**
  372. * Returns the cell on given GridColumn. If the column is merged
  373. * returned cell is the cell for the whole group.
  374. *
  375. * @param column
  376. * the column in grid
  377. * @return the cell on given column, merged cell for merged columns,
  378. * null if not found
  379. */
  380. public CELLTYPE getCell(Column<?, ?> column) {
  381. Set<Column<?, ?>> cellGroup = getCellGroupForColumn(column);
  382. if (cellGroup != null) {
  383. return cellGroups.get(cellGroup);
  384. }
  385. return cells.get(column);
  386. }
  387. /**
  388. * Returns <code>true</code> if this row contains spanned cells.
  389. *
  390. * @since
  391. * @return does this row contain spanned cells
  392. */
  393. public boolean hasSpannedCells() {
  394. return !cellGroups.isEmpty();
  395. }
  396. /**
  397. * Merges columns cells in a row
  398. *
  399. * @param columns
  400. * the columns which header should be merged
  401. * @return the remaining visible cell after the merge, or the cell
  402. * on first column if all are hidden
  403. */
  404. public CELLTYPE join(Column<?, ?>... columns) {
  405. if (columns.length <= 1) {
  406. throw new IllegalArgumentException(
  407. "You can't merge less than 2 columns together.");
  408. }
  409. HashSet<Column<?, ?>> columnGroup = new HashSet<Column<?, ?>>();
  410. for (Column<?, ?> column : columns) {
  411. if (!cells.containsKey(column)) {
  412. throw new IllegalArgumentException(
  413. "Given column does not exists on row " + column);
  414. } else if (getCellGroupForColumn(column) != null) {
  415. throw new IllegalStateException(
  416. "Column is already in a group.");
  417. }
  418. columnGroup.add(column);
  419. }
  420. CELLTYPE joinedCell = createCell();
  421. cellGroups.put(columnGroup, joinedCell);
  422. joinedCell.setSection(getSection());
  423. calculateColspans();
  424. return joinedCell;
  425. }
  426. /**
  427. * Merges columns cells in a row
  428. *
  429. * @param cells
  430. * The cells to merge. Must be from the same row.
  431. * @return The remaining visible cell after the merge, or the first
  432. * cell if all columns are hidden
  433. */
  434. public CELLTYPE join(CELLTYPE... cells) {
  435. if (cells.length <= 1) {
  436. throw new IllegalArgumentException(
  437. "You can't merge less than 2 cells together.");
  438. }
  439. Column<?, ?>[] columns = new Column<?, ?>[cells.length];
  440. int j = 0;
  441. for (Column<?, ?> column : this.cells.keySet()) {
  442. CELLTYPE cell = this.cells.get(column);
  443. if (!this.cells.containsValue(cells[j])) {
  444. throw new IllegalArgumentException(
  445. "Given cell does not exists on row");
  446. } else if (cell.equals(cells[j])) {
  447. columns[j++] = column;
  448. if (j == cells.length) {
  449. break;
  450. }
  451. }
  452. }
  453. return join(columns);
  454. }
  455. private Set<Column<?, ?>> getCellGroupForColumn(Column<?, ?> column) {
  456. for (Set<Column<?, ?>> group : cellGroups.keySet()) {
  457. if (group.contains(column)) {
  458. return group;
  459. }
  460. }
  461. return null;
  462. }
  463. void calculateColspans() {
  464. // Reset all cells
  465. for (CELLTYPE cell : this.cells.values()) {
  466. cell.setColspan(1);
  467. }
  468. List<Column<?, ?>> columnOrder = new ArrayList<Column<?, ?>>(
  469. section.grid.getColumns());
  470. // Set colspan for grouped cells
  471. for (Set<Column<?, ?>> group : cellGroups.keySet()) {
  472. if (!checkCellGroupAndOrder(columnOrder, group)) {
  473. cellGroups.get(group).setColspan(1);
  474. } else {
  475. int colSpan = group.size();
  476. cellGroups.get(group).setColspan(colSpan);
  477. }
  478. }
  479. }
  480. private boolean checkCellGroupAndOrder(
  481. List<Column<?, ?>> columnOrder, Set<Column<?, ?>> cellGroup) {
  482. if (!columnOrder.containsAll(cellGroup)) {
  483. return false;
  484. }
  485. for (int i = 0; i < columnOrder.size(); ++i) {
  486. if (!cellGroup.contains(columnOrder.get(i))) {
  487. continue;
  488. }
  489. for (int j = 1; j < cellGroup.size(); ++j) {
  490. if (!cellGroup.contains(columnOrder.get(i + j))) {
  491. return false;
  492. }
  493. }
  494. return true;
  495. }
  496. return false;
  497. }
  498. protected void addCell(Column<?, ?> column) {
  499. CELLTYPE cell = createCell();
  500. cell.setSection(getSection());
  501. cells.put(column, cell);
  502. }
  503. protected void removeCell(Column<?, ?> column) {
  504. cells.remove(column);
  505. }
  506. protected abstract CELLTYPE createCell();
  507. protected StaticSection<?> getSection() {
  508. return section;
  509. }
  510. protected void setSection(StaticSection<?> section) {
  511. this.section = section;
  512. }
  513. /**
  514. * Returns the custom style name for this row.
  515. *
  516. * @return the style name or null if no style name has been set
  517. */
  518. public String getStyleName() {
  519. return styleName;
  520. }
  521. /**
  522. * Sets a custom style name for this row.
  523. *
  524. * @param styleName
  525. * the style name to set or null to not use any style
  526. * name
  527. */
  528. public void setStyleName(String styleName) {
  529. this.styleName = styleName;
  530. section.requestSectionRefresh();
  531. }
  532. }
  533. private Grid<?> grid;
  534. private List<ROWTYPE> rows = new ArrayList<ROWTYPE>();
  535. private boolean visible = true;
  536. /**
  537. * Creates and returns a new instance of the row type.
  538. *
  539. * @return the created row
  540. */
  541. protected abstract ROWTYPE createRow();
  542. /**
  543. * Informs the grid that this section should be re-rendered.
  544. * <p>
  545. * <b>Note</b> that re-render means calling update() on each cell,
  546. * preAttach()/postAttach()/preDetach()/postDetach() is not called as
  547. * the cells are not removed from the DOM.
  548. */
  549. protected abstract void requestSectionRefresh();
  550. /**
  551. * Sets the visibility of the whole section.
  552. *
  553. * @param visible
  554. * true to show this section, false to hide
  555. */
  556. public void setVisible(boolean visible) {
  557. this.visible = visible;
  558. requestSectionRefresh();
  559. }
  560. /**
  561. * Returns the visibility of this section.
  562. *
  563. * @return true if visible, false otherwise.
  564. */
  565. public boolean isVisible() {
  566. return visible;
  567. }
  568. /**
  569. * Inserts a new row at the given position. Shifts the row currently at
  570. * that position and any subsequent rows down (adds one to their
  571. * indices).
  572. *
  573. * @param index
  574. * the position at which to insert the row
  575. * @return the new row
  576. *
  577. * @throws IndexOutOfBoundsException
  578. * if the index is out of bounds
  579. * @see #appendRow()
  580. * @see #prependRow()
  581. * @see #removeRow(int)
  582. * @see #removeRow(StaticRow)
  583. */
  584. public ROWTYPE addRowAt(int index) {
  585. ROWTYPE row = createRow();
  586. row.setSection(this);
  587. for (int i = 0; i < getGrid().getColumnCount(); ++i) {
  588. row.addCell(grid.getColumn(i));
  589. }
  590. rows.add(index, row);
  591. requestSectionRefresh();
  592. return row;
  593. }
  594. /**
  595. * Adds a new row at the top of this section.
  596. *
  597. * @return the new row
  598. * @see #appendRow()
  599. * @see #addRowAt(int)
  600. * @see #removeRow(int)
  601. * @see #removeRow(StaticRow)
  602. */
  603. public ROWTYPE prependRow() {
  604. return addRowAt(0);
  605. }
  606. /**
  607. * Adds a new row at the bottom of this section.
  608. *
  609. * @return the new row
  610. * @see #prependRow()
  611. * @see #addRowAt(int)
  612. * @see #removeRow(int)
  613. * @see #removeRow(StaticRow)
  614. */
  615. public ROWTYPE appendRow() {
  616. return addRowAt(rows.size());
  617. }
  618. /**
  619. * Removes the row at the given position.
  620. *
  621. * @param index
  622. * the position of the row
  623. *
  624. * @throws IndexOutOfBoundsException
  625. * if the index is out of bounds
  626. * @see #addRowAt(int)
  627. * @see #appendRow()
  628. * @see #prependRow()
  629. * @see #removeRow(StaticRow)
  630. */
  631. public void removeRow(int index) {
  632. rows.remove(index);
  633. requestSectionRefresh();
  634. }
  635. /**
  636. * Removes the given row from the section.
  637. *
  638. * @param row
  639. * the row to be removed
  640. *
  641. * @throws IllegalArgumentException
  642. * if the row does not exist in this section
  643. * @see #addRowAt(int)
  644. * @see #appendRow()
  645. * @see #prependRow()
  646. * @see #removeRow(int)
  647. */
  648. public void removeRow(ROWTYPE row) {
  649. try {
  650. removeRow(rows.indexOf(row));
  651. } catch (IndexOutOfBoundsException e) {
  652. throw new IllegalArgumentException(
  653. "Section does not contain the given row");
  654. }
  655. }
  656. /**
  657. * Returns the row at the given position.
  658. *
  659. * @param index
  660. * the position of the row
  661. * @return the row with the given index
  662. *
  663. * @throws IndexOutOfBoundsException
  664. * if the index is out of bounds
  665. */
  666. public ROWTYPE getRow(int index) {
  667. try {
  668. return rows.get(index);
  669. } catch (IndexOutOfBoundsException e) {
  670. throw new IllegalArgumentException("Row with index " + index
  671. + " does not exist");
  672. }
  673. }
  674. /**
  675. * Returns the number of rows in this section.
  676. *
  677. * @return the number of rows
  678. */
  679. public int getRowCount() {
  680. return rows.size();
  681. }
  682. protected List<ROWTYPE> getRows() {
  683. return rows;
  684. }
  685. protected int getVisibleRowCount() {
  686. return isVisible() ? getRowCount() : 0;
  687. }
  688. protected void addColumn(Column<?, ?> column) {
  689. for (ROWTYPE row : rows) {
  690. row.addCell(column);
  691. }
  692. }
  693. protected void removeColumn(Column<?, ?> column) {
  694. for (ROWTYPE row : rows) {
  695. row.removeCell(column);
  696. }
  697. }
  698. protected void setGrid(Grid<?> grid) {
  699. this.grid = grid;
  700. }
  701. protected Grid<?> getGrid() {
  702. assert grid != null;
  703. return grid;
  704. }
  705. }
  706. /**
  707. * Represents the header section of a Grid. A header consists of a single
  708. * header row containing a header cell for each column. Each cell has a
  709. * simple textual caption.
  710. */
  711. protected static class Header extends StaticSection<HeaderRow> {
  712. private HeaderRow defaultRow;
  713. private boolean markAsDirty = false;
  714. @Override
  715. public void removeRow(int index) {
  716. HeaderRow removedRow = getRow(index);
  717. super.removeRow(index);
  718. if (removedRow == defaultRow) {
  719. setDefaultRow(null);
  720. }
  721. }
  722. /**
  723. * Sets the default row of this header. The default row is a special
  724. * header row providing a user interface for sorting columns.
  725. *
  726. * @param row
  727. * the new default row, or null for no default row
  728. *
  729. * @throws IllegalArgumentException
  730. * this header does not contain the row
  731. */
  732. public void setDefaultRow(HeaderRow row) {
  733. if (row == defaultRow) {
  734. return;
  735. }
  736. if (row != null && !getRows().contains(row)) {
  737. throw new IllegalArgumentException(
  738. "Cannot set a default row that does not exist in the container");
  739. }
  740. if (defaultRow != null) {
  741. defaultRow.setDefault(false);
  742. }
  743. if (row != null) {
  744. row.setDefault(true);
  745. }
  746. defaultRow = row;
  747. requestSectionRefresh();
  748. }
  749. /**
  750. * Returns the current default row of this header. The default row is a
  751. * special header row providing a user interface for sorting columns.
  752. *
  753. * @return the default row or null if no default row set
  754. */
  755. public HeaderRow getDefaultRow() {
  756. return defaultRow;
  757. }
  758. @Override
  759. protected HeaderRow createRow() {
  760. return new HeaderRow();
  761. }
  762. @Override
  763. protected void requestSectionRefresh() {
  764. markAsDirty = true;
  765. /*
  766. * Defer the refresh so if we multiple times call refreshSection()
  767. * (for example when updating cell values) we only get one actual
  768. * refresh in the end.
  769. */
  770. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  771. @Override
  772. public void execute() {
  773. if (markAsDirty) {
  774. markAsDirty = false;
  775. getGrid().refreshHeader();
  776. }
  777. }
  778. });
  779. }
  780. /**
  781. * Returns the events consumed by the header
  782. *
  783. * @return a collection of BrowserEvents
  784. */
  785. public Collection<String> getConsumedEvents() {
  786. return Arrays.asList(BrowserEvents.TOUCHSTART,
  787. BrowserEvents.TOUCHMOVE, BrowserEvents.TOUCHEND,
  788. BrowserEvents.TOUCHCANCEL, BrowserEvents.CLICK);
  789. }
  790. }
  791. /**
  792. * A single row in a grid header section.
  793. *
  794. */
  795. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  796. private boolean isDefault = false;
  797. protected void setDefault(boolean isDefault) {
  798. this.isDefault = isDefault;
  799. }
  800. public boolean isDefault() {
  801. return isDefault;
  802. }
  803. @Override
  804. protected HeaderCell createCell() {
  805. return new HeaderCell();
  806. }
  807. }
  808. /**
  809. * A single cell in a grid header row. Has a textual caption.
  810. *
  811. */
  812. public static class HeaderCell extends StaticSection.StaticCell {
  813. }
  814. /**
  815. * Represents the footer section of a Grid. The footer is always empty.
  816. */
  817. protected static class Footer extends StaticSection<FooterRow> {
  818. private boolean markAsDirty = false;
  819. @Override
  820. protected FooterRow createRow() {
  821. return new FooterRow();
  822. }
  823. @Override
  824. protected void requestSectionRefresh() {
  825. markAsDirty = true;
  826. /*
  827. * Defer the refresh so if we multiple times call refreshSection()
  828. * (for example when updating cell values) we only get one actual
  829. * refresh in the end.
  830. */
  831. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  832. @Override
  833. public void execute() {
  834. if (markAsDirty) {
  835. markAsDirty = false;
  836. getGrid().refreshFooter();
  837. }
  838. }
  839. });
  840. }
  841. }
  842. /**
  843. * A single cell in a grid Footer row. Has a textual caption.
  844. *
  845. */
  846. public static class FooterCell extends StaticSection.StaticCell {
  847. }
  848. /**
  849. * A single row in a grid Footer section.
  850. *
  851. */
  852. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  853. @Override
  854. protected FooterCell createCell() {
  855. return new FooterCell();
  856. }
  857. }
  858. private static class EditorRequestImpl<T> implements EditorRequest<T> {
  859. /**
  860. * A callback interface used to notify the invoker of the editor handler
  861. * of completed editor requests.
  862. *
  863. * @param <T>
  864. * the row data type
  865. */
  866. public static interface RequestCallback<T> {
  867. /**
  868. * The method that must be called when the request has been
  869. * processed correctly.
  870. *
  871. * @param request
  872. * the original request object
  873. */
  874. public void onSuccess(EditorRequest<T> request);
  875. /**
  876. * The method that must be called when processing the request has
  877. * produced an aborting error.
  878. *
  879. * @param request
  880. * the original request object
  881. */
  882. public void onError(EditorRequest<T> request);
  883. }
  884. private Grid<T> grid;
  885. private int rowIndex;
  886. private RequestCallback<T> callback;
  887. private boolean completed = false;
  888. public EditorRequestImpl(Grid<T> grid, int rowIndex,
  889. RequestCallback<T> callback) {
  890. this.grid = grid;
  891. this.rowIndex = rowIndex;
  892. this.callback = callback;
  893. }
  894. @Override
  895. public int getRowIndex() {
  896. return rowIndex;
  897. }
  898. @Override
  899. public T getRow() {
  900. return grid.getDataSource().getRow(rowIndex);
  901. }
  902. @Override
  903. public Grid<T> getGrid() {
  904. return grid;
  905. }
  906. @Override
  907. public Widget getWidget(Grid.Column<?, T> column) {
  908. Widget w = grid.getEditorWidget(column);
  909. assert w != null;
  910. return w;
  911. }
  912. private void complete(String errorMessage,
  913. Collection<Column<?, T>> errorColumns) {
  914. if (completed) {
  915. throw new IllegalStateException(
  916. "An EditorRequest must be completed exactly once");
  917. }
  918. completed = true;
  919. grid.getEditor().setErrorMessage(errorMessage);
  920. grid.getEditor().clearEditorColumnErrors();
  921. if (errorColumns != null) {
  922. for (Column<?, T> column : errorColumns) {
  923. grid.getEditor().setEditorColumnError(column, true);
  924. }
  925. }
  926. }
  927. @Override
  928. public void success() {
  929. complete(null, null);
  930. if (callback != null) {
  931. callback.onSuccess(this);
  932. }
  933. }
  934. @Override
  935. public void failure(String errorMessage,
  936. Collection<Grid.Column<?, T>> errorColumns) {
  937. complete(errorMessage, errorColumns);
  938. if (callback != null) {
  939. callback.onError(this);
  940. }
  941. }
  942. @Override
  943. public boolean isCompleted() {
  944. return completed;
  945. }
  946. }
  947. /**
  948. * An editor UI for Grid rows. A single Grid row at a time can be opened for
  949. * editing.
  950. */
  951. protected static class Editor<T> {
  952. public static final int KEYCODE_SHOW = KeyCodes.KEY_ENTER;
  953. public static final int KEYCODE_HIDE = KeyCodes.KEY_ESCAPE;
  954. private static final String ERROR_CLASS_NAME = "error";
  955. protected enum State {
  956. INACTIVE, ACTIVATING, BINDING, ACTIVE, SAVING
  957. }
  958. private Grid<T> grid;
  959. private EditorHandler<T> handler;
  960. private DivElement editorOverlay = DivElement.as(DOM.createDiv());
  961. private DivElement cellWrapper = DivElement.as(DOM.createDiv());
  962. private DivElement messageAndButtonsWrapper = DivElement.as(DOM
  963. .createDiv());
  964. private DivElement messageWrapper = DivElement.as(DOM.createDiv());
  965. private DivElement buttonsWrapper = DivElement.as(DOM.createDiv());
  966. // Element which contains the error message for the editor
  967. // Should only be added to the DOM when there's a message to show
  968. private DivElement message = DivElement.as(DOM.createDiv());
  969. private Map<Column<?, T>, Widget> columnToWidget = new HashMap<Column<?, T>, Widget>();
  970. private boolean enabled = false;
  971. private State state = State.INACTIVE;
  972. private int rowIndex = -1;
  973. private String styleName = null;
  974. private HandlerRegistration scrollHandler;
  975. private final Button saveButton;
  976. private final Button cancelButton;
  977. private static final int SAVE_TIMEOUT_MS = 5000;
  978. private final Timer saveTimeout = new Timer() {
  979. @Override
  980. public void run() {
  981. getLogger().warning(
  982. "Editor save action is taking longer than expected ("
  983. + SAVE_TIMEOUT_MS + "ms). Does your "
  984. + EditorHandler.class.getSimpleName()
  985. + " remember to call success() or fail()?");
  986. }
  987. };
  988. private final EditorRequestImpl.RequestCallback<T> saveRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  989. @Override
  990. public void onSuccess(EditorRequest<T> request) {
  991. if (state == State.SAVING) {
  992. cleanup();
  993. cancel();
  994. }
  995. }
  996. @Override
  997. public void onError(EditorRequest<T> request) {
  998. if (state == State.SAVING) {
  999. cleanup();
  1000. // TODO probably not the most correct thing to do...
  1001. getLogger().warning(
  1002. "An error occurred when trying to save the "
  1003. + "modified row");
  1004. }
  1005. }
  1006. private void cleanup() {
  1007. state = State.ACTIVE;
  1008. setButtonsEnabled(true);
  1009. saveTimeout.cancel();
  1010. }
  1011. };
  1012. private static final int BIND_TIMEOUT_MS = 5000;
  1013. private final Timer bindTimeout = new Timer() {
  1014. @Override
  1015. public void run() {
  1016. getLogger().warning(
  1017. "Editor bind action is taking longer than expected ("
  1018. + BIND_TIMEOUT_MS + "ms). Does your "
  1019. + EditorHandler.class.getSimpleName()
  1020. + " remember to call success() or fail()?");
  1021. }
  1022. };
  1023. private final EditorRequestImpl.RequestCallback<T> bindRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  1024. @Override
  1025. public void onSuccess(EditorRequest<T> request) {
  1026. if (state == State.BINDING) {
  1027. state = State.ACTIVE;
  1028. bindTimeout.cancel();
  1029. showOverlay(grid.getEscalator().getBody()
  1030. .getRowElement(request.getRowIndex()));
  1031. }
  1032. }
  1033. @Override
  1034. public void onError(EditorRequest<T> request) {
  1035. if (state == State.BINDING) {
  1036. state = State.INACTIVE;
  1037. bindTimeout.cancel();
  1038. // TODO show something in the DOM as well?
  1039. getLogger().warning(
  1040. "An error occurred while trying to show the "
  1041. + "Grid editor");
  1042. grid.getEscalator().setScrollLocked(Direction.VERTICAL,
  1043. false);
  1044. }
  1045. }
  1046. };
  1047. /** A set of all the columns that display an error flag. */
  1048. private final Set<Column<?, T>> columnErrors = new HashSet<Grid.Column<?, T>>();
  1049. public Editor() {
  1050. saveButton = new Button();
  1051. saveButton.setText(GridConstants.DEFAULT_SAVE_CAPTION);
  1052. saveButton.addClickHandler(new ClickHandler() {
  1053. @Override
  1054. public void onClick(ClickEvent event) {
  1055. save();
  1056. }
  1057. });
  1058. cancelButton = new Button();
  1059. cancelButton.setText(GridConstants.DEFAULT_CANCEL_CAPTION);
  1060. cancelButton.addClickHandler(new ClickHandler() {
  1061. @Override
  1062. public void onClick(ClickEvent event) {
  1063. cancel();
  1064. }
  1065. });
  1066. }
  1067. public void setErrorMessage(String errorMessage) {
  1068. if (errorMessage == null) {
  1069. message.removeFromParent();
  1070. } else {
  1071. message.setInnerText(errorMessage);
  1072. if (message.getParentElement() == null) {
  1073. messageWrapper.appendChild(message);
  1074. }
  1075. }
  1076. }
  1077. public int getRow() {
  1078. return rowIndex;
  1079. }
  1080. /**
  1081. * Opens the editor over the row with the given index.
  1082. *
  1083. * @param rowIndex
  1084. * the index of the row to be edited
  1085. *
  1086. * @throws IllegalStateException
  1087. * if this editor is not enabled
  1088. * @throws IllegalStateException
  1089. * if this editor is already in edit mode
  1090. */
  1091. public void editRow(int rowIndex) {
  1092. if (!enabled) {
  1093. throw new IllegalStateException(
  1094. "Cannot edit row: editor is not enabled");
  1095. }
  1096. if (state != State.INACTIVE) {
  1097. throw new IllegalStateException(
  1098. "Cannot edit row: editor already in edit mode");
  1099. }
  1100. this.rowIndex = rowIndex;
  1101. state = State.ACTIVATING;
  1102. if (grid.getEscalator().getVisibleRowRange().contains(rowIndex)) {
  1103. show();
  1104. } else {
  1105. grid.scrollToRow(rowIndex, ScrollDestination.MIDDLE);
  1106. }
  1107. }
  1108. /**
  1109. * Cancels the currently active edit and hides the editor. Any changes
  1110. * that are not {@link #save() saved} are lost.
  1111. *
  1112. * @throws IllegalStateException
  1113. * if this editor is not enabled
  1114. * @throws IllegalStateException
  1115. * if this editor is not in edit mode
  1116. */
  1117. public void cancel() {
  1118. if (!enabled) {
  1119. throw new IllegalStateException(
  1120. "Cannot cancel edit: editor is not enabled");
  1121. }
  1122. if (state == State.INACTIVE) {
  1123. throw new IllegalStateException(
  1124. "Cannot cancel edit: editor is not in edit mode");
  1125. }
  1126. hideOverlay();
  1127. grid.getEscalator().setScrollLocked(Direction.VERTICAL, false);
  1128. EditorRequest<T> request = new EditorRequestImpl<T>(grid, rowIndex,
  1129. null);
  1130. handler.cancel(request);
  1131. state = State.INACTIVE;
  1132. }
  1133. /**
  1134. * Saves any unsaved changes to the data source and hides the editor.
  1135. *
  1136. * @throws IllegalStateException
  1137. * if this editor is not enabled
  1138. * @throws IllegalStateException
  1139. * if this editor is not in edit mode
  1140. */
  1141. public void save() {
  1142. if (!enabled) {
  1143. throw new IllegalStateException(
  1144. "Cannot save: editor is not enabled");
  1145. }
  1146. if (state != State.ACTIVE) {
  1147. throw new IllegalStateException(
  1148. "Cannot save: editor is not in edit mode");
  1149. }
  1150. state = State.SAVING;
  1151. setButtonsEnabled(false);
  1152. saveTimeout.schedule(SAVE_TIMEOUT_MS);
  1153. EditorRequest<T> request = new EditorRequestImpl<T>(grid, rowIndex,
  1154. saveRequestCallback);
  1155. handler.save(request);
  1156. }
  1157. /**
  1158. * Returns the handler responsible for binding data and editor widgets
  1159. * to this editor.
  1160. *
  1161. * @return the editor handler or null if not set
  1162. */
  1163. public EditorHandler<T> getHandler() {
  1164. return handler;
  1165. }
  1166. /**
  1167. * Sets the handler responsible for binding data and editor widgets to
  1168. * this editor.
  1169. *
  1170. * @param rowHandler
  1171. * the new editor handler
  1172. *
  1173. * @throws IllegalStateException
  1174. * if this editor is currently in edit mode
  1175. */
  1176. public void setHandler(EditorHandler<T> rowHandler) {
  1177. if (state != State.INACTIVE) {
  1178. throw new IllegalStateException(
  1179. "Cannot set EditorHandler: editor is currently in edit mode");
  1180. }
  1181. handler = rowHandler;
  1182. }
  1183. public boolean isEnabled() {
  1184. return enabled;
  1185. }
  1186. /**
  1187. * Sets the enabled state of this editor.
  1188. *
  1189. * @param enabled
  1190. * true if enabled, false otherwise
  1191. *
  1192. * @throws IllegalStateException
  1193. * if in edit mode and trying to disable
  1194. * @throws IllegalStateException
  1195. * if the editor handler is not set
  1196. */
  1197. public void setEnabled(boolean enabled) {
  1198. if (enabled == false && state != State.INACTIVE) {
  1199. throw new IllegalStateException(
  1200. "Cannot disable: editor is in edit mode");
  1201. } else if (enabled == true && getHandler() == null) {
  1202. throw new IllegalStateException(
  1203. "Cannot enable: EditorHandler not set");
  1204. }
  1205. this.enabled = enabled;
  1206. }
  1207. protected void show() {
  1208. if (state == State.ACTIVATING) {
  1209. state = State.BINDING;
  1210. bindTimeout.schedule(BIND_TIMEOUT_MS);
  1211. EditorRequest<T> request = new EditorRequestImpl<T>(grid,
  1212. rowIndex, bindRequestCallback);
  1213. handler.bind(request);
  1214. grid.getEscalator().setScrollLocked(Direction.VERTICAL, true);
  1215. }
  1216. }
  1217. protected void setGrid(final Grid<T> grid) {
  1218. assert grid != null : "Grid cannot be null";
  1219. assert this.grid == null : "Can only attach editor to Grid once";
  1220. this.grid = grid;
  1221. grid.addDataAvailableHandler(new DataAvailableHandler() {
  1222. @Override
  1223. public void onDataAvailable(DataAvailableEvent event) {
  1224. if (event.getAvailableRows().contains(rowIndex)) {
  1225. show();
  1226. }
  1227. }
  1228. });
  1229. }
  1230. protected State getState() {
  1231. return state;
  1232. }
  1233. protected void setState(State state) {
  1234. this.state = state;
  1235. }
  1236. /**
  1237. * Returns the editor widget associated with the given column. If the
  1238. * editor is not active or the column is not
  1239. * {@link Grid.Column#isEditable() editable}, returns null.
  1240. *
  1241. * @param column
  1242. * the column
  1243. * @return the widget if the editor is open and the column is editable,
  1244. * null otherwise
  1245. */
  1246. protected Widget getWidget(Column<?, T> column) {
  1247. return columnToWidget.get(column);
  1248. }
  1249. /**
  1250. * Opens the editor overlay over the given table row.
  1251. *
  1252. * @param tr
  1253. * the row to be edited
  1254. */
  1255. protected void showOverlay(TableRowElement tr) {
  1256. DivElement gridElement = DivElement.as(grid.getElement());
  1257. scrollHandler = grid.addScrollHandler(new ScrollHandler() {
  1258. @Override
  1259. public void onScroll(ScrollEvent event) {
  1260. updateHorizontalScrollPosition();
  1261. }
  1262. });
  1263. gridElement.appendChild(editorOverlay);
  1264. editorOverlay.appendChild(cellWrapper);
  1265. editorOverlay.appendChild(messageAndButtonsWrapper);
  1266. for (int i = 0; i < tr.getCells().getLength(); i++) {
  1267. Element cell = createCell(tr.getCells().getItem(i));
  1268. cellWrapper.appendChild(cell);
  1269. Column<?, T> column = grid.getColumn(i);
  1270. if (column.isEditable()) {
  1271. Widget editor = getHandler().getWidget(column);
  1272. if (editor != null) {
  1273. columnToWidget.put(column, editor);
  1274. attachWidget(editor, cell);
  1275. }
  1276. }
  1277. }
  1278. // Only add these elements once
  1279. if (!messageAndButtonsWrapper.isOrHasChild(messageWrapper)) {
  1280. messageAndButtonsWrapper.appendChild(messageWrapper);
  1281. messageAndButtonsWrapper.appendChild(buttonsWrapper);
  1282. }
  1283. attachWidget(saveButton, buttonsWrapper);
  1284. attachWidget(cancelButton, buttonsWrapper);
  1285. updateHorizontalScrollPosition();
  1286. AbstractRowContainer body = (AbstractRowContainer) grid
  1287. .getEscalator().getBody();
  1288. double rowTop = body.getRowTop(tr);
  1289. int bodyTop = body.getElement().getAbsoluteTop();
  1290. int gridTop = gridElement.getAbsoluteTop();
  1291. double overlayTop = rowTop + bodyTop - gridTop;
  1292. if (buttonsShouldBeRenderedBelow(tr)) {
  1293. // Default case, editor buttons are below the edited row
  1294. editorOverlay.getStyle().setTop(overlayTop, Unit.PX);
  1295. editorOverlay.getStyle().clearBottom();
  1296. } else {
  1297. // Move message and buttons wrapper on top of cell wrapper if
  1298. // there is not enough space visible space under and fix the
  1299. // overlay from the bottom
  1300. editorOverlay.appendChild(cellWrapper);
  1301. int gridHeight = grid.getElement().getOffsetHeight();
  1302. editorOverlay.getStyle()
  1303. .setBottom(
  1304. gridHeight - overlayTop - tr.getOffsetHeight(),
  1305. Unit.PX);
  1306. editorOverlay.getStyle().clearTop();
  1307. }
  1308. // Do not render over the vertical scrollbar
  1309. int nativeScrollbarSize = WidgetUtil.getNativeScrollbarSize();
  1310. if (nativeScrollbarSize > 0) {
  1311. editorOverlay.getStyle().setRight(nativeScrollbarSize, Unit.PX);
  1312. }
  1313. }
  1314. private boolean buttonsShouldBeRenderedBelow(TableRowElement tr) {
  1315. TableSectionElement tfoot = grid.escalator.getFooter().getElement();
  1316. double tfootPageTop = WidgetUtil.getBoundingClientRect(tfoot)
  1317. .getTop();
  1318. double trPageBottom = WidgetUtil.getBoundingClientRect(tr)
  1319. .getBottom();
  1320. int messageAndButtonsHeight = messageAndButtonsWrapper
  1321. .getOffsetHeight();
  1322. double bottomOfButtons = trPageBottom + messageAndButtonsHeight;
  1323. return bottomOfButtons < tfootPageTop;
  1324. }
  1325. protected void hideOverlay() {
  1326. for (Widget w : columnToWidget.values()) {
  1327. setParent(w, null);
  1328. }
  1329. columnToWidget.clear();
  1330. detachWidget(saveButton);
  1331. detachWidget(cancelButton);
  1332. editorOverlay.removeAllChildren();
  1333. cellWrapper.removeAllChildren();
  1334. editorOverlay.removeFromParent();
  1335. scrollHandler.removeHandler();
  1336. clearEditorColumnErrors();
  1337. }
  1338. protected void setStylePrimaryName(String primaryName) {
  1339. if (styleName != null) {
  1340. editorOverlay.removeClassName(styleName);
  1341. cellWrapper.removeClassName(styleName + "-cells");
  1342. messageAndButtonsWrapper.removeClassName(styleName + "-footer");
  1343. messageWrapper.removeClassName(styleName + "-message");
  1344. buttonsWrapper.removeClassName(styleName + "-buttons");
  1345. saveButton.removeStyleName(styleName + "-save");
  1346. cancelButton.removeStyleName(styleName + "-cancel");
  1347. }
  1348. styleName = primaryName + "-editor";
  1349. editorOverlay.setClassName(styleName);
  1350. cellWrapper.setClassName(styleName + "-cells");
  1351. messageAndButtonsWrapper.setClassName(styleName + "-footer");
  1352. messageWrapper.setClassName(styleName + "-message");
  1353. buttonsWrapper.setClassName(styleName + "-buttons");
  1354. saveButton.setStyleName(styleName + "-save");
  1355. cancelButton.setStyleName(styleName + "-cancel");
  1356. }
  1357. /**
  1358. * Creates an editor cell corresponding to the given table cell. The
  1359. * returned element is empty and has the same dimensions and position as
  1360. * the table cell.
  1361. *
  1362. * @param td
  1363. * the table cell used as a reference
  1364. * @return an editor cell corresponding to the given cell
  1365. */
  1366. protected Element createCell(TableCellElement td) {
  1367. DivElement cell = DivElement.as(DOM.createDiv());
  1368. double width = WidgetUtil
  1369. .getRequiredWidthBoundingClientRectDouble(td);
  1370. double height = WidgetUtil
  1371. .getRequiredHeightBoundingClientRectDouble(td);
  1372. setBounds(cell, td.getOffsetLeft(), td.getOffsetTop(), width,
  1373. height);
  1374. return cell;
  1375. }
  1376. private void attachWidget(Widget w, Element parent) {
  1377. parent.appendChild(w.getElement());
  1378. setParent(w, grid);
  1379. }
  1380. private void detachWidget(Widget w) {
  1381. setParent(w, null);
  1382. w.getElement().removeFromParent();
  1383. }
  1384. private static void setBounds(Element e, double left, double top,
  1385. double width, double height) {
  1386. Style style = e.getStyle();
  1387. style.setLeft(left, Unit.PX);
  1388. style.setTop(top, Unit.PX);
  1389. style.setWidth(width, Unit.PX);
  1390. style.setHeight(height, Unit.PX);
  1391. }
  1392. private void updateHorizontalScrollPosition() {
  1393. double scrollLeft = grid.getScrollLeft();
  1394. cellWrapper.getStyle().setLeft(-scrollLeft, Unit.PX);
  1395. }
  1396. protected void setGridEnabled(boolean enabled) {
  1397. // TODO: This should be informed to handler as well so possible
  1398. // fields can be disabled.
  1399. setButtonsEnabled(enabled);
  1400. }
  1401. private void setButtonsEnabled(boolean enabled) {
  1402. saveButton.setEnabled(enabled);
  1403. cancelButton.setEnabled(enabled);
  1404. }
  1405. public void setSaveCaption(String saveCaption)
  1406. throws IllegalArgumentException {
  1407. if (saveCaption == null) {
  1408. throw new IllegalArgumentException(
  1409. "Save caption cannot be null");
  1410. }
  1411. saveButton.setText(saveCaption);
  1412. }
  1413. public String getSaveCaption() {
  1414. return saveButton.getText();
  1415. }
  1416. public void setCancelCaption(String cancelCaption)
  1417. throws IllegalArgumentException {
  1418. if (cancelCaption == null) {
  1419. throw new IllegalArgumentException(
  1420. "Cancel caption cannot be null");
  1421. }
  1422. cancelButton.setText(cancelCaption);
  1423. }
  1424. public String getCancelCaption() {
  1425. return cancelButton.getText();
  1426. }
  1427. public void setEditorColumnError(Column<?, T> column, boolean hasError) {
  1428. if (state != State.ACTIVE && state != State.SAVING) {
  1429. throw new IllegalStateException("Cannot set cell error "
  1430. + "status: editor is neither active nor saving.");
  1431. }
  1432. if (isEditorColumnError(column) == hasError) {
  1433. return;
  1434. }
  1435. Element editorCell = getWidget(column).getElement()
  1436. .getParentElement();
  1437. if (hasError) {
  1438. editorCell.addClassName(ERROR_CLASS_NAME);
  1439. columnErrors.add(column);
  1440. } else {
  1441. editorCell.removeClassName(ERROR_CLASS_NAME);
  1442. columnErrors.remove(column);
  1443. }
  1444. }
  1445. public void clearEditorColumnErrors() {
  1446. /*
  1447. * editorOverlay has no children if it's not active, effectively
  1448. * making this loop a NOOP.
  1449. */
  1450. Element e = editorOverlay.getFirstChildElement();
  1451. while (e != null) {
  1452. e.removeClassName(ERROR_CLASS_NAME);
  1453. e = e.getNextSiblingElement();
  1454. }
  1455. columnErrors.clear();
  1456. }
  1457. public boolean isEditorColumnError(Column<?, T> column) {
  1458. return columnErrors.contains(column);
  1459. }
  1460. }
  1461. public static abstract class AbstractGridKeyEvent<HANDLER extends AbstractGridKeyEventHandler>
  1462. extends KeyEvent<HANDLER> {
  1463. private Grid<?> grid;
  1464. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  1465. getBrowserEventType(), this);
  1466. private final CellReference<?> targetCell;
  1467. public AbstractGridKeyEvent(Grid<?> grid, CellReference<?> targetCell) {
  1468. this.grid = grid;
  1469. this.targetCell = targetCell;
  1470. }
  1471. protected abstract String getBrowserEventType();
  1472. /**
  1473. * Gets the Grid instance for this event.
  1474. *
  1475. * @return grid
  1476. */
  1477. public Grid<?> getGrid() {
  1478. return grid;
  1479. }
  1480. /**
  1481. * Gets the focused cell for this event.
  1482. *
  1483. * @return focused cell
  1484. */
  1485. public CellReference<?> getFocusedCell() {
  1486. return targetCell;
  1487. }
  1488. @Override
  1489. protected void dispatch(HANDLER handler) {
  1490. EventTarget target = getNativeEvent().getEventTarget();
  1491. if (Element.is(target)
  1492. && !grid.isElementInChildWidget(Element.as(target))) {
  1493. Section section = Section.FOOTER;
  1494. final RowContainer container = grid.cellFocusHandler.containerWithFocus;
  1495. if (container == grid.escalator.getHeader()) {
  1496. section = Section.HEADER;
  1497. } else if (container == grid.escalator.getBody()) {
  1498. section = Section.BODY;
  1499. }
  1500. doDispatch(handler, section);
  1501. }
  1502. }
  1503. protected abstract void doDispatch(HANDLER handler, Section section);
  1504. @Override
  1505. public Type<HANDLER> getAssociatedType() {
  1506. return associatedType;
  1507. }
  1508. }
  1509. public static abstract class AbstractGridMouseEvent<HANDLER extends AbstractGridMouseEventHandler>
  1510. extends MouseEvent<HANDLER> {
  1511. private Grid<?> grid;
  1512. private final CellReference<?> targetCell;
  1513. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  1514. getBrowserEventType(), this);
  1515. public AbstractGridMouseEvent(Grid<?> grid, CellReference<?> targetCell) {
  1516. this.grid = grid;
  1517. this.targetCell = targetCell;
  1518. }
  1519. protected abstract String getBrowserEventType();
  1520. /**
  1521. * Gets the Grid instance for this event.
  1522. *
  1523. * @return grid
  1524. */
  1525. public Grid<?> getGrid() {
  1526. return grid;
  1527. }
  1528. /**
  1529. * Gets the reference of target cell for this event.
  1530. *
  1531. * @return target cell
  1532. */
  1533. public CellReference<?> getTargetCell() {
  1534. return targetCell;
  1535. }
  1536. @Override
  1537. protected void dispatch(HANDLER handler) {
  1538. EventTarget target = getNativeEvent().getEventTarget();
  1539. if (!Element.is(target)) {
  1540. // Target is not an element
  1541. return;
  1542. }
  1543. Element targetElement = Element.as(target);
  1544. if (grid.isElementInChildWidget(targetElement)) {
  1545. // Target is some widget inside of Grid
  1546. return;
  1547. }
  1548. final RowContainer container = grid.escalator
  1549. .findRowContainer(targetElement);
  1550. if (container == null) {
  1551. // No container for given element
  1552. return;
  1553. }
  1554. Section section = Section.FOOTER;
  1555. if (container == grid.escalator.getHeader()) {
  1556. section = Section.HEADER;
  1557. } else if (container == grid.escalator.getBody()) {
  1558. section = Section.BODY;
  1559. }
  1560. doDispatch(handler, section);
  1561. }
  1562. protected abstract void doDispatch(HANDLER handler, Section section);
  1563. @Override
  1564. public Type<HANDLER> getAssociatedType() {
  1565. return associatedType;
  1566. }
  1567. }
  1568. private static final String CUSTOM_STYLE_PROPERTY_NAME = "customStyle";
  1569. private EventCellReference<T> eventCell = new EventCellReference<T>(this);
  1570. private GridKeyDownEvent keyDown = new GridKeyDownEvent(this, eventCell);
  1571. private GridKeyUpEvent keyUp = new GridKeyUpEvent(this, eventCell);
  1572. private GridKeyPressEvent keyPress = new GridKeyPressEvent(this, eventCell);
  1573. private GridClickEvent clickEvent = new GridClickEvent(this, eventCell);
  1574. private GridDoubleClickEvent doubleClickEvent = new GridDoubleClickEvent(
  1575. this, eventCell);
  1576. private class CellFocusHandler {
  1577. private RowContainer containerWithFocus = escalator.getBody();
  1578. private int rowWithFocus = 0;
  1579. private Range cellFocusRange = Range.withLength(0, 1);
  1580. private int lastFocusedBodyRow = 0;
  1581. private int lastFocusedHeaderRow = 0;
  1582. private int lastFocusedFooterRow = 0;
  1583. private TableCellElement cellWithFocusStyle = null;
  1584. private TableRowElement rowWithFocusStyle = null;
  1585. public CellFocusHandler() {
  1586. sinkEvents(getNavigationEvents());
  1587. }
  1588. private Cell getFocusedCell() {
  1589. return new Cell(rowWithFocus, cellFocusRange.getStart(),
  1590. cellWithFocusStyle);
  1591. }
  1592. /**
  1593. * Sets style names for given cell when needed.
  1594. */
  1595. public void updateFocusedCellStyle(FlyweightCell cell,
  1596. RowContainer cellContainer) {
  1597. int cellRow = cell.getRow();
  1598. int cellColumn = cell.getColumn();
  1599. int colSpan = cell.getColSpan();
  1600. boolean columnHasFocus = Range.withLength(cellColumn, colSpan)
  1601. .intersects(cellFocusRange);
  1602. if (cellContainer == containerWithFocus) {
  1603. // Cell is in the current container
  1604. if (cellRow == rowWithFocus && columnHasFocus) {
  1605. if (cellWithFocusStyle != cell.getElement()) {
  1606. // Cell is correct but it does not have focused style
  1607. if (cellWithFocusStyle != null) {
  1608. // Remove old focus style
  1609. setStyleName(cellWithFocusStyle,
  1610. cellFocusStyleName, false);
  1611. }
  1612. cellWithFocusStyle = cell.getElement();
  1613. // Add focus style to correct cell.
  1614. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  1615. true);
  1616. }
  1617. } else if (cellWithFocusStyle == cell.getElement()) {
  1618. // Due to escalator reusing cells, a new cell has the same
  1619. // element but is not the focused cell.
  1620. setStyleName(cellWithFocusStyle, cellFocusStyleName, false);
  1621. cellWithFocusStyle = null;
  1622. }
  1623. }
  1624. }
  1625. /**
  1626. * Sets focus style for the given row if needed.
  1627. *
  1628. * @param row
  1629. * a row object
  1630. */
  1631. public void updateFocusedRowStyle(Row row) {
  1632. if (rowWithFocus == row.getRow()
  1633. && containerWithFocus == escalator.getBody()) {
  1634. if (row.getElement() != rowWithFocusStyle) {
  1635. // Row should have focus style but does not have it.
  1636. if (rowWithFocusStyle != null) {
  1637. setStyleName(rowWithFocusStyle, rowFocusStyleName,
  1638. false);
  1639. }
  1640. rowWithFocusStyle = row.getElement();
  1641. setStyleName(rowWithFocusStyle, rowFocusStyleName, true);
  1642. }
  1643. } else if (rowWithFocusStyle == row.getElement()
  1644. || (containerWithFocus != escalator.getBody() && rowWithFocusStyle != null)) {
  1645. // Remove focus style.
  1646. setStyleName(rowWithFocusStyle, rowFocusStyleName, false);
  1647. rowWithFocusStyle = null;
  1648. }
  1649. }
  1650. /**
  1651. * Sets the currently focused.
  1652. *
  1653. * @param row
  1654. * the index of the row having focus
  1655. * @param column
  1656. * the index of the column having focus
  1657. * @param container
  1658. * the row container having focus
  1659. */
  1660. private void setCellFocus(int row, int column, RowContainer container) {
  1661. if (row == rowWithFocus && cellFocusRange.contains(column)
  1662. && container == this.containerWithFocus) {
  1663. refreshRow(rowWithFocus);
  1664. return;
  1665. }
  1666. int oldRow = rowWithFocus;
  1667. rowWithFocus = row;
  1668. Range oldRange = cellFocusRange;
  1669. if (container == escalator.getBody()) {
  1670. scrollToRow(rowWithFocus);
  1671. cellFocusRange = Range.withLength(column, 1);
  1672. } else {
  1673. int i = 0;
  1674. Element cell = container.getRowElement(rowWithFocus)
  1675. .getFirstChildElement();
  1676. do {
  1677. int colSpan = cell
  1678. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  1679. Range cellRange = Range.withLength(i, colSpan);
  1680. if (cellRange.contains(column)) {
  1681. cellFocusRange = cellRange;
  1682. break;
  1683. }
  1684. cell = cell.getNextSiblingElement();
  1685. ++i;
  1686. } while (cell != null);
  1687. }
  1688. if (column >= escalator.getColumnConfiguration()
  1689. .getFrozenColumnCount()) {
  1690. escalator.scrollToColumn(column, ScrollDestination.ANY, 10);
  1691. }
  1692. if (this.containerWithFocus == container) {
  1693. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  1694. refreshRow(oldRow);
  1695. } else {
  1696. refreshHeader();
  1697. refreshFooter();
  1698. }
  1699. } else {
  1700. RowContainer oldContainer = this.containerWithFocus;
  1701. this.containerWithFocus = container;
  1702. if (oldContainer == escalator.getBody()) {
  1703. lastFocusedBodyRow = oldRow;
  1704. } else if (oldContainer == escalator.getHeader()) {
  1705. lastFocusedHeaderRow = oldRow;
  1706. } else {
  1707. lastFocusedFooterRow = oldRow;
  1708. }
  1709. if (!oldRange.equals(cellFocusRange)) {
  1710. refreshHeader();
  1711. refreshFooter();
  1712. if (oldContainer == escalator.getBody()) {
  1713. oldContainer.refreshRows(oldRow, 1);
  1714. }
  1715. } else {
  1716. oldContainer.refreshRows(oldRow, 1);
  1717. }
  1718. }
  1719. refreshRow(rowWithFocus);
  1720. }
  1721. /**
  1722. * Sets focus on a cell.
  1723. *
  1724. * <p>
  1725. * <em>Note</em>: cell focus is not the same as JavaScript's
  1726. * {@code document.activeElement}.
  1727. *
  1728. * @param cell
  1729. * a cell object
  1730. */
  1731. public void setCellFocus(CellReference<T> cell) {
  1732. setCellFocus(cell.getRowIndex(), cell.getColumnIndex(),
  1733. escalator.findRowContainer(cell.getElement()));
  1734. }
  1735. /**
  1736. * Gets list of events that can be used for cell focusing.
  1737. *
  1738. * @return list of navigation related event types
  1739. */
  1740. public Collection<String> getNavigationEvents() {
  1741. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  1742. }
  1743. /**
  1744. * Handle events that can move the cell focus.
  1745. */
  1746. public void handleNavigationEvent(Event event, CellReference<T> cell) {
  1747. if (event.getType().equals(BrowserEvents.CLICK)) {
  1748. setCellFocus(cell);
  1749. // Grid should have focus when clicked.
  1750. getElement().focus();
  1751. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  1752. int newRow = rowWithFocus;
  1753. RowContainer newContainer = containerWithFocus;
  1754. int newColumn = cellFocusRange.getStart();
  1755. switch (event.getKeyCode()) {
  1756. case KeyCodes.KEY_DOWN:
  1757. ++newRow;
  1758. break;
  1759. case KeyCodes.KEY_UP:
  1760. --newRow;
  1761. break;
  1762. case KeyCodes.KEY_RIGHT:
  1763. if (cellFocusRange.getEnd() >= getColumns().size()) {
  1764. return;
  1765. }
  1766. newColumn = cellFocusRange.getEnd();
  1767. break;
  1768. case KeyCodes.KEY_LEFT:
  1769. if (newColumn == 0) {
  1770. return;
  1771. }
  1772. --newColumn;
  1773. break;
  1774. case KeyCodes.KEY_TAB:
  1775. if (event.getShiftKey()) {
  1776. newContainer = getPreviousContainer(containerWithFocus);
  1777. } else {
  1778. newContainer = getNextContainer(containerWithFocus);
  1779. }
  1780. if (newContainer == containerWithFocus) {
  1781. return;
  1782. }
  1783. break;
  1784. default:
  1785. return;
  1786. }
  1787. if (newContainer != containerWithFocus) {
  1788. if (newContainer == escalator.getBody()) {
  1789. newRow = lastFocusedBodyRow;
  1790. } else if (newContainer == escalator.getHeader()) {
  1791. newRow = lastFocusedHeaderRow;
  1792. } else {
  1793. newRow = lastFocusedFooterRow;
  1794. }
  1795. } else if (newRow < 0) {
  1796. newContainer = getPreviousContainer(newContainer);
  1797. if (newContainer == containerWithFocus) {
  1798. newRow = 0;
  1799. } else if (newContainer == escalator.getBody()) {
  1800. newRow = getLastVisibleRowIndex();
  1801. } else {
  1802. newRow = newContainer.getRowCount() - 1;
  1803. }
  1804. } else if (newRow >= containerWithFocus.getRowCount()) {
  1805. newContainer = getNextContainer(newContainer);
  1806. if (newContainer == containerWithFocus) {
  1807. newRow = containerWithFocus.getRowCount() - 1;
  1808. } else if (newContainer == escalator.getBody()) {
  1809. newRow = getFirstVisibleRowIndex();
  1810. } else {
  1811. newRow = 0;
  1812. }
  1813. }
  1814. if (newContainer.getRowCount() == 0) {
  1815. /*
  1816. * There are no rows in the container. Can't change the
  1817. * focused cell.
  1818. */
  1819. return;
  1820. }
  1821. event.preventDefault();
  1822. event.stopPropagation();
  1823. setCellFocus(newRow, newColumn, newContainer);
  1824. }
  1825. }
  1826. private RowContainer getPreviousContainer(RowContainer current) {
  1827. if (current == escalator.getFooter()) {
  1828. current = escalator.getBody();
  1829. } else if (current == escalator.getBody()) {
  1830. current = escalator.getHeader();
  1831. } else {
  1832. return current;
  1833. }
  1834. if (current.getRowCount() == 0) {
  1835. return getPreviousContainer(current);
  1836. }
  1837. return current;
  1838. }
  1839. private RowContainer getNextContainer(RowContainer current) {
  1840. if (current == escalator.getHeader()) {
  1841. current = escalator.getBody();
  1842. } else if (current == escalator.getBody()) {
  1843. current = escalator.getFooter();
  1844. } else {
  1845. return current;
  1846. }
  1847. if (current.getRowCount() == 0) {
  1848. return getNextContainer(current);
  1849. }
  1850. return current;
  1851. }
  1852. private void refreshRow(int row) {
  1853. containerWithFocus.refreshRows(row, 1);
  1854. }
  1855. /**
  1856. * Offsets the focused cell's range.
  1857. *
  1858. * @param offset
  1859. * offset for fixing focused cell's range
  1860. */
  1861. public void offsetRangeBy(int offset) {
  1862. cellFocusRange = cellFocusRange.offsetBy(offset);
  1863. }
  1864. /**
  1865. * Informs {@link CellFocusHandler} that certain range of rows has been
  1866. * added to the Grid body. {@link CellFocusHandler} will fix indices
  1867. * accordingly.
  1868. *
  1869. * @param added
  1870. * a range of added rows
  1871. */
  1872. public void rowsAddedToBody(Range added) {
  1873. boolean bodyHasFocus = (containerWithFocus == escalator.getBody());
  1874. boolean insertionIsAboveFocusedCell = (added.getStart() <= rowWithFocus);
  1875. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  1876. rowWithFocus += added.length();
  1877. refreshRow(rowWithFocus);
  1878. }
  1879. }
  1880. /**
  1881. * Informs {@link CellFocusHandler} that certain range of rows has been
  1882. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  1883. * accordingly.
  1884. *
  1885. * @param removed
  1886. * a range of removed rows
  1887. */
  1888. public void rowsRemovedFromBody(Range removed) {
  1889. if (containerWithFocus != escalator.getBody()) {
  1890. return;
  1891. } else if (!removed.contains(rowWithFocus)) {
  1892. if (removed.getStart() > rowWithFocus) {
  1893. return;
  1894. }
  1895. rowWithFocus = rowWithFocus - removed.length();
  1896. } else {
  1897. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  1898. rowWithFocus = removed.getStart();
  1899. } else if (removed.getStart() > 0) {
  1900. rowWithFocus = removed.getStart() - 1;
  1901. } else {
  1902. if (escalator.getHeader().getRowCount() > 0) {
  1903. rowWithFocus = lastFocusedHeaderRow;
  1904. containerWithFocus = escalator.getHeader();
  1905. } else if (escalator.getFooter().getRowCount() > 0) {
  1906. rowWithFocus = lastFocusedFooterRow;
  1907. containerWithFocus = escalator.getFooter();
  1908. }
  1909. }
  1910. }
  1911. refreshRow(rowWithFocus);
  1912. }
  1913. }
  1914. public final class SelectionColumn extends Column<Boolean, T> {
  1915. private boolean initDone = false;
  1916. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  1917. super(selectColumnRenderer);
  1918. }
  1919. void initDone() {
  1920. if (getSelectionModel() instanceof SelectionModel.Multi
  1921. && header.getDefaultRow() != null) {
  1922. /*
  1923. * TODO: Currently the select all check box is shown when multi
  1924. * selection is in use. This might result in malfunctions if no
  1925. * SelectAllHandlers are present.
  1926. *
  1927. * Later on this could be fixed so that it check such handlers
  1928. * exist.
  1929. */
  1930. final SelectionModel.Multi<T> model = (Multi<T>) getSelectionModel();
  1931. final CheckBox checkBox = new CheckBox();
  1932. checkBox.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
  1933. @Override
  1934. public void onValueChange(ValueChangeEvent<Boolean> event) {
  1935. if (event.getValue()) {
  1936. fireEvent(new SelectAllEvent<T>(model));
  1937. } else {
  1938. model.deselectAll();
  1939. }
  1940. }
  1941. });
  1942. header.getDefaultRow().getCell(this).setWidget(checkBox);
  1943. }
  1944. setWidth(-1);
  1945. setEditable(false);
  1946. initDone = true;
  1947. }
  1948. @Override
  1949. public Column<Boolean, T> setWidth(double pixels) {
  1950. if (pixels != getWidth() && initDone) {
  1951. throw new UnsupportedOperationException("The selection "
  1952. + "column cannot be modified after init");
  1953. } else {
  1954. super.setWidth(pixels);
  1955. }
  1956. return this;
  1957. }
  1958. @Override
  1959. public Boolean getValue(T row) {
  1960. return Boolean.valueOf(isSelected(row));
  1961. }
  1962. @Override
  1963. public Column<Boolean, T> setExpandRatio(int ratio) {
  1964. throw new UnsupportedOperationException(
  1965. "can't change the expand ratio of the selection column");
  1966. }
  1967. @Override
  1968. public int getExpandRatio() {
  1969. return 0;
  1970. }
  1971. @Override
  1972. public Column<Boolean, T> setMaximumWidth(double pixels) {
  1973. throw new UnsupportedOperationException(
  1974. "can't change the maximum width of the selection column");
  1975. }
  1976. @Override
  1977. public double getMaximumWidth() {
  1978. return -1;
  1979. }
  1980. @Override
  1981. public Column<Boolean, T> setMinimumWidth(double pixels) {
  1982. throw new UnsupportedOperationException(
  1983. "can't change the minimum width of the selection column");
  1984. }
  1985. @Override
  1986. public double getMinimumWidth() {
  1987. return -1;
  1988. }
  1989. @Override
  1990. public Column<Boolean, T> setEditable(boolean editable) {
  1991. if (initDone) {
  1992. throw new UnsupportedOperationException(
  1993. "can't set the selection column editable");
  1994. }
  1995. super.setEditable(editable);
  1996. return this;
  1997. }
  1998. }
  1999. /**
  2000. * Helper class for performing sorting through the user interface. Controls
  2001. * the sort() method, reporting USER as the event originator. This is a
  2002. * completely internal class, and is, as such, safe to re-name should a more
  2003. * descriptive name come to mind.
  2004. */
  2005. private final class UserSorter {
  2006. private final Timer timer;
  2007. private boolean scheduledMultisort;
  2008. private Column<?, T> column;
  2009. private UserSorter() {
  2010. timer = new Timer() {
  2011. @Override
  2012. public void run() {
  2013. UserSorter.this.sort(column, scheduledMultisort);
  2014. }
  2015. };
  2016. }
  2017. /**
  2018. * Toggle sorting for a cell. If the multisort parameter is set to true,
  2019. * the cell's sort order is modified as a natural part of a multi-sort
  2020. * chain. If false, the sorting order is set to ASCENDING for that
  2021. * cell's column. If that column was already the only sorted column in
  2022. * the Grid, the sort direction is flipped.
  2023. *
  2024. * @param cell
  2025. * a valid cell reference
  2026. * @param multisort
  2027. * whether the sort command should act as a multi-sort stack
  2028. * or not
  2029. */
  2030. public void sort(Column<?, ?> column, boolean multisort) {
  2031. if (!columns.contains(column)) {
  2032. throw new IllegalArgumentException(
  2033. "Given column is not a column in this grid. "
  2034. + column.toString());
  2035. }
  2036. if (!column.isSortable()) {
  2037. return;
  2038. }
  2039. final SortOrder so = getSortOrder(column);
  2040. if (multisort) {
  2041. // If the sort order exists, replace existing value with its
  2042. // opposite
  2043. if (so != null) {
  2044. final int idx = sortOrder.indexOf(so);
  2045. sortOrder.set(idx, so.getOpposite());
  2046. } else {
  2047. // If it doesn't, just add a new sort order to the end of
  2048. // the list
  2049. sortOrder.add(new SortOrder(column));
  2050. }
  2051. } else {
  2052. // Since we're doing single column sorting, first clear the
  2053. // list. Then, if the sort order existed, add its opposite,
  2054. // otherwise just add a new sort value
  2055. int items = sortOrder.size();
  2056. sortOrder.clear();
  2057. if (so != null && items == 1) {
  2058. sortOrder.add(so.getOpposite());
  2059. } else {
  2060. sortOrder.add(new SortOrder(column));
  2061. }
  2062. }
  2063. // sortOrder has been changed; tell the Grid to re-sort itself by
  2064. // user request.
  2065. Grid.this.sort(true);
  2066. }
  2067. /**
  2068. * Perform a sort after a delay.
  2069. *
  2070. * @param delay
  2071. * delay, in milliseconds
  2072. */
  2073. public void sortAfterDelay(int delay, boolean multisort) {
  2074. column = eventCell.getColumn();
  2075. scheduledMultisort = multisort;
  2076. timer.schedule(delay);
  2077. }
  2078. /**
  2079. * Check if a delayed sort command has been issued but not yet carried
  2080. * out.
  2081. *
  2082. * @return a boolean value
  2083. */
  2084. public boolean isDelayedSortScheduled() {
  2085. return timer.isRunning();
  2086. }
  2087. /**
  2088. * Cancel a scheduled sort.
  2089. */
  2090. public void cancelDelayedSort() {
  2091. timer.cancel();
  2092. }
  2093. }
  2094. /** @see Grid#autoColumnWidthsRecalculator */
  2095. private class AutoColumnWidthsRecalculator {
  2096. private final ScheduledCommand calculateCommand = new ScheduledCommand() {
  2097. @Override
  2098. public void execute() {
  2099. if (!isScheduled) {
  2100. // something cancelled running this.
  2101. return;
  2102. }
  2103. if (header.markAsDirty || footer.markAsDirty) {
  2104. if (rescheduleCount < 10) {
  2105. /*
  2106. * Headers and footers are rendered as finally, this way
  2107. * we re-schedule this loop as finally, at the end of
  2108. * the queue, so that the headers have a chance to
  2109. * render themselves.
  2110. */
  2111. Scheduler.get().scheduleFinally(this);
  2112. rescheduleCount++;
  2113. } else {
  2114. /*
  2115. * We've tried too many times reschedule finally. Seems
  2116. * like something is being deferred. Let the queue
  2117. * execute and retry again.
  2118. */
  2119. rescheduleCount = 0;
  2120. Scheduler.get().scheduleDeferred(this);
  2121. }
  2122. } else if (dataIsBeingFetched) {
  2123. Scheduler.get().scheduleDeferred(this);
  2124. } else {
  2125. calculate();
  2126. }
  2127. }
  2128. };
  2129. private int rescheduleCount = 0;
  2130. private boolean isScheduled;
  2131. /**
  2132. * Calculates and applies column widths, taking into account fixed
  2133. * widths and column expand rules
  2134. *
  2135. * @param immediately
  2136. * <code>true</code> if the widths should be executed
  2137. * immediately (ignoring lazy loading completely), or
  2138. * <code>false</code> if the command should be run after a
  2139. * while (duplicate non-immediately invocations are ignored).
  2140. * @see Column#setWidth(double)
  2141. * @see Column#setExpandRatio(int)
  2142. * @see Column#setMinimumWidth(double)
  2143. * @see Column#setMaximumWidth(double)
  2144. */
  2145. public void schedule() {
  2146. if (!isScheduled) {
  2147. isScheduled = true;
  2148. Scheduler.get().scheduleFinally(calculateCommand);
  2149. }
  2150. }
  2151. private void calculate() {
  2152. isScheduled = false;
  2153. rescheduleCount = 0;
  2154. assert !dataIsBeingFetched : "Trying to calculate column widths even though data is still being fetched.";
  2155. if (columnsAreGuaranteedToBeWiderThanGrid()) {
  2156. applyColumnWidths();
  2157. } else {
  2158. applyColumnWidthsWithExpansion();
  2159. /*
  2160. * [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME: just
  2161. * dump all the remaining pixels into the last column and
  2162. * whistle loudly
  2163. */
  2164. boolean dumpIntoLastColumn = false;
  2165. double escalatorWidth = escalator.getInnerWidth();
  2166. double occupiedWidth = 0;
  2167. for (Column column : getColumns()) {
  2168. occupiedWidth += column.getWidthActual();
  2169. if (column.getWidth() < 0 && column.getExpandRatio() != 0) {
  2170. dumpIntoLastColumn = true;
  2171. }
  2172. }
  2173. if (dumpIntoLastColumn) {
  2174. Column<?, T> lastColumn = getColumn(getColumnCount() - 1);
  2175. double width = Math.floor(lastColumn.getWidthActual()
  2176. + (escalatorWidth - occupiedWidth));
  2177. escalator.getColumnConfiguration().setColumnWidth(
  2178. getColumnCount() - 1, width);
  2179. }
  2180. }
  2181. }
  2182. private boolean columnsAreGuaranteedToBeWiderThanGrid() {
  2183. double freeSpace = escalator.getInnerWidth();
  2184. for (Column<?, ?> column : getColumns()) {
  2185. if (column.getWidth() >= 0) {
  2186. freeSpace -= column.getWidth();
  2187. } else if (column.getMinimumWidth() >= 0) {
  2188. freeSpace -= column.getMinimumWidth();
  2189. }
  2190. }
  2191. return freeSpace < 0;
  2192. }
  2193. @SuppressWarnings("boxing")
  2194. private void applyColumnWidths() {
  2195. /* Step 1: Apply all column widths as they are. */
  2196. Map<Integer, Double> selfWidths = new LinkedHashMap<Integer, Double>();
  2197. List<Column<?, T>> columns = getColumns();
  2198. for (int index = 0; index < columns.size(); index++) {
  2199. selfWidths.put(index, columns.get(index).getWidth());
  2200. }
  2201. Grid.this.escalator.getColumnConfiguration().setColumnWidths(
  2202. selfWidths);
  2203. /*
  2204. * Step 2: Make sure that each column ends up obeying their min/max
  2205. * width constraints if defined as autowidth. If constraints are
  2206. * violated, fix it.
  2207. */
  2208. Map<Integer, Double> constrainedWidths = new LinkedHashMap<Integer, Double>();
  2209. for (int index = 0; index < columns.size(); index++) {
  2210. Column<?, T> column = columns.get(index);
  2211. boolean hasAutoWidth = column.getWidth() < 0;
  2212. if (!hasAutoWidth) {
  2213. continue;
  2214. }
  2215. // TODO: bug: these don't honor the CSS max/min. :(
  2216. double actualWidth = column.getWidthActual();
  2217. if (actualWidth < getMinWidth(column)) {
  2218. constrainedWidths.put(index, column.getMinimumWidth());
  2219. } else if (actualWidth > getMaxWidth(column)) {
  2220. constrainedWidths.put(index, column.getMaximumWidth());
  2221. }
  2222. }
  2223. Grid.this.escalator.getColumnConfiguration().setColumnWidths(
  2224. constrainedWidths);
  2225. }
  2226. private void applyColumnWidthsWithExpansion() {
  2227. boolean someColumnExpands = false;
  2228. int totalRatios = 0;
  2229. double reservedPixels = 0;
  2230. final Set<Column<?, ?>> columnsToExpand = new HashSet<Column<?, ?>>();
  2231. /*
  2232. * Set all fixed widths and also calculate the size-to-fit widths
  2233. * for the autocalculated columns.
  2234. *
  2235. * This way we know with how many pixels we have left to expand the
  2236. * rest.
  2237. */
  2238. for (Column<?, ?> column : getColumns()) {
  2239. final double widthAsIs = column.getWidth();
  2240. final boolean isFixedWidth = widthAsIs >= 0;
  2241. final double widthFixed = Math.max(widthAsIs,
  2242. column.getMinimumWidth());
  2243. final int expandRatio = column.getExpandRatio();
  2244. if (isFixedWidth) {
  2245. column.doSetWidth(widthFixed);
  2246. } else {
  2247. column.doSetWidth(-1);
  2248. final double newWidth = column.getWidthActual();
  2249. final double maxWidth = getMaxWidth(column);
  2250. boolean shouldExpand = newWidth < maxWidth
  2251. && expandRatio > 0;
  2252. if (shouldExpand) {
  2253. totalRatios += expandRatio;
  2254. columnsToExpand.add(column);
  2255. someColumnExpands = true;
  2256. }
  2257. }
  2258. reservedPixels += column.getWidthActual();
  2259. }
  2260. /*
  2261. * If no column has a positive expand ratio, all columns with a
  2262. * negative expand ratio has an expand ratio. Columns with 0 expand
  2263. * ratio are excluded.
  2264. *
  2265. * This means that if we only define one column to have 0 expand, it
  2266. * will be the only one not to expand, while all the others expand.
  2267. */
  2268. if (!someColumnExpands) {
  2269. assert totalRatios == 0 : "totalRatios should've been 0";
  2270. assert columnsToExpand.isEmpty() : "columnsToExpand should've been empty";
  2271. for (Column<?, ?> column : getColumns()) {
  2272. final double width = column.getWidth();
  2273. final int expandRatio = column.getExpandRatio();
  2274. if (width < 0 && expandRatio < 0) {
  2275. totalRatios++;
  2276. columnsToExpand.add(column);
  2277. }
  2278. }
  2279. }
  2280. /*
  2281. * Now that we know how many pixels we need at the very least, we
  2282. * can distribute the remaining pixels to all columns according to
  2283. * their expand ratios.
  2284. */
  2285. // [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME: ceil
  2286. double pixelsToDistribute = Math.ceil(escalator.getInnerWidth())
  2287. - reservedPixels;
  2288. if (pixelsToDistribute <= 0 || totalRatios <= 0) {
  2289. return;
  2290. }
  2291. /*
  2292. * Check for columns that hit their max width. Adjust
  2293. * pixelsToDistribute and totalRatios accordingly. Recheck. Stop
  2294. * when no new columns hit their max width
  2295. */
  2296. boolean aColumnHasMaxedOut;
  2297. do {
  2298. aColumnHasMaxedOut = false;
  2299. // [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME floor
  2300. final double widthPerRatio = Math.floor(pixelsToDistribute
  2301. / totalRatios);
  2302. final Iterator<Column<?, ?>> i = columnsToExpand.iterator();
  2303. while (i.hasNext()) {
  2304. final Column<?, ?> column = i.next();
  2305. final int expandRatio = getExpandRatio(column,
  2306. someColumnExpands);
  2307. final double autoWidth = column.getWidthActual();
  2308. final double maxWidth = getMaxWidth(column);
  2309. final double widthCandidate = autoWidth + widthPerRatio
  2310. * expandRatio;
  2311. if (maxWidth <= widthCandidate) {
  2312. column.doSetWidth(maxWidth);
  2313. totalRatios -= expandRatio;
  2314. pixelsToDistribute -= maxWidth - autoWidth;
  2315. i.remove();
  2316. aColumnHasMaxedOut = true;
  2317. }
  2318. }
  2319. } while (aColumnHasMaxedOut);
  2320. if (totalRatios <= 0 && columnsToExpand.isEmpty()) {
  2321. return;
  2322. }
  2323. assert pixelsToDistribute > 0 : "We've run out of pixels to distribute ("
  2324. + pixelsToDistribute
  2325. + "px to "
  2326. + totalRatios
  2327. + " ratios between " + columnsToExpand.size() + " columns)";
  2328. assert totalRatios > 0 && !columnsToExpand.isEmpty() : "Bookkeeping out of sync. Ratios: "
  2329. + totalRatios + " Columns: " + columnsToExpand.size();
  2330. /*
  2331. * If we still have anything left, distribute the remaining pixels
  2332. * to the remaining columns.
  2333. */
  2334. // [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME: floor
  2335. final double widthPerRatio = Math.floor(pixelsToDistribute
  2336. / totalRatios);
  2337. for (Column<?, ?> column : columnsToExpand) {
  2338. final int expandRatio = getExpandRatio(column,
  2339. someColumnExpands);
  2340. final double autoWidth = column.getWidthActual();
  2341. final double totalWidth = autoWidth + widthPerRatio
  2342. * expandRatio;
  2343. column.doSetWidth(totalWidth);
  2344. totalRatios -= expandRatio;
  2345. }
  2346. assert totalRatios == 0 : "Bookkeeping error: there were still some ratios left undistributed: "
  2347. + totalRatios;
  2348. /*
  2349. * Check the guarantees for minimum width and scoot back the columns
  2350. * that don't care.
  2351. */
  2352. boolean minWidthsCausedReflows;
  2353. do {
  2354. minWidthsCausedReflows = false;
  2355. /*
  2356. * First, let's check which columns were too cramped, and expand
  2357. * them. Also keep track on how many pixels we grew - we need to
  2358. * remove those pixels from other columns
  2359. */
  2360. double pixelsToRemoveFromOtherColumns = 0;
  2361. for (Column<?, T> column : getColumns()) {
  2362. /*
  2363. * We can't iterate over columnsToExpand, even though that
  2364. * would be convenient. This is because some column without
  2365. * an expand ratio might still have a min width - those
  2366. * wouldn't show up in that set.
  2367. */
  2368. // [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME ceil
  2369. double minWidth = Math.ceil(getMinWidth(column));
  2370. double currentWidth = column.getWidthActual();
  2371. boolean hasAutoWidth = column.getWidth() < 0;
  2372. if (hasAutoWidth && currentWidth < minWidth) {
  2373. column.doSetWidth(minWidth);
  2374. pixelsToRemoveFromOtherColumns += (minWidth - currentWidth);
  2375. minWidthsCausedReflows = true;
  2376. /*
  2377. * Remove this column form the set if it exists. This
  2378. * way we make sure that it doesn't get shrunk in the
  2379. * next step.
  2380. */
  2381. columnsToExpand.remove(column);
  2382. }
  2383. }
  2384. /*
  2385. * Now we need to shrink the remaining columns according to
  2386. * their ratios. Recalculate the sum of remaining ratios.
  2387. */
  2388. totalRatios = 0;
  2389. for (Column<?, ?> column : columnsToExpand) {
  2390. totalRatios += getExpandRatio(column, someColumnExpands);
  2391. }
  2392. // [[subpixelworkaround]] (6.2.2015, Henrik Paul) FIXME: ceil
  2393. final double pixelsToRemovePerRatio = Math
  2394. .ceil(pixelsToRemoveFromOtherColumns / totalRatios);
  2395. for (Column<?, ?> column : columnsToExpand) {
  2396. final double pixelsToRemove = pixelsToRemovePerRatio
  2397. * getExpandRatio(column, someColumnExpands);
  2398. column.doSetWidth(column.getWidthActual() - pixelsToRemove);
  2399. }
  2400. } while (minWidthsCausedReflows);
  2401. }
  2402. private int getExpandRatio(Column<?, ?> column,
  2403. boolean someColumnExpands) {
  2404. int expandRatio = column.getExpandRatio();
  2405. if (expandRatio > 0) {
  2406. return expandRatio;
  2407. } else if (expandRatio < 0) {
  2408. assert !someColumnExpands : "No columns should've expanded";
  2409. return 1;
  2410. } else {
  2411. assert false : "this method should've not been called at all if expandRatio is 0";
  2412. return 0;
  2413. }
  2414. }
  2415. /**
  2416. * Returns the maximum width of the column, or {@link Double#MAX_VALUE}
  2417. * if defined as negative.
  2418. */
  2419. private double getMaxWidth(Column<?, ?> column) {
  2420. double maxWidth = column.getMaximumWidth();
  2421. if (maxWidth >= 0) {
  2422. return maxWidth;
  2423. } else {
  2424. return Double.MAX_VALUE;
  2425. }
  2426. }
  2427. /**
  2428. * Returns the minimum width of the column, or {@link Double#MIN_VALUE}
  2429. * if defined as negative.
  2430. */
  2431. private double getMinWidth(Column<?, ?> column) {
  2432. double minWidth = column.getMinimumWidth();
  2433. if (minWidth >= 0) {
  2434. return minWidth;
  2435. } else {
  2436. return Double.MIN_VALUE;
  2437. }
  2438. }
  2439. /**
  2440. * Check whether the auto width calculation is currently scheduled.
  2441. *
  2442. * @return <code>true</code> if auto width calculation is currently
  2443. * scheduled
  2444. */
  2445. public boolean isScheduled() {
  2446. return isScheduled;
  2447. }
  2448. }
  2449. /**
  2450. * Escalator used internally by grid to render the rows
  2451. */
  2452. private Escalator escalator = GWT.create(Escalator.class);
  2453. private final Header header = GWT.create(Header.class);
  2454. private final Footer footer = GWT.create(Footer.class);
  2455. /**
  2456. * List of columns in the grid. Order defines the visible order.
  2457. */
  2458. private List<Column<?, T>> columns = new ArrayList<Column<?, T>>();
  2459. /**
  2460. * The datasource currently in use. <em>Note:</em> it is <code>null</code>
  2461. * on initialization, but not after that.
  2462. */
  2463. private DataSource<T> dataSource;
  2464. /**
  2465. * Currently available row range in DataSource.
  2466. */
  2467. private Range currentDataAvailable = Range.withLength(0, 0);
  2468. /**
  2469. * The number of frozen columns, 0 freezes the selection column if
  2470. * displayed, -1 also prevents selection col from freezing.
  2471. */
  2472. private int frozenColumnCount = 0;
  2473. /**
  2474. * Current sort order. The (private) sort() method reads this list to
  2475. * determine the order in which to present rows.
  2476. */
  2477. private List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  2478. private Renderer<Boolean> selectColumnRenderer = null;
  2479. private SelectionColumn selectionColumn;
  2480. private String rowStripeStyleName;
  2481. private String rowHasDataStyleName;
  2482. private String rowSelectedStyleName;
  2483. private String cellFocusStyleName;
  2484. private String rowFocusStyleName;
  2485. /**
  2486. * Current selection model.
  2487. */
  2488. private SelectionModel<T> selectionModel;
  2489. protected final CellFocusHandler cellFocusHandler;
  2490. private final UserSorter sorter = new UserSorter();
  2491. private final Editor<T> editor = GWT.create(Editor.class);
  2492. private boolean dataIsBeingFetched = false;
  2493. /**
  2494. * The cell a click event originated from
  2495. * <p>
  2496. * This is a workaround to make Chrome work like Firefox. In Chrome,
  2497. * normally if you start a drag on one cell and release on:
  2498. * <ul>
  2499. * <li>that same cell, the click event is that {@code <td>}.
  2500. * <li>a cell on that same row, the click event is the parent {@code <tr>}.
  2501. * <li>a cell on another row, the click event is the table section ancestor
  2502. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  2503. * </ul>
  2504. *
  2505. * @see #onBrowserEvent(Event)
  2506. */
  2507. private Cell cellOnPrevMouseDown;
  2508. /**
  2509. * A scheduled command to re-evaluate the widths of <em>all columns</em>
  2510. * that have calculated widths. Most probably called because
  2511. * minwidth/maxwidth/expandratio has changed.
  2512. */
  2513. private final AutoColumnWidthsRecalculator autoColumnWidthsRecalculator = new AutoColumnWidthsRecalculator();
  2514. private boolean enabled = true;
  2515. private boolean columnReorderingAllowed;
  2516. private DragAndDropHandler dndHandler = new DragAndDropHandler();
  2517. private AutoScroller autoScroller = new AutoScroller(this);
  2518. private DragAndDropCallback headerCellDndCallback = new DragAndDropCallback() {
  2519. private final AutoScrollerCallback autoScrollerCallback = new AutoScrollerCallback() {
  2520. @Override
  2521. public void onAutoScroll(int scrollDiff) {
  2522. autoScrollX = scrollDiff;
  2523. onDragUpdate(null);
  2524. }
  2525. @Override
  2526. public void onAutoScrollReachedMin() {
  2527. // make sure the drop marker is visible on the left
  2528. autoScrollX = 0;
  2529. updateDragDropMarker(clientX);
  2530. }
  2531. @Override
  2532. public void onAutoScrollReachedMax() {
  2533. // make sure the drop marker is visible on the right
  2534. autoScrollX = 0;
  2535. updateDragDropMarker(clientX);
  2536. }
  2537. };
  2538. /**
  2539. * Elements for displaying the dragged column(s) and drop marker
  2540. * properly
  2541. */
  2542. private Element table;
  2543. private Element tableHeader;
  2544. /** Marks the column drop location */
  2545. private Element dropMarker;
  2546. /** A copy of the dragged column(s), moves with cursor. */
  2547. private Element dragElement;
  2548. /** Tracks index of the column whose left side the drop would occur */
  2549. private int latestColumnDropIndex;
  2550. /**
  2551. * Map of possible drop positions for the column and the corresponding
  2552. * column index.
  2553. */
  2554. private final TreeMap<Double, Integer> possibleDropPositions = new TreeMap<Double, Integer>();
  2555. /**
  2556. * Makes sure that drag cancel doesn't cause anything unwanted like sort
  2557. */
  2558. private HandlerRegistration columnSortPreventRegistration;
  2559. private int clientX;
  2560. /** How much the grid is being auto scrolled while dragging. */
  2561. private int autoScrollX;
  2562. private void initHeaderDragElementDOM() {
  2563. if (table == null) {
  2564. tableHeader = DOM.createTHead();
  2565. dropMarker = DOM.createDiv();
  2566. tableHeader.appendChild(dropMarker);
  2567. table = DOM.createTable();
  2568. table.appendChild(tableHeader);
  2569. table.setClassName("header-drag-table");
  2570. }
  2571. // update the style names on each run in case primary name has been
  2572. // modified
  2573. tableHeader.setClassName(escalator.getHeader().getElement()
  2574. .getClassName());
  2575. dropMarker.setClassName(getStylePrimaryName() + "-drop-marker");
  2576. int topOffset = 0;
  2577. for (int i = 0; i < eventCell.getRowIndex(); i++) {
  2578. topOffset += escalator.getHeader().getRowElement(i)
  2579. .getFirstChildElement().getOffsetHeight();
  2580. }
  2581. tableHeader.getStyle().setTop(topOffset, Unit.PX);
  2582. getElement().appendChild(table);
  2583. }
  2584. @Override
  2585. public void onDragUpdate(NativePreviewEvent event) {
  2586. if (event != null) {
  2587. clientX = WidgetUtil.getTouchOrMouseClientX(event
  2588. .getNativeEvent());
  2589. autoScrollX = 0;
  2590. }
  2591. resolveDragElementHorizontalPosition(clientX);
  2592. updateDragDropMarker(clientX);
  2593. }
  2594. private void updateDragDropMarker(final int clientX) {
  2595. final double scrollLeft = getScrollLeft();
  2596. final double cursorXCoordinate = clientX
  2597. - escalator.getHeader().getElement().getAbsoluteLeft();
  2598. final Entry<Double, Integer> cellEdgeOnRight = possibleDropPositions
  2599. .ceilingEntry(cursorXCoordinate);
  2600. final Entry<Double, Integer> cellEdgeOnLeft = possibleDropPositions
  2601. .floorEntry(cursorXCoordinate);
  2602. final double diffToRightEdge = cellEdgeOnRight == null ? Double.MAX_VALUE
  2603. : cellEdgeOnRight.getKey() - cursorXCoordinate;
  2604. final double diffToLeftEdge = cellEdgeOnLeft == null ? Double.MAX_VALUE
  2605. : cursorXCoordinate - cellEdgeOnLeft.getKey();
  2606. double dropMarkerLeft = 0 - scrollLeft;
  2607. if (diffToRightEdge > diffToLeftEdge) {
  2608. latestColumnDropIndex = cellEdgeOnLeft.getValue();
  2609. dropMarkerLeft += cellEdgeOnLeft.getKey();
  2610. } else {
  2611. latestColumnDropIndex = cellEdgeOnRight.getValue();
  2612. dropMarkerLeft += cellEdgeOnRight.getKey();
  2613. }
  2614. dropMarkerLeft += autoScrollX;
  2615. final double frozenColumnsWidth = getFrozenColumnsWidth();
  2616. if (dropMarkerLeft < frozenColumnsWidth
  2617. || dropMarkerLeft > escalator.getHeader().getElement()
  2618. .getOffsetWidth() || dropMarkerLeft < 0) {
  2619. dropMarkerLeft = -10000000;
  2620. }
  2621. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  2622. }
  2623. private void resolveDragElementHorizontalPosition(final int clientX) {
  2624. double left = clientX - table.getAbsoluteLeft();
  2625. final double frozenColumnsWidth = getFrozenColumnsWidth();
  2626. if (left < frozenColumnsWidth) {
  2627. left = (int) frozenColumnsWidth;
  2628. }
  2629. // do not show the drag element beyond a spanned header cell
  2630. // limitation
  2631. final Double leftBound = possibleDropPositions.firstKey();
  2632. final Double rightBound = possibleDropPositions.lastKey();
  2633. double scrollLeft = getScrollLeft();
  2634. if (left + scrollLeft < leftBound) {
  2635. left = leftBound - scrollLeft + autoScrollX;
  2636. } else if (left + scrollLeft > rightBound) {
  2637. left = rightBound - scrollLeft + autoScrollX;
  2638. }
  2639. // do not show the drag element beyond the grid
  2640. left = Math.max(0, Math.min(left, table.getClientWidth()));
  2641. left -= dragElement.getClientWidth() / 2;
  2642. dragElement.getStyle().setLeft(left, Unit.PX);
  2643. }
  2644. @Override
  2645. public boolean onDragStart(NativeEvent startingEvent) {
  2646. calculatePossibleDropPositions();
  2647. if (possibleDropPositions.isEmpty()) {
  2648. return false;
  2649. }
  2650. initHeaderDragElementDOM();
  2651. // needs to clone focus and sorting indicators too (UX)
  2652. dragElement = DOM.clone(eventCell.getElement(), true);
  2653. dragElement.getStyle().clearWidth();
  2654. dropMarker.getStyle().setProperty("height",
  2655. dragElement.getStyle().getHeight());
  2656. tableHeader.appendChild(dragElement);
  2657. // mark the column being dragged for styling
  2658. eventCell.getElement().addClassName("dragged");
  2659. // mark the floating cell, for styling & testing
  2660. dragElement.addClassName("dragged-column-header");
  2661. // start the auto scroll handler
  2662. autoScroller.setScrollAreaPX(60);
  2663. autoScroller.start(startingEvent, ScrollAxis.HORIZONTAL,
  2664. autoScrollerCallback);
  2665. return true;
  2666. }
  2667. @Override
  2668. public void onDragEnd() {
  2669. table.removeFromParent();
  2670. dragElement.removeFromParent();
  2671. eventCell.getElement().removeClassName("dragged");
  2672. }
  2673. @Override
  2674. public void onDrop() {
  2675. final int draggedColumnIndex = eventCell.getColumnIndex();
  2676. if (latestColumnDropIndex != draggedColumnIndex
  2677. && latestColumnDropIndex != (draggedColumnIndex + 1)) {
  2678. List<Column<?, T>> columns = getColumns();
  2679. List<Column<?, T>> reordered = new ArrayList<Column<?, T>>(
  2680. columns);
  2681. Column<?, T> moved = reordered.remove(draggedColumnIndex);
  2682. if (draggedColumnIndex < latestColumnDropIndex) {
  2683. latestColumnDropIndex--;
  2684. }
  2685. reordered.add(latestColumnDropIndex, moved);
  2686. reordered.remove(selectionColumn); // since setColumnOrder will
  2687. // add it anyway!
  2688. @SuppressWarnings("unchecked")
  2689. Column<?, T>[] array = reordered.toArray(new Column[reordered
  2690. .size()]);
  2691. setColumnOrder(array);
  2692. transferCellFocusOnDrop();
  2693. } // else no reordering
  2694. }
  2695. private void transferCellFocusOnDrop() {
  2696. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  2697. if (focusedCell != null) {
  2698. final int focusedCellColumnIndex = focusedCell.getColumn();
  2699. final int focusedRowIndex = focusedCell.getRow();
  2700. final int draggedColumnIndex = eventCell.getColumnIndex();
  2701. // transfer focus if it was effected by the new column order
  2702. final RowContainer rowContainer = escalator
  2703. .findRowContainer(focusedCell.getElement());
  2704. if (focusedCellColumnIndex == draggedColumnIndex) {
  2705. // move with the dragged column
  2706. cellFocusHandler.setCellFocus(focusedRowIndex,
  2707. latestColumnDropIndex, rowContainer);
  2708. } else if (latestColumnDropIndex <= focusedCellColumnIndex
  2709. && draggedColumnIndex > focusedCellColumnIndex) {
  2710. cellFocusHandler.setCellFocus(focusedRowIndex,
  2711. focusedCellColumnIndex + 1, rowContainer);
  2712. } else if (latestColumnDropIndex >= focusedCellColumnIndex
  2713. && draggedColumnIndex < focusedCellColumnIndex) {
  2714. cellFocusHandler.setCellFocus(focusedRowIndex,
  2715. focusedCellColumnIndex - 1, rowContainer);
  2716. }
  2717. }
  2718. }
  2719. @Override
  2720. public void onDragCancel() {
  2721. // cancel next click so that we may prevent column sorting if
  2722. // mouse was released on top of the dragged cell
  2723. if (columnSortPreventRegistration == null) {
  2724. columnSortPreventRegistration = Event
  2725. .addNativePreviewHandler(new NativePreviewHandler() {
  2726. @Override
  2727. public void onPreviewNativeEvent(
  2728. NativePreviewEvent event) {
  2729. if (event.getTypeInt() == Event.ONCLICK) {
  2730. event.cancel();
  2731. event.getNativeEvent().preventDefault();
  2732. columnSortPreventRegistration
  2733. .removeHandler();
  2734. columnSortPreventRegistration = null;
  2735. }
  2736. }
  2737. });
  2738. }
  2739. autoScroller.stop();
  2740. }
  2741. private double getFrozenColumnsWidth() {
  2742. double value = getMultiSelectColumnWidth();
  2743. for (int i = 0; i < getFrozenColumnCount(); i++) {
  2744. value += getColumn(i).getWidthActual();
  2745. }
  2746. return value;
  2747. }
  2748. private double getMultiSelectColumnWidth() {
  2749. if (getSelectionModel().getSelectionColumnRenderer() != null) {
  2750. // frozen checkbox column is present, it is always the first
  2751. // column
  2752. return escalator.getHeader().getElement()
  2753. .getFirstChildElement().getFirstChildElement()
  2754. .getOffsetWidth();
  2755. }
  2756. return 0.0;
  2757. }
  2758. /**
  2759. * Returns the amount of frozen columns. The selection column is always
  2760. * considered frozen, since it can't be moved.
  2761. */
  2762. private int getSelectionAndFrozenColumnCount() {
  2763. // no matter if selection column is frozen or not, it is considered
  2764. // frozen for column dnd reorder
  2765. if (getSelectionModel().getSelectionColumnRenderer() != null) {
  2766. return Math.max(0, getFrozenColumnCount()) + 1;
  2767. } else {
  2768. return Math.max(0, getFrozenColumnCount());
  2769. }
  2770. }
  2771. @SuppressWarnings("boxing")
  2772. private void calculatePossibleDropPositions() {
  2773. possibleDropPositions.clear();
  2774. final int draggedColumnIndex = eventCell.getColumnIndex();
  2775. HashSet<Integer> unavailableColumnDropIndices = new HashSet<Integer>();
  2776. final int frozenColumns = getSelectionAndFrozenColumnCount();
  2777. /*
  2778. * If the dragged cell is adjacent to a spanned cell in any other
  2779. * header or footer row, then the drag is limited inside that
  2780. * spanned cell. The same rules apply: the cell can't be dropped
  2781. * inside another spanned cell. The left and right bounds keep track
  2782. * of the edges of the most limiting spanned cell.
  2783. */
  2784. int leftBound = -1;
  2785. int rightBound = getColumnCount() + 1;
  2786. final List<StaticRow<?>> rows = new ArrayList<StaticRow<?>>();
  2787. rows.addAll(header.getRows());
  2788. rows.addAll(footer.getRows());
  2789. for (StaticRow<?> row : rows) {
  2790. if (!row.hasSpannedCells()) {
  2791. continue;
  2792. }
  2793. for (int c = frozenColumns; c < getColumnCount(); c++) {
  2794. StaticCell cell = row.getCell(getColumn(c));
  2795. int colspan = cell.getColspan();
  2796. if (colspan <= 1) {
  2797. continue;
  2798. }
  2799. final int spannedCellRightEdgeIndex = c + colspan;
  2800. if (c <= draggedColumnIndex
  2801. && spannedCellRightEdgeIndex > draggedColumnIndex) {
  2802. // the spanned cell overlaps the dragged cell
  2803. if (c <= draggedColumnIndex && c > leftBound) {
  2804. leftBound = c;
  2805. }
  2806. if (spannedCellRightEdgeIndex < rightBound) {
  2807. rightBound = spannedCellRightEdgeIndex;
  2808. }
  2809. c = spannedCellRightEdgeIndex - 1;
  2810. }
  2811. else { // can't drop inside a spanned cell
  2812. while (colspan > 1) {
  2813. c++;
  2814. colspan--;
  2815. unavailableColumnDropIndices.add(c);
  2816. }
  2817. }
  2818. }
  2819. }
  2820. if (leftBound == (rightBound - 1)) {
  2821. return;
  2822. }
  2823. double position = getFrozenColumnsWidth();
  2824. // iterate column indices and add possible drop positions
  2825. for (int i = frozenColumns; i < getColumnCount(); i++) {
  2826. if (!unavailableColumnDropIndices.contains(i)) {
  2827. if (leftBound != -1) {
  2828. if (i >= leftBound && i <= rightBound) {
  2829. possibleDropPositions.put(position, i);
  2830. }
  2831. } else {
  2832. possibleDropPositions.put(position, i);
  2833. }
  2834. }
  2835. position += getColumn(i).getWidthActual();
  2836. }
  2837. if (leftBound == -1) {
  2838. // add the right side of the last column as columns.size()
  2839. possibleDropPositions.put(position, getColumnCount());
  2840. }
  2841. }
  2842. };
  2843. /**
  2844. * Enumeration for easy setting of selection mode.
  2845. */
  2846. public enum SelectionMode {
  2847. /**
  2848. * Shortcut for {@link SelectionModelSingle}.
  2849. */
  2850. SINGLE {
  2851. @Override
  2852. protected <T> SelectionModel<T> createModel() {
  2853. return new SelectionModelSingle<T>();
  2854. }
  2855. },
  2856. /**
  2857. * Shortcut for {@link SelectionModelMulti}.
  2858. */
  2859. MULTI {
  2860. @Override
  2861. protected <T> SelectionModel<T> createModel() {
  2862. return new SelectionModelMulti<T>();
  2863. }
  2864. },
  2865. /**
  2866. * Shortcut for {@link SelectionModelNone}.
  2867. */
  2868. NONE {
  2869. @Override
  2870. protected <T> SelectionModel<T> createModel() {
  2871. return new SelectionModelNone<T>();
  2872. }
  2873. };
  2874. protected abstract <T> SelectionModel<T> createModel();
  2875. }
  2876. /**
  2877. * Base class for grid columns internally used by the Grid. The user should
  2878. * use {@link Column} when creating new columns.
  2879. *
  2880. * @param <C>
  2881. * the column type
  2882. *
  2883. * @param <T>
  2884. * the row type
  2885. */
  2886. public static abstract class Column<C, T> {
  2887. /**
  2888. * Default renderer for GridColumns. Renders everything into text
  2889. * through {@link Object#toString()}.
  2890. */
  2891. private final class DefaultTextRenderer implements Renderer<Object> {
  2892. boolean warned = false;
  2893. private final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  2894. + "A more suitable renderer should be set using the setRenderer() method.";
  2895. @Override
  2896. public void render(RendererCellReference cell, Object data) {
  2897. if (!warned && !(data instanceof String)) {
  2898. getLogger().warning(
  2899. Column.this.toString() + ": "
  2900. + DEFAULT_RENDERER_WARNING);
  2901. warned = true;
  2902. }
  2903. final String text;
  2904. if (data == null) {
  2905. text = "";
  2906. } else {
  2907. text = data.toString();
  2908. }
  2909. cell.getElement().setInnerText(text);
  2910. }
  2911. }
  2912. /**
  2913. * the column is associated with
  2914. */
  2915. private Grid<T> grid;
  2916. /**
  2917. * Width of column in pixels as {@link #setWidth(double)} has been
  2918. * called
  2919. */
  2920. private double widthUser = GridConstants.DEFAULT_COLUMN_WIDTH_PX;
  2921. /**
  2922. * Renderer for rendering a value into the cell
  2923. */
  2924. private Renderer<? super C> bodyRenderer;
  2925. private boolean sortable = false;
  2926. private boolean editable = true;
  2927. private String headerCaption = "";
  2928. private double minimumWidthPx = GridConstants.DEFAULT_MIN_WIDTH;
  2929. private double maximumWidthPx = GridConstants.DEFAULT_MAX_WIDTH;
  2930. private int expandRatio = GridConstants.DEFAULT_EXPAND_RATIO;
  2931. /**
  2932. * Constructs a new column with a simple TextRenderer.
  2933. */
  2934. public Column() {
  2935. setRenderer(new DefaultTextRenderer());
  2936. }
  2937. /**
  2938. * Constructs a new column with a simple TextRenderer.
  2939. *
  2940. * @param caption
  2941. * The header caption for this column
  2942. *
  2943. * @throws IllegalArgumentException
  2944. * if given header caption is null
  2945. */
  2946. public Column(String caption) throws IllegalArgumentException {
  2947. this();
  2948. setHeaderCaption(caption);
  2949. }
  2950. /**
  2951. * Constructs a new column with a custom renderer.
  2952. *
  2953. * @param renderer
  2954. * The renderer to use for rendering the cells
  2955. *
  2956. * @throws IllegalArgumentException
  2957. * if given Renderer is null
  2958. */
  2959. public Column(Renderer<? super C> renderer)
  2960. throws IllegalArgumentException {
  2961. setRenderer(renderer);
  2962. }
  2963. /**
  2964. * Constructs a new column with a custom renderer.
  2965. *
  2966. * @param renderer
  2967. * The renderer to use for rendering the cells
  2968. * @param caption
  2969. * The header caption for this column
  2970. *
  2971. * @throws IllegalArgumentException
  2972. * if given Renderer or header caption is null
  2973. */
  2974. public Column(String caption, Renderer<? super C> renderer)
  2975. throws IllegalArgumentException {
  2976. this(renderer);
  2977. setHeaderCaption(caption);
  2978. }
  2979. /**
  2980. * Internally used by the grid to set itself
  2981. *
  2982. * @param grid
  2983. */
  2984. private void setGrid(Grid<T> grid) {
  2985. if (this.grid != null && grid != null) {
  2986. // Trying to replace grid
  2987. throw new IllegalStateException("Column already is attached "
  2988. + "to a grid. Remove the column first from the grid "
  2989. + "and then add it. (in: " + toString() + ")");
  2990. }
  2991. if (this.grid != null) {
  2992. this.grid.autoColumnWidthsRecalculator.schedule();
  2993. }
  2994. this.grid = grid;
  2995. if (this.grid != null) {
  2996. this.grid.autoColumnWidthsRecalculator.schedule();
  2997. updateHeader();
  2998. }
  2999. }
  3000. /**
  3001. * Sets a header caption for this column.
  3002. *
  3003. * @param caption
  3004. * The header caption for this column
  3005. * @return the column itself
  3006. *
  3007. * @throws IllegalArgumentException
  3008. * if given caption text is null
  3009. */
  3010. public Column<C, T> setHeaderCaption(String caption) {
  3011. if (caption == null) {
  3012. throw new IllegalArgumentException("Caption cannot be null.");
  3013. }
  3014. if (!this.headerCaption.equals(caption)) {
  3015. this.headerCaption = caption;
  3016. if (grid != null) {
  3017. updateHeader();
  3018. }
  3019. }
  3020. return this;
  3021. }
  3022. private void updateHeader() {
  3023. HeaderRow row = grid.getHeader().getDefaultRow();
  3024. if (row != null) {
  3025. row.getCell(this).setText(headerCaption);
  3026. }
  3027. }
  3028. /**
  3029. * Returns the data that should be rendered into the cell. By default
  3030. * returning Strings and Widgets are supported. If the return type is a
  3031. * String then it will be treated as preformatted text.
  3032. * <p>
  3033. * To support other types you will need to pass a custom renderer to the
  3034. * column via the column constructor.
  3035. *
  3036. * @param row
  3037. * The row object that provides the cell content.
  3038. *
  3039. * @return The cell content
  3040. */
  3041. public abstract C getValue(T row);
  3042. /**
  3043. * The renderer to render the cell with. By default renders the data as
  3044. * a String or adds the widget into the cell if the column type is of
  3045. * widget type.
  3046. *
  3047. * @return The renderer to render the cell content with
  3048. */
  3049. public Renderer<? super C> getRenderer() {
  3050. return bodyRenderer;
  3051. }
  3052. /**
  3053. * Sets a custom {@link Renderer} for this column.
  3054. *
  3055. * @param renderer
  3056. * The renderer to use for rendering the cells
  3057. * @return the column itself
  3058. *
  3059. * @throws IllegalArgumentException
  3060. * if given Renderer is null
  3061. */
  3062. public Column<C, T> setRenderer(Renderer<? super C> renderer)
  3063. throws IllegalArgumentException {
  3064. if (renderer == null) {
  3065. throw new IllegalArgumentException("Renderer cannot be null.");
  3066. }
  3067. bodyRenderer = renderer;
  3068. if (grid != null) {
  3069. grid.refreshBody();
  3070. }
  3071. return this;
  3072. }
  3073. /**
  3074. * Sets the pixel width of the column. Use a negative value for the grid
  3075. * to autosize column based on content and available space.
  3076. * <p>
  3077. * This action is done "finally", once the current execution loop
  3078. * returns. This is done to reduce overhead of unintentionally always
  3079. * recalculate all columns, when modifying several columns at once.
  3080. *
  3081. * @param pixels
  3082. * the width in pixels or negative for auto sizing
  3083. */
  3084. public Column<C, T> setWidth(double pixels) {
  3085. if (!WidgetUtil.pixelValuesEqual(widthUser, pixels)) {
  3086. widthUser = pixels;
  3087. scheduleColumnWidthRecalculator();
  3088. }
  3089. return this;
  3090. }
  3091. void doSetWidth(double pixels) {
  3092. if (grid != null) {
  3093. int index = grid.columns.indexOf(this);
  3094. ColumnConfiguration conf = grid.escalator
  3095. .getColumnConfiguration();
  3096. conf.setColumnWidth(index, pixels);
  3097. }
  3098. }
  3099. /**
  3100. * Returns the pixel width of the column as given by the user.
  3101. * <p>
  3102. * <em>Note:</em> If a negative value was given to
  3103. * {@link #setWidth(double)}, that same negative value is returned here.
  3104. *
  3105. * @return pixel width of the column, or a negative number if the column
  3106. * width has been automatically calculated.
  3107. * @see #setWidth(double)
  3108. * @see #getWidthActual()
  3109. */
  3110. public double getWidth() {
  3111. return widthUser;
  3112. }
  3113. /**
  3114. * Returns the effective pixel width of the column.
  3115. * <p>
  3116. * This differs from {@link #getWidth()} only when the column has been
  3117. * automatically resized.
  3118. *
  3119. * @return pixel width of the column.
  3120. */
  3121. public double getWidthActual() {
  3122. return grid.escalator.getColumnConfiguration()
  3123. .getColumnWidthActual(grid.columns.indexOf(this));
  3124. }
  3125. void reapplyWidth() {
  3126. setWidth(getWidth());
  3127. }
  3128. /**
  3129. * Enables sort indicators for the grid.
  3130. * <p>
  3131. * <b>Note:</b>The API can still sort the column even if this is set to
  3132. * <code>false</code>.
  3133. *
  3134. * @param sortable
  3135. * <code>true</code> when column sort indicators are visible.
  3136. * @return the column itself
  3137. */
  3138. public Column<C, T> setSortable(boolean sortable) {
  3139. if (this.sortable != sortable) {
  3140. this.sortable = sortable;
  3141. if (grid != null) {
  3142. grid.refreshHeader();
  3143. }
  3144. }
  3145. return this;
  3146. }
  3147. /**
  3148. * Are sort indicators shown for the column.
  3149. *
  3150. * @return <code>true</code> if the column is sortable
  3151. */
  3152. public boolean isSortable() {
  3153. return sortable;
  3154. }
  3155. @Override
  3156. public String toString() {
  3157. String details = "";
  3158. if (headerCaption != null && !headerCaption.isEmpty()) {
  3159. details += "header:\"" + headerCaption + "\" ";
  3160. } else {
  3161. details += "header:empty ";
  3162. }
  3163. if (grid != null) {
  3164. int index = grid.getColumns().indexOf(this);
  3165. if (index != -1) {
  3166. details += "attached:#" + index + " ";
  3167. } else {
  3168. details += "attached:unindexed ";
  3169. }
  3170. } else {
  3171. details += "detached ";
  3172. }
  3173. details += "sortable:" + sortable + " ";
  3174. return getClass().getSimpleName() + "[" + details.trim() + "]";
  3175. }
  3176. /**
  3177. * Sets the minimum width for this column.
  3178. * <p>
  3179. * This defines the minimum guaranteed pixel width of the column
  3180. * <em>when it is set to expand</em>.
  3181. * <p>
  3182. * This action is done "finally", once the current execution loop
  3183. * returns. This is done to reduce overhead of unintentionally always
  3184. * recalculate all columns, when modifying several columns at once.
  3185. *
  3186. * @param pixels
  3187. * the minimum width
  3188. * @return this column
  3189. */
  3190. public Column<C, T> setMinimumWidth(double pixels) {
  3191. final double maxwidth = getMaximumWidth();
  3192. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  3193. throw new IllegalArgumentException("New minimum width ("
  3194. + pixels + ") was greater than maximum width ("
  3195. + maxwidth + ")");
  3196. }
  3197. if (minimumWidthPx != pixels) {
  3198. minimumWidthPx = pixels;
  3199. scheduleColumnWidthRecalculator();
  3200. }
  3201. return this;
  3202. }
  3203. /**
  3204. * Sets the maximum width for this column.
  3205. * <p>
  3206. * This defines the maximum allowed pixel width of the column
  3207. * <em>when it is set to expand</em>.
  3208. * <p>
  3209. * This action is done "finally", once the current execution loop
  3210. * returns. This is done to reduce overhead of unintentionally always
  3211. * recalculate all columns, when modifying several columns at once.
  3212. *
  3213. * @param pixels
  3214. * the maximum width
  3215. * @param immediately
  3216. * <code>true</code> if the widths should be executed
  3217. * immediately (ignoring lazy loading completely), or
  3218. * <code>false</code> if the command should be run after a
  3219. * while (duplicate non-immediately invocations are ignored).
  3220. * @return this column
  3221. */
  3222. public Column<C, T> setMaximumWidth(double pixels) {
  3223. final double minwidth = getMinimumWidth();
  3224. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  3225. throw new IllegalArgumentException("New maximum width ("
  3226. + pixels + ") was less than minimum width (" + minwidth
  3227. + ")");
  3228. }
  3229. if (maximumWidthPx != pixels) {
  3230. maximumWidthPx = pixels;
  3231. scheduleColumnWidthRecalculator();
  3232. }
  3233. return this;
  3234. }
  3235. /**
  3236. * Sets the ratio with which the column expands.
  3237. * <p>
  3238. * By default, all columns expand equally (treated as if all of them had
  3239. * an expand ratio of 1). Once at least one column gets a defined expand
  3240. * ratio, the implicit expand ratio is removed, and only the defined
  3241. * expand ratios are taken into account.
  3242. * <p>
  3243. * If a column has a defined width ({@link #setWidth(double)}), it
  3244. * overrides this method's effects.
  3245. * <p>
  3246. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  3247. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  3248. * as wide as its contents requires</strong>. The column with a ratio of
  3249. * 1 is as wide as it needs, <strong>plus a third of any excess
  3250. * space</strong>, bceause we have 3 parts total, and this column
  3251. * reservs only one of those. The column with a ratio of 2, is as wide
  3252. * as it needs to be, <strong>plus two thirds</strong> of the excess
  3253. * width.
  3254. * <p>
  3255. * This action is done "finally", once the current execution loop
  3256. * returns. This is done to reduce overhead of unintentionally always
  3257. * recalculate all columns, when modifying several columns at once.
  3258. *
  3259. * @param expandRatio
  3260. * the expand ratio of this column. {@code 0} to not have it
  3261. * expand at all. A negative number to clear the expand
  3262. * value.
  3263. * @return this column
  3264. */
  3265. public Column<C, T> setExpandRatio(int ratio) {
  3266. if (expandRatio != ratio) {
  3267. expandRatio = ratio;
  3268. scheduleColumnWidthRecalculator();
  3269. }
  3270. return this;
  3271. }
  3272. /**
  3273. * Clears the column's expand ratio.
  3274. * <p>
  3275. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  3276. *
  3277. * @return this column
  3278. */
  3279. public Column<C, T> clearExpandRatio() {
  3280. return setExpandRatio(-1);
  3281. }
  3282. /**
  3283. * Gets the minimum width for this column.
  3284. *
  3285. * @return the minimum width for this column
  3286. * @see #setMinimumWidth(double)
  3287. */
  3288. public double getMinimumWidth() {
  3289. return minimumWidthPx;
  3290. }
  3291. /**
  3292. * Gets the maximum width for this column.
  3293. *
  3294. * @return the maximum width for this column
  3295. * @see #setMaximumWidth(double)
  3296. */
  3297. public double getMaximumWidth() {
  3298. return maximumWidthPx;
  3299. }
  3300. /**
  3301. * Gets the expand ratio for this column.
  3302. *
  3303. * @return the expand ratio for this column
  3304. * @see #setExpandRatio(int)
  3305. */
  3306. public int getExpandRatio() {
  3307. return expandRatio;
  3308. }
  3309. /**
  3310. * Sets whether the values in this column should be editable by the user
  3311. * when the row editor is active. By default columns are editable.
  3312. *
  3313. * @param editable
  3314. * {@code true} to set this column editable, {@code false}
  3315. * otherwise
  3316. * @return this column
  3317. *
  3318. * @throws IllegalStateException
  3319. * if the editor is currently active
  3320. *
  3321. * @see Grid#editRow(int)
  3322. * @see Grid#isEditorActive()
  3323. */
  3324. public Column<C, T> setEditable(boolean editable) {
  3325. if (editable != this.editable && grid.isEditorActive()) {
  3326. throw new IllegalStateException(
  3327. "Cannot change column editable status while the editor is active");
  3328. }
  3329. this.editable = editable;
  3330. return this;
  3331. }
  3332. /**
  3333. * Returns whether the values in this column are editable by the user
  3334. * when the row editor is active.
  3335. *
  3336. * @return {@code true} if this column is editable, {@code false}
  3337. * otherwise
  3338. *
  3339. * @see #setEditable(boolean)
  3340. */
  3341. public boolean isEditable() {
  3342. return editable;
  3343. }
  3344. private void scheduleColumnWidthRecalculator() {
  3345. if (grid != null) {
  3346. grid.autoColumnWidthsRecalculator.schedule();
  3347. } else {
  3348. /*
  3349. * NOOP
  3350. *
  3351. * Since setGrid() will call reapplyWidths as the colum is
  3352. * attached to a grid, it will call setWidth, which, in turn,
  3353. * will call this method again. Therefore, it's guaranteed that
  3354. * the recalculation is scheduled eventually, once the column is
  3355. * attached to a grid.
  3356. */
  3357. }
  3358. }
  3359. }
  3360. protected class BodyUpdater implements EscalatorUpdater {
  3361. @Override
  3362. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  3363. int rowIndex = row.getRow();
  3364. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  3365. row.getElement());
  3366. for (FlyweightCell cell : cellsToAttach) {
  3367. Renderer<?> renderer = findRenderer(cell);
  3368. if (renderer instanceof ComplexRenderer) {
  3369. try {
  3370. rendererCellReference.set(cell,
  3371. getColumn(cell.getColumn()));
  3372. ((ComplexRenderer<?>) renderer)
  3373. .init(rendererCellReference);
  3374. } catch (RuntimeException e) {
  3375. getLogger().log(
  3376. Level.SEVERE,
  3377. "Error initing cell in column "
  3378. + cell.getColumn(), e);
  3379. }
  3380. }
  3381. }
  3382. }
  3383. @Override
  3384. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  3385. for (FlyweightCell cell : attachedCells) {
  3386. Renderer<?> renderer = findRenderer(cell);
  3387. if (renderer instanceof WidgetRenderer) {
  3388. try {
  3389. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  3390. Widget widget = widgetRenderer.createWidget();
  3391. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  3392. assert widget.getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  3393. assert cell.getElement().getChildCount() == 0 : "Cell content should be empty when adding Widget";
  3394. // Physical attach
  3395. cell.getElement().appendChild(widget.getElement());
  3396. // Logical attach
  3397. setParent(widget, Grid.this);
  3398. } catch (RuntimeException e) {
  3399. getLogger().log(
  3400. Level.SEVERE,
  3401. "Error attaching child widget in column "
  3402. + cell.getColumn(), e);
  3403. }
  3404. }
  3405. }
  3406. }
  3407. @Override
  3408. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  3409. int rowIndex = row.getRow();
  3410. TableRowElement rowElement = row.getElement();
  3411. T rowData = dataSource.getRow(rowIndex);
  3412. boolean hasData = rowData != null;
  3413. /*
  3414. * TODO could be more efficient to build a list of all styles that
  3415. * should be used and update the element only once instead of
  3416. * attempting to update only the ones that have changed.
  3417. */
  3418. // Assign stylename for rows with data
  3419. boolean usedToHaveData = rowElement
  3420. .hasClassName(rowHasDataStyleName);
  3421. if (usedToHaveData != hasData) {
  3422. setStyleName(rowElement, rowHasDataStyleName, hasData);
  3423. }
  3424. boolean isEvenIndex = (row.getRow() % 2 == 0);
  3425. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  3426. rowReference.set(rowIndex, rowData, rowElement);
  3427. if (hasData) {
  3428. setStyleName(rowElement, rowSelectedStyleName,
  3429. isSelected(rowData));
  3430. if (rowStyleGenerator != null) {
  3431. try {
  3432. String rowStylename = rowStyleGenerator
  3433. .getStyle(rowReference);
  3434. setCustomStyleName(rowElement, rowStylename);
  3435. } catch (RuntimeException e) {
  3436. getLogger().log(
  3437. Level.SEVERE,
  3438. "Error generating styles for row "
  3439. + row.getRow(), e);
  3440. }
  3441. } else {
  3442. // Remove in case there was a generator previously
  3443. setCustomStyleName(rowElement, null);
  3444. }
  3445. } else if (usedToHaveData) {
  3446. setStyleName(rowElement, rowSelectedStyleName, false);
  3447. setCustomStyleName(rowElement, null);
  3448. }
  3449. cellFocusHandler.updateFocusedRowStyle(row);
  3450. for (FlyweightCell cell : cellsToUpdate) {
  3451. Column<?, T> column = getColumn(cell.getColumn());
  3452. assert column != null : "Column was not found from cell ("
  3453. + cell.getColumn() + "," + cell.getRow() + ")";
  3454. cellFocusHandler.updateFocusedCellStyle(cell,
  3455. escalator.getBody());
  3456. if (hasData && cellStyleGenerator != null) {
  3457. try {
  3458. cellReference.set(cell.getColumn(), column);
  3459. String generatedStyle = cellStyleGenerator
  3460. .getStyle(cellReference);
  3461. setCustomStyleName(cell.getElement(), generatedStyle);
  3462. } catch (RuntimeException e) {
  3463. getLogger().log(
  3464. Level.SEVERE,
  3465. "Error generating style for cell in column "
  3466. + cell.getColumn(), e);
  3467. }
  3468. } else if (hasData || usedToHaveData) {
  3469. setCustomStyleName(cell.getElement(), null);
  3470. }
  3471. Renderer renderer = column.getRenderer();
  3472. try {
  3473. rendererCellReference.set(cell, column);
  3474. if (renderer instanceof ComplexRenderer) {
  3475. // Hide cell content if needed
  3476. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  3477. if (hasData) {
  3478. if (!usedToHaveData) {
  3479. // Prepare cell for rendering
  3480. clxRenderer.setContentVisible(
  3481. rendererCellReference, true);
  3482. }
  3483. Object value = column.getValue(rowData);
  3484. clxRenderer.render(rendererCellReference, value);
  3485. } else {
  3486. // Prepare cell for no data
  3487. clxRenderer.setContentVisible(
  3488. rendererCellReference, false);
  3489. }
  3490. } else if (hasData) {
  3491. // Simple renderers just render
  3492. Object value = column.getValue(rowData);
  3493. renderer.render(rendererCellReference, value);
  3494. } else {
  3495. // Clear cell if there is no data
  3496. cell.getElement().removeAllChildren();
  3497. }
  3498. } catch (RuntimeException e) {
  3499. getLogger().log(
  3500. Level.SEVERE,
  3501. "Error rendering cell in column "
  3502. + cell.getColumn(), e);
  3503. }
  3504. }
  3505. }
  3506. @Override
  3507. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  3508. for (FlyweightCell cell : cellsToDetach) {
  3509. Renderer renderer = findRenderer(cell);
  3510. if (renderer instanceof WidgetRenderer) {
  3511. try {
  3512. Widget w = WidgetUtil.findWidget(cell.getElement()
  3513. .getFirstChildElement(), Widget.class);
  3514. if (w != null) {
  3515. // Logical detach
  3516. setParent(w, null);
  3517. // Physical detach
  3518. cell.getElement().removeChild(w.getElement());
  3519. }
  3520. } catch (RuntimeException e) {
  3521. getLogger().log(
  3522. Level.SEVERE,
  3523. "Error detaching widget in column "
  3524. + cell.getColumn(), e);
  3525. }
  3526. }
  3527. }
  3528. }
  3529. @Override
  3530. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  3531. int rowIndex = row.getRow();
  3532. // Passing null row data since it might not exist in the data source
  3533. // any more
  3534. rowReference.set(rowIndex, null, row.getElement());
  3535. for (FlyweightCell cell : detachedCells) {
  3536. Renderer renderer = findRenderer(cell);
  3537. if (renderer instanceof ComplexRenderer) {
  3538. try {
  3539. rendererCellReference.set(cell,
  3540. getColumn(cell.getColumn()));
  3541. ((ComplexRenderer) renderer)
  3542. .destroy(rendererCellReference);
  3543. } catch (RuntimeException e) {
  3544. getLogger().log(
  3545. Level.SEVERE,
  3546. "Error destroying cell in column "
  3547. + cell.getColumn(), e);
  3548. }
  3549. }
  3550. }
  3551. }
  3552. }
  3553. protected class StaticSectionUpdater implements EscalatorUpdater {
  3554. private StaticSection<?> section;
  3555. private RowContainer container;
  3556. public StaticSectionUpdater(StaticSection<?> section,
  3557. RowContainer container) {
  3558. super();
  3559. this.section = section;
  3560. this.container = container;
  3561. }
  3562. @Override
  3563. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  3564. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  3565. final List<Column<?, T>> columns = getColumns();
  3566. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  3567. for (FlyweightCell cell : cellsToUpdate) {
  3568. final StaticSection.StaticCell metadata = staticRow
  3569. .getCell(columns.get(cell.getColumn()));
  3570. // Decorate default row with sorting indicators
  3571. if (staticRow instanceof HeaderRow) {
  3572. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow, cell);
  3573. }
  3574. // Assign colspan to cell before rendering
  3575. cell.setColSpan(metadata.getColspan());
  3576. TableCellElement element = cell.getElement();
  3577. switch (metadata.getType()) {
  3578. case TEXT:
  3579. element.setInnerText(metadata.getText());
  3580. break;
  3581. case HTML:
  3582. element.setInnerHTML(metadata.getHtml());
  3583. break;
  3584. case WIDGET:
  3585. preDetach(row, Arrays.asList(cell));
  3586. element.setInnerHTML("");
  3587. postAttach(row, Arrays.asList(cell));
  3588. break;
  3589. }
  3590. setCustomStyleName(element, metadata.getStyleName());
  3591. cellFocusHandler.updateFocusedCellStyle(cell, container);
  3592. }
  3593. }
  3594. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  3595. FlyweightCell cell) {
  3596. cleanup(cell);
  3597. Column<?, ?> column = getColumn(cell.getColumn());
  3598. SortOrder sortingOrder = getSortOrder(column);
  3599. if (!headerRow.isDefault() || !column.isSortable()
  3600. || sortingOrder == null) {
  3601. // Only apply sorting indicators to sortable header columns in
  3602. // the default header row
  3603. return;
  3604. }
  3605. Element cellElement = cell.getElement();
  3606. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  3607. cellElement.addClassName("sort-asc");
  3608. } else {
  3609. cellElement.addClassName("sort-desc");
  3610. }
  3611. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  3612. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  3613. // Show sort order indicator if column is
  3614. // sorted and other sorted columns also exists.
  3615. cellElement.setAttribute("sort-order",
  3616. String.valueOf(sortIndex + 1));
  3617. }
  3618. }
  3619. /**
  3620. * Finds the sort order for this column
  3621. */
  3622. private SortOrder getSortOrder(Column<?, ?> column) {
  3623. for (SortOrder order : Grid.this.getSortOrder()) {
  3624. if (order.getColumn() == column) {
  3625. return order;
  3626. }
  3627. }
  3628. return null;
  3629. }
  3630. private void cleanup(FlyweightCell cell) {
  3631. Element cellElement = cell.getElement();
  3632. cellElement.removeAttribute("sort-order");
  3633. cellElement.removeClassName("sort-desc");
  3634. cellElement.removeClassName("sort-asc");
  3635. }
  3636. @Override
  3637. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  3638. }
  3639. @Override
  3640. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  3641. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  3642. List<Column<?, T>> columns = getColumns();
  3643. for (FlyweightCell cell : attachedCells) {
  3644. StaticSection.StaticCell metadata = gridRow.getCell(columns
  3645. .get(cell.getColumn()));
  3646. /*
  3647. * If the cell contains widgets that are not currently attach
  3648. * then attach them now.
  3649. */
  3650. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  3651. final Widget widget = metadata.getWidget();
  3652. final Element cellElement = cell.getElement();
  3653. if (!widget.isAttached()) {
  3654. // Physical attach
  3655. cellElement.appendChild(widget.getElement());
  3656. // Logical attach
  3657. setParent(widget, Grid.this);
  3658. }
  3659. }
  3660. }
  3661. }
  3662. @Override
  3663. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  3664. if (section.getRowCount() > row.getRow()) {
  3665. StaticSection.StaticRow<?> gridRow = section.getRow(row
  3666. .getRow());
  3667. List<Column<?, T>> columns = getColumns();
  3668. for (FlyweightCell cell : cellsToDetach) {
  3669. StaticSection.StaticCell metadata = gridRow.getCell(columns
  3670. .get(cell.getColumn()));
  3671. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  3672. && metadata.getWidget().isAttached()) {
  3673. Widget widget = metadata.getWidget();
  3674. // Logical detach
  3675. setParent(widget, null);
  3676. // Physical detach
  3677. widget.getElement().removeFromParent();
  3678. }
  3679. }
  3680. }
  3681. }
  3682. @Override
  3683. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  3684. }
  3685. };
  3686. /**
  3687. * Creates a new instance.
  3688. */
  3689. public Grid() {
  3690. initWidget(escalator);
  3691. getElement().setTabIndex(0);
  3692. cellFocusHandler = new CellFocusHandler();
  3693. setStylePrimaryName("v-grid");
  3694. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  3695. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  3696. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  3697. header.setGrid(this);
  3698. HeaderRow defaultRow = header.appendRow();
  3699. header.setDefaultRow(defaultRow);
  3700. footer.setGrid(this);
  3701. editor.setGrid(this);
  3702. setSelectionMode(SelectionMode.SINGLE);
  3703. escalator.addScrollHandler(new ScrollHandler() {
  3704. @Override
  3705. public void onScroll(ScrollEvent event) {
  3706. fireEvent(new ScrollEvent());
  3707. }
  3708. });
  3709. escalator
  3710. .addRowVisibilityChangeHandler(new RowVisibilityChangeHandler() {
  3711. @Override
  3712. public void onRowVisibilityChange(
  3713. RowVisibilityChangeEvent event) {
  3714. if (dataSource != null && dataSource.size() != 0) {
  3715. dataIsBeingFetched = true;
  3716. dataSource.ensureAvailability(
  3717. event.getFirstVisibleRow(),
  3718. event.getVisibleRowCount());
  3719. }
  3720. }
  3721. });
  3722. // Default action on SelectionEvents. Refresh the body so changed
  3723. // become visible.
  3724. addSelectionHandler(new SelectionHandler<T>() {
  3725. @Override
  3726. public void onSelect(SelectionEvent<T> event) {
  3727. refreshBody();
  3728. }
  3729. });
  3730. // Sink header events and key events
  3731. sinkEvents(getHeader().getConsumedEvents());
  3732. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  3733. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  3734. BrowserEvents.MOUSEDOWN));
  3735. // Make ENTER and SHIFT+ENTER in the header perform sorting
  3736. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  3737. @Override
  3738. public void onKeyUp(GridKeyUpEvent event) {
  3739. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  3740. return;
  3741. }
  3742. sorter.sort(event.getFocusedCell().getColumn(),
  3743. event.isShiftKeyDown());
  3744. }
  3745. });
  3746. addDataAvailableHandler(new DataAvailableHandler() {
  3747. @Override
  3748. public void onDataAvailable(DataAvailableEvent event) {
  3749. dataIsBeingFetched = false;
  3750. }
  3751. });
  3752. }
  3753. @Override
  3754. public boolean isEnabled() {
  3755. return enabled;
  3756. }
  3757. @Override
  3758. public void setEnabled(boolean enabled) {
  3759. if (enabled == this.enabled) {
  3760. return;
  3761. }
  3762. this.enabled = enabled;
  3763. getElement().setTabIndex(enabled ? 0 : -1);
  3764. // Editor save and cancel buttons need to be disabled.
  3765. boolean editorOpen = editor.getState() != State.INACTIVE;
  3766. if (editorOpen) {
  3767. editor.setGridEnabled(enabled);
  3768. }
  3769. getEscalator().setScrollLocked(Direction.VERTICAL,
  3770. !enabled || editorOpen);
  3771. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  3772. }
  3773. @Override
  3774. public void setStylePrimaryName(String style) {
  3775. super.setStylePrimaryName(style);
  3776. escalator.setStylePrimaryName(style);
  3777. editor.setStylePrimaryName(style);
  3778. String rowStyle = getStylePrimaryName() + "-row";
  3779. rowHasDataStyleName = rowStyle + "-has-data";
  3780. rowSelectedStyleName = rowStyle + "-selected";
  3781. rowStripeStyleName = rowStyle + "-stripe";
  3782. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  3783. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  3784. if (isAttached()) {
  3785. refreshHeader();
  3786. refreshBody();
  3787. refreshFooter();
  3788. }
  3789. }
  3790. /**
  3791. * Creates the escalator updater used to update the header rows in this
  3792. * grid. The updater is invoked when header rows or columns are added or
  3793. * removed, or the content of existing header cells is changed.
  3794. *
  3795. * @return the new header updater instance
  3796. *
  3797. * @see GridHeader
  3798. * @see Grid#getHeader()
  3799. */
  3800. protected EscalatorUpdater createHeaderUpdater() {
  3801. return new StaticSectionUpdater(header, escalator.getHeader());
  3802. }
  3803. /**
  3804. * Creates the escalator updater used to update the body rows in this grid.
  3805. * The updater is invoked when body rows or columns are added or removed,
  3806. * the content of body cells is changed, or the body is scrolled to expose
  3807. * previously hidden content.
  3808. *
  3809. * @return the new body updater instance
  3810. */
  3811. protected EscalatorUpdater createBodyUpdater() {
  3812. return new BodyUpdater();
  3813. }
  3814. /**
  3815. * Creates the escalator updater used to update the footer rows in this
  3816. * grid. The updater is invoked when header rows or columns are added or
  3817. * removed, or the content of existing header cells is changed.
  3818. *
  3819. * @return the new footer updater instance
  3820. *
  3821. * @see GridFooter
  3822. * @see #getFooter()
  3823. */
  3824. protected EscalatorUpdater createFooterUpdater() {
  3825. return new StaticSectionUpdater(footer, escalator.getFooter());
  3826. }
  3827. /**
  3828. * Refreshes header or footer rows on demand
  3829. *
  3830. * @param rows
  3831. * The row container
  3832. * @param firstRowIsVisible
  3833. * is the first row visible
  3834. * @param isHeader
  3835. * <code>true</code> if we refreshing the header, else assumed
  3836. * the footer
  3837. */
  3838. private void refreshRowContainer(RowContainer rows, StaticSection<?> section) {
  3839. // Add or Remove rows on demand
  3840. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  3841. if (rowDiff > 0) {
  3842. rows.insertRows(0, rowDiff);
  3843. } else if (rowDiff < 0) {
  3844. rows.removeRows(0, -rowDiff);
  3845. }
  3846. // Refresh all the rows
  3847. if (rows.getRowCount() > 0) {
  3848. rows.refreshRows(0, rows.getRowCount());
  3849. }
  3850. }
  3851. /**
  3852. * Refreshes all header rows
  3853. */
  3854. void refreshHeader() {
  3855. refreshRowContainer(escalator.getHeader(), header);
  3856. }
  3857. /**
  3858. * Refreshes all body rows
  3859. */
  3860. private void refreshBody() {
  3861. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  3862. }
  3863. /**
  3864. * Refreshes all footer rows
  3865. */
  3866. void refreshFooter() {
  3867. refreshRowContainer(escalator.getFooter(), footer);
  3868. }
  3869. /**
  3870. * Adds columns as the last columns in the grid.
  3871. *
  3872. * @param columns
  3873. * the columns to add
  3874. */
  3875. public void addColumns(Column<?, T>... columns) {
  3876. int count = getColumnCount();
  3877. for (Column<?, T> column : columns) {
  3878. addColumn(column, count++);
  3879. }
  3880. }
  3881. /**
  3882. * Adds a column as the last column in the grid.
  3883. *
  3884. * @param column
  3885. * the column to add
  3886. * @return given column
  3887. */
  3888. public <C extends Column<?, T>> C addColumn(C column) {
  3889. addColumn(column, getColumnCount());
  3890. return column;
  3891. }
  3892. /**
  3893. * Inserts a column into a specific position in the grid.
  3894. *
  3895. * @param index
  3896. * the index where the column should be inserted into
  3897. * @param column
  3898. * the column to add
  3899. * @return given column
  3900. *
  3901. * @throws IllegalStateException
  3902. * if Grid's current selection model renders a selection column,
  3903. * and {@code index} is 0.
  3904. */
  3905. public <C extends Column<?, T>> C addColumn(C column, int index) {
  3906. if (column == selectionColumn) {
  3907. throw new IllegalArgumentException("The selection column many "
  3908. + "not be added manually");
  3909. } else if (selectionColumn != null && index == 0) {
  3910. throw new IllegalStateException("A column cannot be inserted "
  3911. + "before the selection column");
  3912. }
  3913. addColumnSkipSelectionColumnCheck(column, index);
  3914. return column;
  3915. }
  3916. private void addColumnSkipSelectionColumnCheck(Column<?, T> column,
  3917. int index) {
  3918. // Register column with grid
  3919. columns.add(index, column);
  3920. header.addColumn(column);
  3921. footer.addColumn(column);
  3922. // Register this grid instance with the column
  3923. ((Column<?, T>) column).setGrid(this);
  3924. // Add to escalator
  3925. escalator.getColumnConfiguration().insertColumns(index, 1);
  3926. // Reapply column width
  3927. column.reapplyWidth();
  3928. // Sink all renderer events
  3929. Set<String> events = new HashSet<String>();
  3930. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  3931. sinkEvents(events);
  3932. }
  3933. private void sinkEvents(Collection<String> events) {
  3934. assert events != null;
  3935. int eventsToSink = 0;
  3936. for (String typeName : events) {
  3937. int typeInt = Event.getTypeInt(typeName);
  3938. if (typeInt < 0) {
  3939. // Type not recognized by typeInt
  3940. sinkBitlessEvent(typeName);
  3941. } else {
  3942. eventsToSink |= typeInt;
  3943. }
  3944. }
  3945. if (eventsToSink > 0) {
  3946. sinkEvents(eventsToSink);
  3947. }
  3948. }
  3949. private Renderer<?> findRenderer(FlyweightCell cell) {
  3950. Column<?, T> column = getColumn(cell.getColumn());
  3951. assert column != null : "Could not find column at index:"
  3952. + cell.getColumn();
  3953. return column.getRenderer();
  3954. }
  3955. /**
  3956. * Removes a column from the grid.
  3957. *
  3958. * @param column
  3959. * the column to remove
  3960. */
  3961. public void removeColumn(Column<?, T> column) {
  3962. if (column != null && column.equals(selectionColumn)) {
  3963. throw new IllegalArgumentException(
  3964. "The selection column may not be removed manually.");
  3965. }
  3966. removeColumnSkipSelectionColumnCheck(column);
  3967. }
  3968. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  3969. int columnIndex = columns.indexOf(column);
  3970. // Remove from column configuration
  3971. escalator.getColumnConfiguration().removeColumns(columnIndex, 1);
  3972. updateFrozenColumns();
  3973. header.removeColumn(column);
  3974. footer.removeColumn(column);
  3975. // de-register column with grid
  3976. ((Column<?, T>) column).setGrid(null);
  3977. columns.remove(columnIndex);
  3978. }
  3979. /**
  3980. * Returns the amount of columns in the grid.
  3981. *
  3982. * @return The number of columns in the grid
  3983. */
  3984. public int getColumnCount() {
  3985. return columns.size();
  3986. }
  3987. /**
  3988. * Returns a list of columns in the grid.
  3989. *
  3990. * @return A unmodifiable list of the columns in the grid
  3991. */
  3992. public List<Column<?, T>> getColumns() {
  3993. return Collections
  3994. .unmodifiableList(new ArrayList<Column<?, T>>(columns));
  3995. }
  3996. /**
  3997. * Returns a column by its index in the grid.
  3998. *
  3999. * @param index
  4000. * the index of the column
  4001. * @return The column in the given index
  4002. * @throws IllegalArgumentException
  4003. * if the column index does not exist in the grid
  4004. */
  4005. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  4006. if (index < 0 || index >= columns.size()) {
  4007. throw new IllegalStateException("Column not found.");
  4008. }
  4009. return columns.get(index);
  4010. }
  4011. /**
  4012. * Returns current index of given column
  4013. *
  4014. * @param column
  4015. * column in grid
  4016. * @return column index, or <code>-1</code> if not in this Grid
  4017. */
  4018. protected int indexOfColumn(Column<?, T> column) {
  4019. return columns.indexOf(column);
  4020. }
  4021. /**
  4022. * Returns the header section of this grid. The default header contains a
  4023. * single row displaying the column captions.
  4024. *
  4025. * @return the header
  4026. */
  4027. protected Header getHeader() {
  4028. return header;
  4029. }
  4030. /**
  4031. * Gets the header row at given index.
  4032. *
  4033. * @param rowIndex
  4034. * 0 based index for row. Counted from top to bottom
  4035. * @return header row at given index
  4036. * @throws IllegalArgumentException
  4037. * if no row exists at given index
  4038. */
  4039. public HeaderRow getHeaderRow(int rowIndex) {
  4040. return header.getRow(rowIndex);
  4041. }
  4042. /**
  4043. * Inserts a new row at the given position to the header section. Shifts the
  4044. * row currently at that position and any subsequent rows down (adds one to
  4045. * their indices).
  4046. *
  4047. * @param index
  4048. * the position at which to insert the row
  4049. * @return the new row
  4050. *
  4051. * @throws IllegalArgumentException
  4052. * if the index is less than 0 or greater than row count
  4053. * @see #appendHeaderRow()
  4054. * @see #prependHeaderRow()
  4055. * @see #removeHeaderRow(HeaderRow)
  4056. * @see #removeHeaderRow(int)
  4057. */
  4058. public HeaderRow addHeaderRowAt(int index) {
  4059. return header.addRowAt(index);
  4060. }
  4061. /**
  4062. * Adds a new row at the bottom of the header section.
  4063. *
  4064. * @return the new row
  4065. * @see #prependHeaderRow()
  4066. * @see #addHeaderRowAt(int)
  4067. * @see #removeHeaderRow(HeaderRow)
  4068. * @see #removeHeaderRow(int)
  4069. */
  4070. public HeaderRow appendHeaderRow() {
  4071. return header.appendRow();
  4072. }
  4073. /**
  4074. * Returns the current default row of the header section. The default row is
  4075. * a special header row providing a user interface for sorting columns.
  4076. * Setting a header caption for column updates cells in the default header.
  4077. *
  4078. * @return the default row or null if no default row set
  4079. */
  4080. public HeaderRow getDefaultHeaderRow() {
  4081. return header.getDefaultRow();
  4082. }
  4083. /**
  4084. * Gets the row count for the header section.
  4085. *
  4086. * @return row count
  4087. */
  4088. public int getHeaderRowCount() {
  4089. return header.getRowCount();
  4090. }
  4091. /**
  4092. * Adds a new row at the top of the header section.
  4093. *
  4094. * @return the new row
  4095. * @see #appendHeaderRow()
  4096. * @see #addHeaderRowAt(int)
  4097. * @see #removeHeaderRow(HeaderRow)
  4098. * @see #removeHeaderRow(int)
  4099. */
  4100. public HeaderRow prependHeaderRow() {
  4101. return header.prependRow();
  4102. }
  4103. /**
  4104. * Removes the given row from the header section.
  4105. *
  4106. * @param row
  4107. * the row to be removed
  4108. *
  4109. * @throws IllegalArgumentException
  4110. * if the row does not exist in this section
  4111. * @see #removeHeaderRow(int)
  4112. * @see #addHeaderRowAt(int)
  4113. * @see #appendHeaderRow()
  4114. * @see #prependHeaderRow()
  4115. */
  4116. public void removeHeaderRow(HeaderRow row) {
  4117. header.removeRow(row);
  4118. }
  4119. /**
  4120. * Removes the row at the given position from the header section.
  4121. *
  4122. * @param index
  4123. * the position of the row
  4124. *
  4125. * @throws IllegalArgumentException
  4126. * if no row exists at given index
  4127. * @see #removeHeaderRow(HeaderRow)
  4128. * @see #addHeaderRowAt(int)
  4129. * @see #appendHeaderRow()
  4130. * @see #prependHeaderRow()
  4131. */
  4132. public void removeHeaderRow(int rowIndex) {
  4133. header.removeRow(rowIndex);
  4134. }
  4135. /**
  4136. * Sets the default row of the header. The default row is a special header
  4137. * row providing a user interface for sorting columns.
  4138. *
  4139. * @param row
  4140. * the new default row, or null for no default row
  4141. *
  4142. * @throws IllegalArgumentException
  4143. * header does not contain the row
  4144. */
  4145. public void setDefaultHeaderRow(HeaderRow row) {
  4146. header.setDefaultRow(row);
  4147. }
  4148. /**
  4149. * Sets the visibility of the header section.
  4150. *
  4151. * @param visible
  4152. * true to show header section, false to hide
  4153. */
  4154. public void setHeaderVisible(boolean visible) {
  4155. header.setVisible(visible);
  4156. }
  4157. /**
  4158. * Returns the visibility of the header section.
  4159. *
  4160. * @return true if visible, false otherwise.
  4161. */
  4162. public boolean isHeaderVisible() {
  4163. return header.isVisible();
  4164. }
  4165. /* Grid Footers */
  4166. /**
  4167. * Returns the footer section of this grid. The default footer is empty.
  4168. *
  4169. * @return the footer
  4170. */
  4171. protected Footer getFooter() {
  4172. return footer;
  4173. }
  4174. /**
  4175. * Gets the footer row at given index.
  4176. *
  4177. * @param rowIndex
  4178. * 0 based index for row. Counted from top to bottom
  4179. * @return footer row at given index
  4180. * @throws IllegalArgumentException
  4181. * if no row exists at given index
  4182. */
  4183. public FooterRow getFooterRow(int rowIndex) {
  4184. return footer.getRow(rowIndex);
  4185. }
  4186. /**
  4187. * Inserts a new row at the given position to the footer section. Shifts the
  4188. * row currently at that position and any subsequent rows down (adds one to
  4189. * their indices).
  4190. *
  4191. * @param index
  4192. * the position at which to insert the row
  4193. * @return the new row
  4194. *
  4195. * @throws IllegalArgumentException
  4196. * if the index is less than 0 or greater than row count
  4197. * @see #appendFooterRow()
  4198. * @see #prependFooterRow()
  4199. * @see #removeFooterRow(FooterRow)
  4200. * @see #removeFooterRow(int)
  4201. */
  4202. public FooterRow addFooterRowAt(int index) {
  4203. return footer.addRowAt(index);
  4204. }
  4205. /**
  4206. * Adds a new row at the bottom of the footer section.
  4207. *
  4208. * @return the new row
  4209. * @see #prependFooterRow()
  4210. * @see #addFooterRowAt(int)
  4211. * @see #removeFooterRow(FooterRow)
  4212. * @see #removeFooterRow(int)
  4213. */
  4214. public FooterRow appendFooterRow() {
  4215. return footer.appendRow();
  4216. }
  4217. /**
  4218. * Gets the row count for the footer.
  4219. *
  4220. * @return row count
  4221. */
  4222. public int getFooterRowCount() {
  4223. return footer.getRowCount();
  4224. }
  4225. /**
  4226. * Adds a new row at the top of the footer section.
  4227. *
  4228. * @return the new row
  4229. * @see #appendFooterRow()
  4230. * @see #addFooterRowAt(int)
  4231. * @see #removeFooterRow(FooterRow)
  4232. * @see #removeFooterRow(int)
  4233. */
  4234. public FooterRow prependFooterRow() {
  4235. return footer.prependRow();
  4236. }
  4237. /**
  4238. * Removes the given row from the footer section.
  4239. *
  4240. * @param row
  4241. * the row to be removed
  4242. *
  4243. * @throws IllegalArgumentException
  4244. * if the row does not exist in this section
  4245. * @see #removeFooterRow(int)
  4246. * @see #addFooterRowAt(int)
  4247. * @see #appendFooterRow()
  4248. * @see #prependFooterRow()
  4249. */
  4250. public void removeFooterRow(FooterRow row) {
  4251. footer.removeRow(row);
  4252. }
  4253. /**
  4254. * Removes the row at the given position from the footer section.
  4255. *
  4256. * @param index
  4257. * the position of the row
  4258. *
  4259. * @throws IllegalArgumentException
  4260. * if no row exists at given index
  4261. * @see #removeFooterRow(FooterRow)
  4262. * @see #addFooterRowAt(int)
  4263. * @see #appendFooterRow()
  4264. * @see #prependFooterRow()
  4265. */
  4266. public void removeFooterRow(int rowIndex) {
  4267. footer.removeRow(rowIndex);
  4268. }
  4269. /**
  4270. * Sets the visibility of the footer section.
  4271. *
  4272. * @param visible
  4273. * true to show footer section, false to hide
  4274. */
  4275. public void setFooterVisible(boolean visible) {
  4276. footer.setVisible(visible);
  4277. }
  4278. /**
  4279. * Returns the visibility of the footer section.
  4280. *
  4281. * @return true if visible, false otherwise.
  4282. */
  4283. public boolean isFooterVisible() {
  4284. return footer.isVisible();
  4285. }
  4286. protected Editor<T> getEditor() {
  4287. return editor;
  4288. }
  4289. protected Escalator getEscalator() {
  4290. return escalator;
  4291. }
  4292. /**
  4293. * {@inheritDoc}
  4294. * <p>
  4295. * <em>Note:</em> This method will change the widget's size in the browser
  4296. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  4297. *
  4298. * @see #setHeightMode(HeightMode)
  4299. */
  4300. @Override
  4301. public void setHeight(String height) {
  4302. escalator.setHeight(height);
  4303. }
  4304. @Override
  4305. public void setWidth(String width) {
  4306. escalator.setWidth(width);
  4307. }
  4308. /**
  4309. * Sets the data source used by this grid.
  4310. *
  4311. * @param dataSource
  4312. * the data source to use, not null
  4313. * @throws IllegalArgumentException
  4314. * if <code>dataSource</code> is <code>null</code>
  4315. */
  4316. public void setDataSource(final DataSource<T> dataSource)
  4317. throws IllegalArgumentException {
  4318. if (dataSource == null) {
  4319. throw new IllegalArgumentException("dataSource can't be null.");
  4320. }
  4321. selectionModel.reset();
  4322. if (this.dataSource != null) {
  4323. this.dataSource.setDataChangeHandler(null);
  4324. }
  4325. this.dataSource = dataSource;
  4326. dataSource.setDataChangeHandler(new DataChangeHandler() {
  4327. @Override
  4328. public void dataUpdated(int firstIndex, int numberOfItems) {
  4329. escalator.getBody().refreshRows(firstIndex, numberOfItems);
  4330. }
  4331. @Override
  4332. public void dataRemoved(int firstIndex, int numberOfItems) {
  4333. escalator.getBody().removeRows(firstIndex, numberOfItems);
  4334. Range removed = Range.withLength(firstIndex, numberOfItems);
  4335. cellFocusHandler.rowsRemovedFromBody(removed);
  4336. }
  4337. @Override
  4338. public void dataAdded(int firstIndex, int numberOfItems) {
  4339. escalator.getBody().insertRows(firstIndex, numberOfItems);
  4340. Range added = Range.withLength(firstIndex, numberOfItems);
  4341. cellFocusHandler.rowsAddedToBody(added);
  4342. }
  4343. @Override
  4344. public void dataAvailable(int firstIndex, int numberOfItems) {
  4345. currentDataAvailable = Range.withLength(firstIndex,
  4346. numberOfItems);
  4347. fireEvent(new DataAvailableEvent(currentDataAvailable));
  4348. }
  4349. @Override
  4350. public void resetDataAndSize(int newSize) {
  4351. RowContainer body = escalator.getBody();
  4352. int oldSize = body.getRowCount();
  4353. if (newSize > oldSize) {
  4354. body.insertRows(oldSize, newSize - oldSize);
  4355. } else if (newSize < oldSize) {
  4356. body.removeRows(newSize, oldSize - newSize);
  4357. }
  4358. if (newSize > 0) {
  4359. dataIsBeingFetched = true;
  4360. Range visibleRowRange = escalator.getVisibleRowRange();
  4361. dataSource.ensureAvailability(visibleRowRange.getStart(),
  4362. visibleRowRange.length());
  4363. }
  4364. assert body.getRowCount() == newSize;
  4365. }
  4366. });
  4367. int previousRowCount = escalator.getBody().getRowCount();
  4368. if (previousRowCount != 0) {
  4369. escalator.getBody().removeRows(0, previousRowCount);
  4370. }
  4371. setEscalatorSizeFromDataSource();
  4372. }
  4373. private void setEscalatorSizeFromDataSource() {
  4374. assert escalator.getBody().getRowCount() == 0;
  4375. int size = dataSource.size();
  4376. if (size == -1 && isAttached()) {
  4377. // Exact size is not yet known, start with some reasonable guess
  4378. // just to get an initial backend request going
  4379. size = getEscalator().getMaxVisibleRowCount();
  4380. }
  4381. if (size > 0) {
  4382. escalator.getBody().insertRows(0, size);
  4383. }
  4384. }
  4385. /**
  4386. * Gets the {@Link DataSource} for this Grid.
  4387. *
  4388. * @return the data source used by this grid
  4389. */
  4390. public DataSource<T> getDataSource() {
  4391. return dataSource;
  4392. }
  4393. /**
  4394. * Sets the number of frozen columns in this grid. Setting the count to 0
  4395. * means that no data columns will be frozen, but the built-in selection
  4396. * checkbox column will still be frozen if it's in use. Setting the count to
  4397. * -1 will also disable the selection column.
  4398. * <p>
  4399. * The default value is 0.
  4400. *
  4401. * @param numberOfColumns
  4402. * the number of columns that should be frozen
  4403. *
  4404. * @throws IllegalArgumentException
  4405. * if the column count is < -1 or > the number of visible
  4406. * columns
  4407. */
  4408. public void setFrozenColumnCount(int numberOfColumns) {
  4409. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  4410. throw new IllegalArgumentException(
  4411. "count must be between -1 and the current number of columns ("
  4412. + getColumnCount() + ")");
  4413. }
  4414. frozenColumnCount = numberOfColumns;
  4415. updateFrozenColumns();
  4416. }
  4417. private void updateFrozenColumns() {
  4418. int numberOfColumns = frozenColumnCount;
  4419. if (numberOfColumns == -1) {
  4420. numberOfColumns = 0;
  4421. } else if (selectionColumn != null) {
  4422. numberOfColumns++;
  4423. }
  4424. escalator.getColumnConfiguration()
  4425. .setFrozenColumnCount(numberOfColumns);
  4426. }
  4427. /**
  4428. * Gets the number of frozen columns in this grid. 0 means that no data
  4429. * columns will be frozen, but the built-in selection checkbox column will
  4430. * still be frozen if it's in use. -1 means that not even the selection
  4431. * column is frozen.
  4432. *
  4433. * @return the number of frozen columns
  4434. */
  4435. public int getFrozenColumnCount() {
  4436. return frozenColumnCount;
  4437. }
  4438. public HandlerRegistration addRowVisibilityChangeHandler(
  4439. RowVisibilityChangeHandler handler) {
  4440. /*
  4441. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  4442. * concept is too abstract. e.g. the event needs to be re-sent when the
  4443. * widget is resized.
  4444. */
  4445. return escalator.addRowVisibilityChangeHandler(handler);
  4446. }
  4447. /**
  4448. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  4449. *
  4450. * @param rowIndex
  4451. * zero-based index of the row to scroll to.
  4452. * @throws IllegalArgumentException
  4453. * if rowIndex is below zero, or above the maximum value
  4454. * supported by the data source.
  4455. */
  4456. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  4457. scrollToRow(rowIndex, ScrollDestination.ANY,
  4458. GridConstants.DEFAULT_PADDING);
  4459. }
  4460. /**
  4461. * Scrolls to a certain row, using user-specified scroll destination.
  4462. *
  4463. * @param rowIndex
  4464. * zero-based index of the row to scroll to.
  4465. * @param destination
  4466. * desired destination placement of scrolled-to-row. See
  4467. * {@link ScrollDestination} for more information.
  4468. * @throws IllegalArgumentException
  4469. * if rowIndex is below zero, or above the maximum value
  4470. * supported by the data source.
  4471. */
  4472. public void scrollToRow(int rowIndex, ScrollDestination destination)
  4473. throws IllegalArgumentException {
  4474. scrollToRow(rowIndex, destination,
  4475. destination == ScrollDestination.MIDDLE ? 0
  4476. : GridConstants.DEFAULT_PADDING);
  4477. }
  4478. /**
  4479. * Scrolls to a certain row using only user-specified parameters.
  4480. *
  4481. * @param rowIndex
  4482. * zero-based index of the row to scroll to.
  4483. * @param destination
  4484. * desired destination placement of scrolled-to-row. See
  4485. * {@link ScrollDestination} for more information.
  4486. * @param paddingPx
  4487. * number of pixels to overscroll. Behavior depends on
  4488. * destination.
  4489. * @throws IllegalArgumentException
  4490. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  4491. * and padding is nonzero, because having a padding on a
  4492. * centered row is undefined behavior, or if rowIndex is below
  4493. * zero or above the row count of the data source.
  4494. */
  4495. private void scrollToRow(int rowIndex, ScrollDestination destination,
  4496. int paddingPx) throws IllegalArgumentException {
  4497. int maxsize = escalator.getBody().getRowCount() - 1;
  4498. if (rowIndex < 0) {
  4499. throw new IllegalArgumentException("Row index (" + rowIndex
  4500. + ") is below zero!");
  4501. }
  4502. if (rowIndex > maxsize) {
  4503. throw new IllegalArgumentException("Row index (" + rowIndex
  4504. + ") is above maximum (" + maxsize + ")!");
  4505. }
  4506. escalator.scrollToRow(rowIndex, destination, paddingPx);
  4507. }
  4508. /**
  4509. * Scrolls to the beginning of the very first row.
  4510. */
  4511. public void scrollToStart() {
  4512. scrollToRow(0, ScrollDestination.START);
  4513. }
  4514. /**
  4515. * Scrolls to the end of the very last row.
  4516. */
  4517. public void scrollToEnd() {
  4518. scrollToRow(escalator.getBody().getRowCount() - 1,
  4519. ScrollDestination.END);
  4520. }
  4521. /**
  4522. * Sets the vertical scroll offset.
  4523. *
  4524. * @param px
  4525. * the number of pixels this grid should be scrolled down
  4526. */
  4527. public void setScrollTop(double px) {
  4528. escalator.setScrollTop(px);
  4529. }
  4530. /**
  4531. * Gets the vertical scroll offset
  4532. *
  4533. * @return the number of pixels this grid is scrolled down
  4534. */
  4535. public double getScrollTop() {
  4536. return escalator.getScrollTop();
  4537. }
  4538. /**
  4539. * Sets the horizontal scroll offset
  4540. *
  4541. * @since
  4542. * @param px
  4543. * the number of pixels this grid should be scrolled right
  4544. */
  4545. public void setScrollLeft(double px) {
  4546. escalator.setScrollLeft(px);
  4547. }
  4548. /**
  4549. * Gets the horizontal scroll offset
  4550. *
  4551. * @return the number of pixels this grid is scrolled to the right
  4552. */
  4553. public double getScrollLeft() {
  4554. return escalator.getScrollLeft();
  4555. }
  4556. /**
  4557. * Returns the height of the scrollable area in pixels.
  4558. *
  4559. * @since
  4560. * @return the height of the scrollable area in pixels
  4561. */
  4562. public double getScrollHeight() {
  4563. return escalator.getScrollHeight();
  4564. }
  4565. /**
  4566. * Returns the width of the scrollable area in pixels.
  4567. *
  4568. * @since
  4569. * @return the width of the scrollable area in pixels.
  4570. */
  4571. public double getScrollWidth() {
  4572. return escalator.getScrollWidth();
  4573. }
  4574. private static final Logger getLogger() {
  4575. return Logger.getLogger(Grid.class.getName());
  4576. }
  4577. /**
  4578. * Sets the number of rows that should be visible in Grid's body, while
  4579. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  4580. * <p>
  4581. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  4582. * remembered, and applied once the mode is applied.
  4583. *
  4584. * @param rows
  4585. * The height in terms of number of rows displayed in Grid's
  4586. * body. If Grid doesn't contain enough rows, white space is
  4587. * displayed instead.
  4588. * @throws IllegalArgumentException
  4589. * if {@code rows} is zero or less
  4590. * @throws IllegalArgumentException
  4591. * if {@code rows} is {@link Double#isInifinite(double)
  4592. * infinite}
  4593. * @throws IllegalArgumentException
  4594. * if {@code rows} is {@link Double#isNaN(double) NaN}
  4595. *
  4596. * @see #setHeightMode(HeightMode)
  4597. */
  4598. public void setHeightByRows(double rows) throws IllegalArgumentException {
  4599. escalator.setHeightByRows(rows);
  4600. }
  4601. /**
  4602. * Gets the amount of rows in Grid's body that are shown, while
  4603. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  4604. * <p>
  4605. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  4606. *
  4607. * @return the amount of rows that should be shown in Grid's body, while in
  4608. * {@link HeightMode#ROW}.
  4609. * @see #setHeightByRows(double)
  4610. */
  4611. public double getHeightByRows() {
  4612. return escalator.getHeightByRows();
  4613. }
  4614. /**
  4615. * Defines the mode in which the Grid widget's height is calculated.
  4616. * <p>
  4617. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  4618. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  4619. * <p>
  4620. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  4621. * will display as many rows as {@link #getHeightByRows()} defines.
  4622. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  4623. * will resize itself to still display the required amount of rows in its
  4624. * body. It also takes the horizontal scrollbar into account.
  4625. *
  4626. * @param heightMode
  4627. * the mode in to which Grid should be set
  4628. */
  4629. public void setHeightMode(HeightMode heightMode) {
  4630. /*
  4631. * This method is a workaround for the fact that Vaadin re-applies
  4632. * widget dimensions (height/width) on each state change event. The
  4633. * original design was to have setHeight an setHeightByRow be equals,
  4634. * and whichever was called the latest was considered in effect.
  4635. *
  4636. * But, because of Vaadin always calling setHeight on the widget, this
  4637. * approach doesn't work.
  4638. */
  4639. escalator.setHeightMode(heightMode);
  4640. }
  4641. /**
  4642. * Returns the current {@link HeightMode} the Grid is in.
  4643. * <p>
  4644. * Defaults to {@link HeightMode#CSS}.
  4645. *
  4646. * @return the current HeightMode
  4647. */
  4648. public HeightMode getHeightMode() {
  4649. return escalator.getHeightMode();
  4650. }
  4651. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  4652. Set<String> events = new HashSet<String>();
  4653. if (renderer instanceof ComplexRenderer) {
  4654. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  4655. .getConsumedEvents();
  4656. if (consumedEvents != null) {
  4657. events.addAll(consumedEvents);
  4658. }
  4659. }
  4660. return events;
  4661. }
  4662. @Override
  4663. public void onBrowserEvent(Event event) {
  4664. if (!isEnabled()) {
  4665. return;
  4666. }
  4667. EventTarget target = event.getEventTarget();
  4668. if (!Element.is(target)) {
  4669. return;
  4670. }
  4671. Element e = Element.as(target);
  4672. RowContainer container = escalator.findRowContainer(e);
  4673. Cell cell;
  4674. String eventType = event.getType();
  4675. if (container == null) {
  4676. if (eventType.equals(BrowserEvents.KEYDOWN)
  4677. || eventType.equals(BrowserEvents.KEYUP)
  4678. || eventType.equals(BrowserEvents.KEYPRESS)) {
  4679. cell = cellFocusHandler.getFocusedCell();
  4680. container = cellFocusHandler.containerWithFocus;
  4681. } else {
  4682. // Click in a location that does not contain cells.
  4683. return;
  4684. }
  4685. } else {
  4686. cell = container.getCell(e);
  4687. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  4688. cellOnPrevMouseDown = cell;
  4689. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  4690. /*
  4691. * Chrome has an interesting idea on click targets (see
  4692. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  4693. * the mousedown target as the click target.
  4694. */
  4695. cell = cellOnPrevMouseDown;
  4696. }
  4697. }
  4698. assert cell != null : "received " + eventType
  4699. + "-event with a null cell target";
  4700. eventCell.set(cell);
  4701. // Editor can steal focus from Grid and is still handled
  4702. if (handleEditorEvent(event, container)) {
  4703. return;
  4704. }
  4705. // Fire GridKeyEvents and GridClickEvents. Pass the event to escalator.
  4706. super.onBrowserEvent(event);
  4707. if (!isElementInChildWidget(e)) {
  4708. if (handleHeaderCellDragStartEvent(event, container)) {
  4709. return;
  4710. }
  4711. // Sorting through header Click / KeyUp
  4712. if (handleHeaderDefaultRowEvent(event, container)) {
  4713. return;
  4714. }
  4715. if (handleRendererEvent(event, container)) {
  4716. return;
  4717. }
  4718. if (handleNavigationEvent(event, container)) {
  4719. return;
  4720. }
  4721. if (handleCellFocusEvent(event, container)) {
  4722. return;
  4723. }
  4724. }
  4725. }
  4726. private boolean isElementInChildWidget(Element e) {
  4727. Widget w = WidgetUtil.findWidget(e, null);
  4728. if (w == this) {
  4729. return false;
  4730. }
  4731. /*
  4732. * If e is directly inside this grid, but the grid is wrapped in a
  4733. * Composite, findWidget is not going to find this, only the wrapper.
  4734. * Thus we need to check its parents to see if we encounter this; if we
  4735. * don't, the found widget is actually a parent of this, so we should
  4736. * return false.
  4737. */
  4738. while (w != null && w != this) {
  4739. w = w.getParent();
  4740. }
  4741. return w != null;
  4742. }
  4743. private boolean handleEditorEvent(Event event, RowContainer container) {
  4744. if (editor.getState() != Editor.State.INACTIVE) {
  4745. if (event.getTypeInt() == Event.ONKEYDOWN
  4746. && event.getKeyCode() == Editor.KEYCODE_HIDE) {
  4747. editor.cancel();
  4748. }
  4749. return true;
  4750. }
  4751. if (container == escalator.getBody() && editor.isEnabled()) {
  4752. if (event.getTypeInt() == Event.ONDBLCLICK) {
  4753. editor.editRow(eventCell.getRowIndex());
  4754. return true;
  4755. } else if (event.getTypeInt() == Event.ONKEYDOWN
  4756. && event.getKeyCode() == Editor.KEYCODE_SHOW) {
  4757. editor.editRow(cellFocusHandler.rowWithFocus);
  4758. return true;
  4759. }
  4760. }
  4761. return false;
  4762. }
  4763. private boolean handleRendererEvent(Event event, RowContainer container) {
  4764. if (container == escalator.getBody()) {
  4765. Column<?, T> gridColumn = eventCell.getColumn();
  4766. boolean enterKey = event.getType().equals(BrowserEvents.KEYDOWN)
  4767. && event.getKeyCode() == KeyCodes.KEY_ENTER;
  4768. boolean doubleClick = event.getType()
  4769. .equals(BrowserEvents.DBLCLICK);
  4770. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  4771. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  4772. .getRenderer();
  4773. if (cplxRenderer.getConsumedEvents().contains(event.getType())) {
  4774. if (cplxRenderer.onBrowserEvent(eventCell, event)) {
  4775. return true;
  4776. }
  4777. }
  4778. // Calls onActivate if KeyDown and Enter or double click
  4779. if ((enterKey || doubleClick)
  4780. && cplxRenderer.onActivate(eventCell)) {
  4781. return true;
  4782. }
  4783. }
  4784. }
  4785. return false;
  4786. }
  4787. private boolean handleCellFocusEvent(Event event, RowContainer container) {
  4788. Collection<String> navigation = cellFocusHandler.getNavigationEvents();
  4789. if (navigation.contains(event.getType())) {
  4790. cellFocusHandler.handleNavigationEvent(event, eventCell);
  4791. }
  4792. return false;
  4793. }
  4794. private boolean handleNavigationEvent(Event event, RowContainer unused) {
  4795. if (!event.getType().equals(BrowserEvents.KEYDOWN)) {
  4796. // Only handle key downs
  4797. return false;
  4798. }
  4799. int newRow = -1;
  4800. RowContainer container = escalator.getBody();
  4801. switch (event.getKeyCode()) {
  4802. case KeyCodes.KEY_HOME:
  4803. if (container.getRowCount() > 0) {
  4804. newRow = 0;
  4805. }
  4806. break;
  4807. case KeyCodes.KEY_END:
  4808. if (container.getRowCount() > 0) {
  4809. newRow = container.getRowCount() - 1;
  4810. }
  4811. break;
  4812. case KeyCodes.KEY_PAGEUP: {
  4813. Range range = escalator.getVisibleRowRange();
  4814. if (!range.isEmpty()) {
  4815. int firstIndex = getFirstVisibleRowIndex();
  4816. newRow = firstIndex - range.length();
  4817. if (newRow < 0) {
  4818. newRow = 0;
  4819. }
  4820. }
  4821. break;
  4822. }
  4823. case KeyCodes.KEY_PAGEDOWN: {
  4824. Range range = escalator.getVisibleRowRange();
  4825. if (!range.isEmpty()) {
  4826. int lastIndex = getLastVisibleRowIndex();
  4827. newRow = lastIndex + range.length();
  4828. if (newRow >= container.getRowCount()) {
  4829. newRow = container.getRowCount() - 1;
  4830. }
  4831. }
  4832. break;
  4833. }
  4834. default:
  4835. return false;
  4836. }
  4837. scrollToRow(newRow);
  4838. return true;
  4839. }
  4840. private boolean handleHeaderCellDragStartEvent(Event event,
  4841. RowContainer container) {
  4842. if (!isColumnReorderingAllowed()) {
  4843. return false;
  4844. }
  4845. if (container != escalator.getHeader()) {
  4846. return false;
  4847. }
  4848. if (eventCell.getColumnIndex() < escalator.getColumnConfiguration()
  4849. .getFrozenColumnCount()) {
  4850. return false;
  4851. }
  4852. // for now prevent dragging of spanned cells
  4853. if (eventCell.getElement().getColSpan() > 1) {
  4854. return false;
  4855. }
  4856. if (event.getTypeInt() == Event.ONMOUSEDOWN
  4857. && event.getButton() == NativeEvent.BUTTON_LEFT
  4858. || event.getTypeInt() == Event.ONTOUCHSTART) {
  4859. dndHandler.onDragStartOnDraggableElement(event,
  4860. headerCellDndCallback);
  4861. event.preventDefault();
  4862. event.stopPropagation();
  4863. return true;
  4864. }
  4865. return false;
  4866. }
  4867. private Point rowEventTouchStartingPoint;
  4868. private CellStyleGenerator<T> cellStyleGenerator;
  4869. private RowStyleGenerator<T> rowStyleGenerator;
  4870. private RowReference<T> rowReference = new RowReference<T>(this);
  4871. private CellReference<T> cellReference = new CellReference<T>(rowReference);
  4872. private RendererCellReference rendererCellReference = new RendererCellReference(
  4873. (RowReference<Object>) rowReference);
  4874. private boolean handleHeaderDefaultRowEvent(Event event,
  4875. RowContainer container) {
  4876. if (container != escalator.getHeader()) {
  4877. return false;
  4878. }
  4879. if (!getHeader().getRow(eventCell.getRowIndex()).isDefault()) {
  4880. return false;
  4881. }
  4882. if (!eventCell.getColumn().isSortable()) {
  4883. // Only handle sorting events if the column is sortable
  4884. return false;
  4885. }
  4886. if (BrowserEvents.MOUSEDOWN.equals(event.getType())
  4887. && event.getShiftKey()) {
  4888. // Don't select text when shift clicking on a header.
  4889. event.preventDefault();
  4890. }
  4891. if (BrowserEvents.TOUCHSTART.equals(event.getType())) {
  4892. if (event.getTouches().length() > 1) {
  4893. return false;
  4894. }
  4895. event.preventDefault();
  4896. Touch touch = event.getChangedTouches().get(0);
  4897. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  4898. touch.getClientY());
  4899. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, true);
  4900. return true;
  4901. } else if (BrowserEvents.TOUCHMOVE.equals(event.getType())) {
  4902. if (event.getTouches().length() > 1) {
  4903. return false;
  4904. }
  4905. event.preventDefault();
  4906. Touch touch = event.getChangedTouches().get(0);
  4907. double diffX = Math.abs(touch.getClientX()
  4908. - rowEventTouchStartingPoint.getX());
  4909. double diffY = Math.abs(touch.getClientY()
  4910. - rowEventTouchStartingPoint.getY());
  4911. // Cancel long tap if finger strays too far from
  4912. // starting point
  4913. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  4914. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  4915. sorter.cancelDelayedSort();
  4916. }
  4917. return true;
  4918. } else if (BrowserEvents.TOUCHEND.equals(event.getType())) {
  4919. if (event.getTouches().length() > 1) {
  4920. return false;
  4921. }
  4922. if (sorter.isDelayedSortScheduled()) {
  4923. // Not a long tap yet, perform single sort
  4924. sorter.cancelDelayedSort();
  4925. sorter.sort(eventCell.getColumn(), false);
  4926. }
  4927. return true;
  4928. } else if (BrowserEvents.TOUCHCANCEL.equals(event.getType())) {
  4929. if (event.getTouches().length() > 1) {
  4930. return false;
  4931. }
  4932. sorter.cancelDelayedSort();
  4933. return true;
  4934. } else if (BrowserEvents.CLICK.equals(event.getType())) {
  4935. sorter.sort(eventCell.getColumn(), event.getShiftKey());
  4936. // Click events should go onward to cell focus logic
  4937. return false;
  4938. } else {
  4939. return false;
  4940. }
  4941. }
  4942. @Override
  4943. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  4944. // Parse SubPart string to type and indices
  4945. String[] splitArgs = subPart.split("\\[");
  4946. String type = splitArgs[0];
  4947. int[] indices = new int[splitArgs.length - 1];
  4948. for (int i = 0; i < indices.length; ++i) {
  4949. String tmp = splitArgs[i + 1];
  4950. indices[i] = Integer.parseInt(tmp.substring(0, tmp.length() - 1));
  4951. }
  4952. // Get correct RowContainer for type from Escalator
  4953. RowContainer container = null;
  4954. if (type.equalsIgnoreCase("header")) {
  4955. container = escalator.getHeader();
  4956. } else if (type.equalsIgnoreCase("cell")) {
  4957. // If wanted row is not visible, we need to scroll there.
  4958. Range visibleRowRange = escalator.getVisibleRowRange();
  4959. if (indices.length > 0 && !visibleRowRange.contains(indices[0])) {
  4960. try {
  4961. scrollToRow(indices[0]);
  4962. } catch (IllegalArgumentException e) {
  4963. getLogger().log(Level.SEVERE, e.getMessage());
  4964. }
  4965. // Scrolling causes a lazy loading event. No element can
  4966. // currently be retrieved.
  4967. return null;
  4968. }
  4969. container = escalator.getBody();
  4970. } else if (type.equalsIgnoreCase("footer")) {
  4971. container = escalator.getFooter();
  4972. } else if (type.equalsIgnoreCase("editor")) {
  4973. if (editor.getState() != State.ACTIVE) {
  4974. // Editor is not there.
  4975. return null;
  4976. }
  4977. if (indices.length == 0) {
  4978. return DOM.asOld(editor.editorOverlay);
  4979. } else if (indices.length == 1 && indices[0] < columns.size()) {
  4980. escalator.scrollToColumn(indices[0], ScrollDestination.ANY, 0);
  4981. return editor.getWidget(columns.get(indices[0])).getElement();
  4982. } else {
  4983. return null;
  4984. }
  4985. }
  4986. if (null != container) {
  4987. if (indices.length == 0) {
  4988. // No indexing. Just return the wanted container element
  4989. return DOM.asOld(container.getElement());
  4990. } else {
  4991. try {
  4992. return DOM.asOld(getSubPart(container, indices));
  4993. } catch (Exception e) {
  4994. getLogger().log(Level.SEVERE, e.getMessage());
  4995. }
  4996. }
  4997. }
  4998. return null;
  4999. }
  5000. private Element getSubPart(RowContainer container, int[] indices) {
  5001. Element targetElement = container.getRowElement(indices[0]);
  5002. // Scroll wanted column to view if able
  5003. if (indices.length > 1 && targetElement != null) {
  5004. if (escalator.getColumnConfiguration().getFrozenColumnCount() <= indices[1]) {
  5005. escalator.scrollToColumn(indices[1], ScrollDestination.ANY, 0);
  5006. }
  5007. targetElement = getCellFromRow(TableRowElement.as(targetElement),
  5008. indices[1]);
  5009. for (int i = 2; i < indices.length && targetElement != null; ++i) {
  5010. targetElement = (Element) targetElement.getChild(indices[i]);
  5011. }
  5012. }
  5013. return targetElement;
  5014. }
  5015. private Element getCellFromRow(TableRowElement rowElement, int index) {
  5016. int childCount = rowElement.getCells().getLength();
  5017. if (index < 0 || index >= childCount) {
  5018. return null;
  5019. }
  5020. TableCellElement currentCell = null;
  5021. boolean indexInColspan = false;
  5022. int i = 0;
  5023. while (!indexInColspan) {
  5024. currentCell = rowElement.getCells().getItem(i);
  5025. // Calculate if this is the cell we are looking for
  5026. int colSpan = currentCell.getColSpan();
  5027. indexInColspan = index < colSpan + i;
  5028. // Increment by colspan to skip over hidden cells
  5029. i += colSpan;
  5030. }
  5031. return currentCell;
  5032. }
  5033. @Override
  5034. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  5035. // Containers and matching SubPart types
  5036. List<RowContainer> containers = Arrays.asList(escalator.getHeader(),
  5037. escalator.getBody(), escalator.getFooter());
  5038. List<String> containerType = Arrays.asList("header", "cell", "footer");
  5039. for (int i = 0; i < containers.size(); ++i) {
  5040. RowContainer container = containers.get(i);
  5041. boolean containerRow = (subElement.getTagName().equalsIgnoreCase(
  5042. "tr") && subElement.getParentElement() == container
  5043. .getElement());
  5044. if (containerRow) {
  5045. // Wanted SubPart is row that is a child of containers root
  5046. // To get indices, we use a cell that is a child of this row
  5047. subElement = DOM.asOld(subElement.getFirstChildElement());
  5048. }
  5049. Cell cell = container.getCell(subElement);
  5050. if (cell != null) {
  5051. // Skip the column index if subElement was a child of root
  5052. return containerType.get(i) + "[" + cell.getRow()
  5053. + (containerRow ? "]" : "][" + cell.getColumn() + "]");
  5054. }
  5055. }
  5056. // Check if subelement is part of editor.
  5057. if (editor.getState() == State.ACTIVE) {
  5058. if (editor.editorOverlay.isOrHasChild(subElement)) {
  5059. int i = 0;
  5060. for (Column<?, T> column : columns) {
  5061. if (editor.getWidget(column).getElement()
  5062. .isOrHasChild(subElement)) {
  5063. return "editor[" + i + "]";
  5064. }
  5065. ++i;
  5066. }
  5067. return "editor";
  5068. }
  5069. }
  5070. return null;
  5071. }
  5072. private void setSelectColumnRenderer(
  5073. final Renderer<Boolean> selectColumnRenderer) {
  5074. if (this.selectColumnRenderer == selectColumnRenderer) {
  5075. return;
  5076. }
  5077. if (this.selectColumnRenderer != null) {
  5078. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  5079. // End of Life for the old selection column renderer.
  5080. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  5081. }
  5082. // Clear field so frozen column logic in the remove method knows
  5083. // what to do
  5084. Column<?, T> colToRemove = selectionColumn;
  5085. selectionColumn = null;
  5086. removeColumnSkipSelectionColumnCheck(colToRemove);
  5087. cellFocusHandler.offsetRangeBy(-1);
  5088. }
  5089. this.selectColumnRenderer = selectColumnRenderer;
  5090. if (selectColumnRenderer != null) {
  5091. cellFocusHandler.offsetRangeBy(1);
  5092. selectionColumn = new SelectionColumn(selectColumnRenderer);
  5093. addColumnSkipSelectionColumnCheck(selectionColumn, 0);
  5094. selectionColumn.initDone();
  5095. } else {
  5096. selectionColumn = null;
  5097. refreshBody();
  5098. }
  5099. updateFrozenColumns();
  5100. }
  5101. /**
  5102. * Sets the current selection model.
  5103. * <p>
  5104. * This function will call {@link SelectionModel#setGrid(Grid)}.
  5105. *
  5106. * @param selectionModel
  5107. * a selection model implementation.
  5108. * @throws IllegalArgumentException
  5109. * if selection model argument is null
  5110. */
  5111. public void setSelectionModel(SelectionModel<T> selectionModel) {
  5112. if (selectionModel == null) {
  5113. throw new IllegalArgumentException("Selection model can't be null");
  5114. }
  5115. if (this.selectionModel != null) {
  5116. // Detach selection model from Grid.
  5117. this.selectionModel.setGrid(null);
  5118. }
  5119. this.selectionModel = selectionModel;
  5120. selectionModel.setGrid(this);
  5121. setSelectColumnRenderer(this.selectionModel
  5122. .getSelectionColumnRenderer());
  5123. }
  5124. /**
  5125. * Gets a reference to the current selection model.
  5126. *
  5127. * @return the currently used SelectionModel instance.
  5128. */
  5129. public SelectionModel<T> getSelectionModel() {
  5130. return selectionModel;
  5131. }
  5132. /**
  5133. * Sets current selection mode.
  5134. * <p>
  5135. * This is a shorthand method for {@link Grid#setSelectionModel}.
  5136. *
  5137. * @param mode
  5138. * a selection mode value
  5139. * @see {@link SelectionMode}.
  5140. */
  5141. public void setSelectionMode(SelectionMode mode) {
  5142. SelectionModel<T> model = mode.createModel();
  5143. setSelectionModel(model);
  5144. }
  5145. /**
  5146. * Test if a row is selected.
  5147. *
  5148. * @param row
  5149. * a row object
  5150. * @return true, if the current selection model considers the provided row
  5151. * object selected.
  5152. */
  5153. public boolean isSelected(T row) {
  5154. return selectionModel.isSelected(row);
  5155. }
  5156. /**
  5157. * Select a row using the current selection model.
  5158. * <p>
  5159. * Only selection models implementing {@link SelectionModel.Single} and
  5160. * {@link SelectionModel.Multi} are supported; for anything else, an
  5161. * exception will be thrown.
  5162. *
  5163. * @param row
  5164. * a row object
  5165. * @return <code>true</code> iff the current selection changed
  5166. * @throws IllegalStateException
  5167. * if the current selection model is not an instance of
  5168. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  5169. */
  5170. @SuppressWarnings("unchecked")
  5171. public boolean select(T row) {
  5172. if (selectionModel instanceof SelectionModel.Single<?>) {
  5173. return ((SelectionModel.Single<T>) selectionModel).select(row);
  5174. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  5175. return ((SelectionModel.Multi<T>) selectionModel).select(row);
  5176. } else {
  5177. throw new IllegalStateException("Unsupported selection model");
  5178. }
  5179. }
  5180. /**
  5181. * Deselect a row using the current selection model.
  5182. * <p>
  5183. * Only selection models implementing {@link SelectionModel.Single} and
  5184. * {@link SelectionModel.Multi} are supported; for anything else, an
  5185. * exception will be thrown.
  5186. *
  5187. * @param row
  5188. * a row object
  5189. * @return <code>true</code> iff the current selection changed
  5190. * @throws IllegalStateException
  5191. * if the current selection model is not an instance of
  5192. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  5193. */
  5194. @SuppressWarnings("unchecked")
  5195. public boolean deselect(T row) {
  5196. if (selectionModel instanceof SelectionModel.Single<?>) {
  5197. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  5198. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  5199. return ((SelectionModel.Multi<T>) selectionModel).deselect(row);
  5200. } else {
  5201. throw new IllegalStateException("Unsupported selection model");
  5202. }
  5203. }
  5204. /**
  5205. * Gets last selected row from the current SelectionModel.
  5206. * <p>
  5207. * Only selection models implementing {@link SelectionModel.Single} are
  5208. * valid for this method; for anything else, use the
  5209. * {@link Grid#getSelectedRows()} method.
  5210. *
  5211. * @return a selected row reference, or null, if no row is selected
  5212. * @throws IllegalStateException
  5213. * if the current selection model is not an instance of
  5214. * {@link SelectionModel.Single}
  5215. */
  5216. public T getSelectedRow() {
  5217. if (selectionModel instanceof SelectionModel.Single<?>) {
  5218. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  5219. } else {
  5220. throw new IllegalStateException(
  5221. "Unsupported selection model; can not get single selected row");
  5222. }
  5223. }
  5224. /**
  5225. * Gets currently selected rows from the current selection model.
  5226. *
  5227. * @return a non-null collection containing all currently selected rows.
  5228. */
  5229. public Collection<T> getSelectedRows() {
  5230. return selectionModel.getSelectedRows();
  5231. }
  5232. @Override
  5233. public HandlerRegistration addSelectionHandler(
  5234. final SelectionHandler<T> handler) {
  5235. return addHandler(handler, SelectionEvent.getType());
  5236. }
  5237. /**
  5238. * Sets the current sort order using the fluid Sort API. Read the
  5239. * documentation for {@link Sort} for more information.
  5240. *
  5241. * @param s
  5242. * a sort instance
  5243. */
  5244. public void sort(Sort s) {
  5245. setSortOrder(s.build());
  5246. }
  5247. /**
  5248. * Sorts the Grid data in ascending order along one column.
  5249. *
  5250. * @param column
  5251. * a grid column reference
  5252. */
  5253. public <C> void sort(Column<C, T> column) {
  5254. sort(column, SortDirection.ASCENDING);
  5255. }
  5256. /**
  5257. * Sorts the Grid data along one column.
  5258. *
  5259. * @param column
  5260. * a grid column reference
  5261. * @param direction
  5262. * a sort direction value
  5263. */
  5264. public <C> void sort(Column<C, T> column, SortDirection direction) {
  5265. sort(Sort.by(column, direction));
  5266. }
  5267. /**
  5268. * Sets the sort order to use. Setting this causes the Grid to re-sort
  5269. * itself.
  5270. *
  5271. * @param order
  5272. * a sort order list. If set to null, the sort order is cleared.
  5273. */
  5274. public void setSortOrder(List<SortOrder> order) {
  5275. setSortOrder(order, false);
  5276. }
  5277. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  5278. if (order != sortOrder) {
  5279. sortOrder.clear();
  5280. if (order != null) {
  5281. sortOrder.addAll(order);
  5282. }
  5283. }
  5284. sort(userOriginated);
  5285. }
  5286. /**
  5287. * Get a copy of the current sort order array.
  5288. *
  5289. * @return a copy of the current sort order array
  5290. */
  5291. public List<SortOrder> getSortOrder() {
  5292. return Collections.unmodifiableList(sortOrder);
  5293. }
  5294. /**
  5295. * Finds the sorting order for this column
  5296. */
  5297. private SortOrder getSortOrder(Column<?, ?> column) {
  5298. for (SortOrder order : getSortOrder()) {
  5299. if (order.getColumn() == column) {
  5300. return order;
  5301. }
  5302. }
  5303. return null;
  5304. }
  5305. /**
  5306. * Register a GWT event handler for a sorting event. This handler gets
  5307. * called whenever this Grid needs its data source to provide data sorted in
  5308. * a specific order.
  5309. *
  5310. * @param handler
  5311. * a sort event handler
  5312. * @return the registration for the event
  5313. */
  5314. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  5315. return addHandler(handler, SortEvent.getType());
  5316. }
  5317. /**
  5318. * Register a GWT event handler for a select all event. This handler gets
  5319. * called whenever Grid needs all rows selected.
  5320. *
  5321. * @param handler
  5322. * a select all event handler
  5323. */
  5324. public HandlerRegistration addSelectAllHandler(SelectAllHandler<T> handler) {
  5325. return addHandler(handler, SelectAllEvent.getType());
  5326. }
  5327. /**
  5328. * Register a GWT event handler for a data available event. This handler
  5329. * gets called whenever the {@link DataSource} for this Grid has new data
  5330. * available.
  5331. * <p>
  5332. * This handle will be fired with the current available data after
  5333. * registration is done.
  5334. *
  5335. * @param handler
  5336. * a data available event handler
  5337. * @return the registartion for the event
  5338. */
  5339. public HandlerRegistration addDataAvailableHandler(
  5340. final DataAvailableHandler handler) {
  5341. // Deferred call to handler with current row range
  5342. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  5343. @Override
  5344. public void execute() {
  5345. if (!dataIsBeingFetched) {
  5346. handler.onDataAvailable(new DataAvailableEvent(
  5347. currentDataAvailable));
  5348. }
  5349. }
  5350. });
  5351. return addHandler(handler, DataAvailableEvent.TYPE);
  5352. }
  5353. /**
  5354. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  5355. * fired when a KeyDown event occurs while cell focus is in the Body of this
  5356. * Grid.
  5357. *
  5358. * @param handler
  5359. * the key handler to register
  5360. * @return the registration for the event
  5361. */
  5362. public HandlerRegistration addBodyKeyDownHandler(BodyKeyDownHandler handler) {
  5363. return addHandler(handler, keyDown.getAssociatedType());
  5364. }
  5365. /**
  5366. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  5367. * fired when a KeyUp event occurs while cell focus is in the Body of this
  5368. * Grid.
  5369. *
  5370. * @param handler
  5371. * the key handler to register
  5372. * @return the registration for the event
  5373. */
  5374. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  5375. return addHandler(handler, keyUp.getAssociatedType());
  5376. }
  5377. /**
  5378. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  5379. * is fired when a KeyPress event occurs while cell focus is in the Body of
  5380. * this Grid.
  5381. *
  5382. * @param handler
  5383. * the key handler to register
  5384. * @return the registration for the event
  5385. */
  5386. public HandlerRegistration addBodyKeyPressHandler(
  5387. BodyKeyPressHandler handler) {
  5388. return addHandler(handler, keyPress.getAssociatedType());
  5389. }
  5390. /**
  5391. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  5392. * is fired when a KeyDown event occurs while cell focus is in the Header of
  5393. * this Grid.
  5394. *
  5395. * @param handler
  5396. * the key handler to register
  5397. * @return the registration for the event
  5398. */
  5399. public HandlerRegistration addHeaderKeyDownHandler(
  5400. HeaderKeyDownHandler handler) {
  5401. return addHandler(handler, keyDown.getAssociatedType());
  5402. }
  5403. /**
  5404. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  5405. * fired when a KeyUp event occurs while cell focus is in the Header of this
  5406. * Grid.
  5407. *
  5408. * @param handler
  5409. * the key handler to register
  5410. * @return the registration for the event
  5411. */
  5412. public HandlerRegistration addHeaderKeyUpHandler(HeaderKeyUpHandler handler) {
  5413. return addHandler(handler, keyUp.getAssociatedType());
  5414. }
  5415. /**
  5416. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  5417. * is fired when a KeyPress event occurs while cell focus is in the Header
  5418. * of this Grid.
  5419. *
  5420. * @param handler
  5421. * the key handler to register
  5422. * @return the registration for the event
  5423. */
  5424. public HandlerRegistration addHeaderKeyPressHandler(
  5425. HeaderKeyPressHandler handler) {
  5426. return addHandler(handler, keyPress.getAssociatedType());
  5427. }
  5428. /**
  5429. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  5430. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  5431. * this Grid.
  5432. *
  5433. * @param handler
  5434. * the key handler to register
  5435. * @return the registration for the event
  5436. */
  5437. public HandlerRegistration addFooterKeyDownHandler(
  5438. FooterKeyDownHandler handler) {
  5439. return addHandler(handler, keyDown.getAssociatedType());
  5440. }
  5441. /**
  5442. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  5443. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  5444. * Grid.
  5445. *
  5446. * @param handler
  5447. * the key handler to register
  5448. * @return the registration for the event
  5449. */
  5450. public HandlerRegistration addFooterKeyUpHandler(FooterKeyUpHandler handler) {
  5451. return addHandler(handler, keyUp.getAssociatedType());
  5452. }
  5453. /**
  5454. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  5455. * is fired when a KeyPress event occurs while cell focus is in the Footer
  5456. * of this Grid.
  5457. *
  5458. * @param handler
  5459. * the key handler to register
  5460. * @return the registration for the event
  5461. */
  5462. public HandlerRegistration addFooterKeyPressHandler(
  5463. FooterKeyPressHandler handler) {
  5464. return addHandler(handler, keyPress.getAssociatedType());
  5465. }
  5466. /**
  5467. * Register a BodyClickHandler to this Grid. The event for this handler is
  5468. * fired when a Click event occurs in the Body of this Grid.
  5469. *
  5470. * @param handler
  5471. * the click handler to register
  5472. * @return the registration for the event
  5473. */
  5474. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  5475. return addHandler(handler, clickEvent.getAssociatedType());
  5476. }
  5477. /**
  5478. * Register a HeaderClickHandler to this Grid. The event for this handler is
  5479. * fired when a Click event occurs in the Header of this Grid.
  5480. *
  5481. * @param handler
  5482. * the click handler to register
  5483. * @return the registration for the event
  5484. */
  5485. public HandlerRegistration addHeaderClickHandler(HeaderClickHandler handler) {
  5486. return addHandler(handler, clickEvent.getAssociatedType());
  5487. }
  5488. /**
  5489. * Register a FooterClickHandler to this Grid. The event for this handler is
  5490. * fired when a Click event occurs in the Footer of this Grid.
  5491. *
  5492. * @param handler
  5493. * the click handler to register
  5494. * @return the registration for the event
  5495. */
  5496. public HandlerRegistration addFooterClickHandler(FooterClickHandler handler) {
  5497. return addHandler(handler, clickEvent.getAssociatedType());
  5498. }
  5499. /**
  5500. * Register a BodyDoubleClickHandler to this Grid. The event for this
  5501. * handler is fired when a double click event occurs in the Body of this
  5502. * Grid.
  5503. *
  5504. * @param handler
  5505. * the double click handler to register
  5506. * @return the registration for the event
  5507. */
  5508. public HandlerRegistration addBodyDoubleClickHandler(
  5509. BodyDoubleClickHandler handler) {
  5510. return addHandler(handler, doubleClickEvent.getAssociatedType());
  5511. }
  5512. /**
  5513. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  5514. * handler is fired when a double click event occurs in the Header of this
  5515. * Grid.
  5516. *
  5517. * @param handler
  5518. * the double click handler to register
  5519. * @return the registration for the event
  5520. */
  5521. public HandlerRegistration addHeaderDoubleClickHandler(
  5522. HeaderDoubleClickHandler handler) {
  5523. return addHandler(handler, doubleClickEvent.getAssociatedType());
  5524. }
  5525. /**
  5526. * Register a FooterDoubleClickHandler to this Grid. The event for this
  5527. * handler is fired when a double click event occurs in the Footer of this
  5528. * Grid.
  5529. *
  5530. * @param handler
  5531. * the double click handler to register
  5532. * @return the registration for the event
  5533. */
  5534. public HandlerRegistration addFooterDoubleClickHandler(
  5535. FooterDoubleClickHandler handler) {
  5536. return addHandler(handler, doubleClickEvent.getAssociatedType());
  5537. }
  5538. /**
  5539. * Register a column reorder handler to this Grid. The event for this
  5540. * handler is fired when the Grid's columns are reordered.
  5541. *
  5542. * @since
  5543. * @param handler
  5544. * the handler for the event
  5545. * @return the registration for the event
  5546. */
  5547. public HandlerRegistration addColumnReorderHandler(
  5548. ColumnReorderHandler<T> handler) {
  5549. return addHandler(handler, ColumnReorderEvent.getType());
  5550. }
  5551. /**
  5552. * Apply sorting to data source.
  5553. */
  5554. private void sort(boolean userOriginated) {
  5555. refreshHeader();
  5556. fireEvent(new SortEvent<T>(this,
  5557. Collections.unmodifiableList(sortOrder), userOriginated));
  5558. }
  5559. private int getLastVisibleRowIndex() {
  5560. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  5561. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  5562. Element lastRow;
  5563. do {
  5564. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  5565. } while (lastRow.getAbsoluteTop() > footerTop);
  5566. return lastRowIndex;
  5567. }
  5568. private int getFirstVisibleRowIndex() {
  5569. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  5570. int headerBottom = escalator.getHeader().getElement()
  5571. .getAbsoluteBottom();
  5572. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  5573. while (firstRow.getAbsoluteBottom() < headerBottom) {
  5574. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  5575. }
  5576. return firstRowIndex;
  5577. }
  5578. /**
  5579. * Adds a scroll handler to this grid
  5580. *
  5581. * @param handler
  5582. * the scroll handler to add
  5583. * @return a handler registration for the registered scroll handler
  5584. */
  5585. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  5586. return addHandler(handler, ScrollEvent.TYPE);
  5587. }
  5588. @Override
  5589. public boolean isWorkPending() {
  5590. return escalator.isWorkPending() || dataIsBeingFetched
  5591. || autoColumnWidthsRecalculator.isScheduled();
  5592. }
  5593. /**
  5594. * Returns whether columns can be reordered with drag and drop.
  5595. *
  5596. * @since
  5597. * @return <code>true</code> if columns can be reordered, false otherwise
  5598. */
  5599. public boolean isColumnReorderingAllowed() {
  5600. return columnReorderingAllowed;
  5601. }
  5602. /**
  5603. * Sets whether column reordering with drag and drop is allowed or not.
  5604. *
  5605. * @since
  5606. * @param columnReorderingAllowed
  5607. * specifies whether column reordering is allowed
  5608. */
  5609. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  5610. this.columnReorderingAllowed = columnReorderingAllowed;
  5611. }
  5612. /**
  5613. * Sets a new column order for the grid. All columns which are not ordered
  5614. * here will remain in the order they were before as the last columns of
  5615. * grid.
  5616. *
  5617. * @param orderedColumns
  5618. * array of columns in wanted order
  5619. */
  5620. public void setColumnOrder(Column<?, T>... orderedColumns) {
  5621. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  5622. // Trigger ComplexRenderer.destroy for old content
  5623. conf.removeColumns(0, conf.getColumnCount());
  5624. List<Column<?, T>> newOrder = new ArrayList<Column<?, T>>();
  5625. if (selectionColumn != null) {
  5626. newOrder.add(selectionColumn);
  5627. }
  5628. int i = 0;
  5629. for (Column<?, T> column : orderedColumns) {
  5630. if (columns.contains(column)) {
  5631. newOrder.add(column);
  5632. ++i;
  5633. } else {
  5634. throw new IllegalArgumentException("Given column at index " + i
  5635. + " does not exist in Grid");
  5636. }
  5637. }
  5638. if (columns.size() != newOrder.size()) {
  5639. columns.removeAll(newOrder);
  5640. newOrder.addAll(columns);
  5641. }
  5642. columns = newOrder;
  5643. // Do ComplexRenderer.init and render new content
  5644. conf.insertColumns(0, columns.size());
  5645. // Update column widths.
  5646. for (Column<?, T> column : columns) {
  5647. column.reapplyWidth();
  5648. }
  5649. // Recalculate all the colspans
  5650. for (HeaderRow row : header.getRows()) {
  5651. row.calculateColspans();
  5652. }
  5653. for (FooterRow row : footer.getRows()) {
  5654. row.calculateColspans();
  5655. }
  5656. fireEvent(new ColumnReorderEvent<T>());
  5657. }
  5658. /**
  5659. * Sets the style generator that is used for generating styles for cells
  5660. *
  5661. * @param cellStyleGenerator
  5662. * the cell style generator to set, or <code>null</code> to
  5663. * remove a previously set generator
  5664. */
  5665. public void setCellStyleGenerator(CellStyleGenerator<T> cellStyleGenerator) {
  5666. this.cellStyleGenerator = cellStyleGenerator;
  5667. refreshBody();
  5668. }
  5669. /**
  5670. * Gets the style generator that is used for generating styles for cells
  5671. *
  5672. * @return the cell style generator, or <code>null</code> if no generator is
  5673. * set
  5674. */
  5675. public CellStyleGenerator<T> getCellStyleGenerator() {
  5676. return cellStyleGenerator;
  5677. }
  5678. /**
  5679. * Sets the style generator that is used for generating styles for rows
  5680. *
  5681. * @param rowStyleGenerator
  5682. * the row style generator to set, or <code>null</code> to remove
  5683. * a previously set generator
  5684. */
  5685. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  5686. this.rowStyleGenerator = rowStyleGenerator;
  5687. refreshBody();
  5688. }
  5689. /**
  5690. * Gets the style generator that is used for generating styles for rows
  5691. *
  5692. * @return the row style generator, or <code>null</code> if no generator is
  5693. * set
  5694. */
  5695. public RowStyleGenerator<T> getRowStyleGenerator() {
  5696. return rowStyleGenerator;
  5697. }
  5698. private static void setCustomStyleName(Element element, String styleName) {
  5699. assert element != null;
  5700. String oldStyleName = element
  5701. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  5702. if (!SharedUtil.equals(oldStyleName, styleName)) {
  5703. if (oldStyleName != null) {
  5704. element.removeClassName(oldStyleName);
  5705. }
  5706. if (styleName != null) {
  5707. element.addClassName(styleName);
  5708. }
  5709. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  5710. }
  5711. }
  5712. /**
  5713. * Opens the editor over the row with the given index.
  5714. *
  5715. * @param rowIndex
  5716. * the index of the row to be edited
  5717. *
  5718. * @throws IllegalStateException
  5719. * if the editor is not enabled
  5720. * @throws IllegalStateException
  5721. * if the editor is already in edit mode
  5722. */
  5723. public void editRow(int rowIndex) {
  5724. editor.editRow(rowIndex);
  5725. }
  5726. /**
  5727. * Returns whether the editor is currently open on some row.
  5728. *
  5729. * @return {@code true} if the editor is active, {@code false} otherwise.
  5730. */
  5731. public boolean isEditorActive() {
  5732. return editor.getState() != State.INACTIVE;
  5733. }
  5734. /**
  5735. * Saves any unsaved changes in the editor to the data source.
  5736. *
  5737. * @throws IllegalStateException
  5738. * if the editor is not enabled
  5739. * @throws IllegalStateException
  5740. * if the editor is not in edit mode
  5741. */
  5742. public void saveEditor() {
  5743. editor.save();
  5744. }
  5745. /**
  5746. * Cancels the currently active edit and hides the editor. Any changes that
  5747. * are not {@link #saveEditor() saved} are lost.
  5748. *
  5749. * @throws IllegalStateException
  5750. * if the editor is not enabled
  5751. * @throws IllegalStateException
  5752. * if the editor is not in edit mode
  5753. */
  5754. public void cancelEditor() {
  5755. editor.cancel();
  5756. }
  5757. /**
  5758. * Returns the handler responsible for binding data and editor widgets to
  5759. * the editor.
  5760. *
  5761. * @return the editor handler or null if not set
  5762. */
  5763. public EditorHandler<T> getEditorHandler() {
  5764. return editor.getHandler();
  5765. }
  5766. /**
  5767. * Sets the handler responsible for binding data and editor widgets to the
  5768. * editor.
  5769. *
  5770. * @param rowHandler
  5771. * the new editor handler
  5772. *
  5773. * @throws IllegalStateException
  5774. * if the editor is currently in edit mode
  5775. */
  5776. public void setEditorHandler(EditorHandler<T> handler) {
  5777. editor.setHandler(handler);
  5778. }
  5779. /**
  5780. * Returns the enabled state of the editor.
  5781. *
  5782. * @return true if editing is enabled, false otherwise
  5783. */
  5784. public boolean isEditorEnabled() {
  5785. return editor.isEnabled();
  5786. }
  5787. /**
  5788. * Sets the enabled state of the editor.
  5789. *
  5790. * @param enabled
  5791. * true to enable editing, false to disable
  5792. *
  5793. * @throws IllegalStateException
  5794. * if in edit mode and trying to disable
  5795. * @throws IllegalStateException
  5796. * if the editor handler is not set
  5797. */
  5798. public void setEditorEnabled(boolean enabled) {
  5799. editor.setEnabled(enabled);
  5800. }
  5801. /**
  5802. * Returns the editor widget associated with the given column. If the editor
  5803. * is not active, returns null.
  5804. *
  5805. * @param column
  5806. * the column
  5807. * @return the widget if the editor is open, null otherwise
  5808. */
  5809. public Widget getEditorWidget(Column<?, T> column) {
  5810. return editor.getWidget(column);
  5811. }
  5812. /**
  5813. * Sets the caption on the save button in the Grid editor.
  5814. *
  5815. * @param saveCaption
  5816. * the caption to set
  5817. * @throws IllegalArgumentException
  5818. * if {@code saveCaption} is {@code null}
  5819. */
  5820. public void setEditorSaveCaption(String saveCaption)
  5821. throws IllegalArgumentException {
  5822. editor.setSaveCaption(saveCaption);
  5823. }
  5824. /**
  5825. * Gets the current caption on the save button in the Grid editor.
  5826. *
  5827. * @return the current caption on the save button
  5828. */
  5829. public String getEditorSaveCaption() {
  5830. return editor.getSaveCaption();
  5831. }
  5832. /**
  5833. * Sets the caption on the cancel button in the Grid editor.
  5834. *
  5835. * @param cancelCaption
  5836. * the caption to set
  5837. * @throws IllegalArgumentException
  5838. * if {@code cancelCaption} is {@code null}
  5839. */
  5840. public void setEditorCancelCaption(String cancelCaption)
  5841. throws IllegalArgumentException {
  5842. editor.setCancelCaption(cancelCaption);
  5843. }
  5844. /**
  5845. * Gets the caption on the cancel button in the Grid editor.
  5846. *
  5847. * @return the current caption on the cancel button
  5848. */
  5849. public String getEditorCancelCaption() {
  5850. return editor.getCancelCaption();
  5851. }
  5852. @Override
  5853. protected void onAttach() {
  5854. super.onAttach();
  5855. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  5856. setEscalatorSizeFromDataSource();
  5857. }
  5858. }
  5859. /**
  5860. * Grid does not support adding Widgets this way.
  5861. * <p>
  5862. * This method is implemented only because removing widgets from Grid (added
  5863. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  5864. *
  5865. * @param w
  5866. * irrelevant
  5867. * @throws UnsupportedOperationException
  5868. * always
  5869. */
  5870. @Override
  5871. @Deprecated
  5872. public void add(Widget w) {
  5873. throw new UnsupportedOperationException(
  5874. "Cannot add widgets to Grid with this method");
  5875. }
  5876. /**
  5877. * Grid does not support clearing Widgets this way.
  5878. * <p>
  5879. * This method is implemented only because removing widgets from Grid (added
  5880. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  5881. *
  5882. * @throws UnsupportedOperationException
  5883. * always
  5884. */
  5885. @Override
  5886. @Deprecated
  5887. public void clear() {
  5888. throw new UnsupportedOperationException(
  5889. "Cannot clear widgets from Grid this way");
  5890. }
  5891. /**
  5892. * Grid does not support iterating through Widgets this way.
  5893. * <p>
  5894. * This method is implemented only because removing widgets from Grid (added
  5895. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  5896. *
  5897. * @return never
  5898. * @throws UnsupportedOperationException
  5899. * always
  5900. */
  5901. @Override
  5902. @Deprecated
  5903. public Iterator<Widget> iterator() {
  5904. throw new UnsupportedOperationException(
  5905. "Cannot iterate through widgets in Grid this way");
  5906. }
  5907. /**
  5908. * Grid does not support removing Widgets this way.
  5909. * <p>
  5910. * This method is implemented only because removing widgets from Grid (added
  5911. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  5912. *
  5913. * @return always <code>false</code>
  5914. */
  5915. @Override
  5916. @Deprecated
  5917. public boolean remove(Widget w) {
  5918. /*
  5919. * This is the method that is the sole reason to have Grid implement
  5920. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  5921. * corresponding Widget will call removeFromParent() on itself. GWT will
  5922. * check there that its parent (i.e. Grid) implements HasWidgets, and
  5923. * will call this remove(Widget) method.
  5924. *
  5925. * tl;dr: all this song and dance to make sure GWT's sanity checks
  5926. * aren't triggered, even though they effectively do nothing interesting
  5927. * from Grid's perspective.
  5928. */
  5929. return false;
  5930. }
  5931. /**
  5932. * Accesses the package private method Widget#setParent()
  5933. *
  5934. * @param widget
  5935. * The widget to access
  5936. * @param parent
  5937. * The parent to set
  5938. */
  5939. private static native final void setParent(Widget widget, Grid<?> parent)
  5940. /*-{
  5941. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  5942. }-*/;
  5943. /**
  5944. * Resets all cached pixel sizes and reads new values from the DOM. This
  5945. * methods should be used e.g. when styles affecting the dimensions of
  5946. * elements in this grid have been changed.
  5947. */
  5948. public void resetSizesFromDom() {
  5949. getEscalator().resetSizesFromDom();
  5950. }
  5951. }