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

Grid.java 331KB

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