Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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 HashMap<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. /**
  3646. * Currently available row range in DataSource.
  3647. */
  3648. private Range currentDataAvailable = Range.withLength(0, 0);
  3649. /**
  3650. * The number of frozen columns, 0 freezes the selection column if
  3651. * displayed, -1 also prevents selection col from freezing.
  3652. */
  3653. private int frozenColumnCount = 0;
  3654. /**
  3655. * Current sort order. The (private) sort() method reads this list to
  3656. * determine the order in which to present rows.
  3657. */
  3658. private List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  3659. private Renderer<Boolean> selectColumnRenderer = null;
  3660. private SelectionColumn selectionColumn;
  3661. private String rowStripeStyleName;
  3662. private String rowHasDataStyleName;
  3663. private String rowSelectedStyleName;
  3664. private String cellFocusStyleName;
  3665. private String rowFocusStyleName;
  3666. /**
  3667. * Current selection model.
  3668. */
  3669. private SelectionModel<T> selectionModel;
  3670. protected final CellFocusHandler cellFocusHandler;
  3671. private final UserSorter sorter = new UserSorter();
  3672. private final Editor<T> editor = GWT.create(Editor.class);
  3673. /**
  3674. * The cell a click event originated from
  3675. * <p>
  3676. * This is a workaround to make Chrome work like Firefox. In Chrome,
  3677. * normally if you start a drag on one cell and release on:
  3678. * <ul>
  3679. * <li>that same cell, the click event is that <code>&lt;td></code>.
  3680. * <li>a cell on that same row, the click event is the parent
  3681. * <code>&lt;tr></code>.
  3682. * <li>a cell on another row, the click event is the table section ancestor
  3683. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  3684. * </ul>
  3685. *
  3686. * @see #onBrowserEvent(Event)
  3687. */
  3688. private Cell cellOnPrevMouseDown;
  3689. /**
  3690. * A scheduled command to re-evaluate the widths of <em>all columns</em>
  3691. * that have calculated widths. Most probably called because
  3692. * minwidth/maxwidth/expandratio has changed.
  3693. */
  3694. private final AutoColumnWidthsRecalculator autoColumnWidthsRecalculator = new AutoColumnWidthsRecalculator();
  3695. private boolean enabled = true;
  3696. private DetailsGenerator detailsGenerator = DetailsGenerator.NULL;
  3697. private GridSpacerUpdater gridSpacerUpdater = new GridSpacerUpdater();
  3698. /** A set keeping track of the indices of all currently open details */
  3699. private Set<Integer> visibleDetails = new HashSet<Integer>();
  3700. /** A set of indices of details to reopen after detach and on attach */
  3701. private final Set<Integer> reattachVisibleDetails = new HashSet<Integer>();
  3702. private boolean columnReorderingAllowed;
  3703. private ColumnHider columnHider = new ColumnHider();
  3704. private DragAndDropHandler dndHandler = new DragAndDropHandler();
  3705. private AutoScroller autoScroller = new AutoScroller(this);
  3706. private ColumnResizeMode columnResizeMode = ColumnResizeMode.ANIMATED;
  3707. private DragAndDropHandler.DragAndDropCallback headerCellDndCallback = new DragAndDropCallback() {
  3708. private final AutoScrollerCallback autoScrollerCallback = new AutoScrollerCallback() {
  3709. @Override
  3710. public void onAutoScroll(int scrollDiff) {
  3711. autoScrollX = scrollDiff;
  3712. onDragUpdate(null);
  3713. }
  3714. @Override
  3715. public void onAutoScrollReachedMin() {
  3716. // make sure the drop marker is visible on the left
  3717. autoScrollX = 0;
  3718. updateDragDropMarker(clientX);
  3719. }
  3720. @Override
  3721. public void onAutoScrollReachedMax() {
  3722. // make sure the drop marker is visible on the right
  3723. autoScrollX = 0;
  3724. updateDragDropMarker(clientX);
  3725. }
  3726. };
  3727. /**
  3728. * Elements for displaying the dragged column(s) and drop marker
  3729. * properly
  3730. */
  3731. private Element table;
  3732. private Element tableHeader;
  3733. /** Marks the column drop location */
  3734. private Element dropMarker;
  3735. /** A copy of the dragged column(s), moves with cursor. */
  3736. private Element dragElement;
  3737. /** Tracks index of the column whose left side the drop would occur */
  3738. private int latestColumnDropIndex;
  3739. /**
  3740. * Map of possible drop positions for the column and the corresponding
  3741. * column index.
  3742. */
  3743. private final TreeMap<Double, Integer> possibleDropPositions = new TreeMap<Double, Integer>();
  3744. /**
  3745. * Makes sure that drag cancel doesn't cause anything unwanted like sort
  3746. */
  3747. private HandlerRegistration columnSortPreventRegistration;
  3748. private int clientX;
  3749. /** How much the grid is being auto scrolled while dragging. */
  3750. private int autoScrollX;
  3751. /** Captures the value of the focused column before reordering */
  3752. private int focusedColumnIndex;
  3753. /** Offset caused by the drag and drop marker width */
  3754. private double dropMarkerWidthOffset;
  3755. private void initHeaderDragElementDOM() {
  3756. if (table == null) {
  3757. tableHeader = DOM.createTHead();
  3758. dropMarker = DOM.createDiv();
  3759. tableHeader.appendChild(dropMarker);
  3760. table = DOM.createTable();
  3761. table.appendChild(tableHeader);
  3762. table.setClassName("header-drag-table");
  3763. }
  3764. // update the style names on each run in case primary name has been
  3765. // modified
  3766. tableHeader.setClassName(
  3767. escalator.getHeader().getElement().getClassName());
  3768. dropMarker.setClassName(getStylePrimaryName() + "-drop-marker");
  3769. int topOffset = 0;
  3770. for (int i = 0; i < eventCell.getRowIndex(); i++) {
  3771. topOffset += escalator.getHeader().getRowElement(i)
  3772. .getFirstChildElement().getOffsetHeight();
  3773. }
  3774. tableHeader.getStyle().setTop(topOffset, Unit.PX);
  3775. getElement().appendChild(table);
  3776. dropMarkerWidthOffset = WidgetUtil
  3777. .getRequiredWidthBoundingClientRectDouble(dropMarker) / 2;
  3778. }
  3779. @Override
  3780. public void onDragUpdate(Event e) {
  3781. if (e != null) {
  3782. clientX = WidgetUtil.getTouchOrMouseClientX(e);
  3783. autoScrollX = 0;
  3784. }
  3785. resolveDragElementHorizontalPosition(clientX);
  3786. updateDragDropMarker(clientX);
  3787. }
  3788. private void updateDragDropMarker(final int clientX) {
  3789. final double scrollLeft = getScrollLeft();
  3790. final double cursorXCoordinate = clientX
  3791. - escalator.getHeader().getElement().getAbsoluteLeft();
  3792. final Entry<Double, Integer> cellEdgeOnRight = possibleDropPositions
  3793. .ceilingEntry(cursorXCoordinate);
  3794. final Entry<Double, Integer> cellEdgeOnLeft = possibleDropPositions
  3795. .floorEntry(cursorXCoordinate);
  3796. final double diffToRightEdge = cellEdgeOnRight == null
  3797. ? Double.MAX_VALUE
  3798. : cellEdgeOnRight.getKey() - cursorXCoordinate;
  3799. final double diffToLeftEdge = cellEdgeOnLeft == null
  3800. ? Double.MAX_VALUE
  3801. : cursorXCoordinate - cellEdgeOnLeft.getKey();
  3802. double dropMarkerLeft = 0 - scrollLeft;
  3803. if (diffToRightEdge > diffToLeftEdge) {
  3804. latestColumnDropIndex = cellEdgeOnLeft.getValue();
  3805. dropMarkerLeft += cellEdgeOnLeft.getKey();
  3806. } else {
  3807. latestColumnDropIndex = cellEdgeOnRight.getValue();
  3808. dropMarkerLeft += cellEdgeOnRight.getKey();
  3809. }
  3810. dropMarkerLeft += autoScrollX;
  3811. final double frozenColumnsWidth = autoScroller
  3812. .getFrozenColumnsWidth();
  3813. final double rightBoundaryForDrag = getSidebarBoundaryComparedTo(
  3814. dropMarkerLeft);
  3815. final int visibleColumns = getVisibleColumns().size();
  3816. // First check if the drop marker should move left because of the
  3817. // sidebar opening button. this only the case if the grid is
  3818. // scrolled to the right
  3819. if (latestColumnDropIndex == visibleColumns
  3820. && rightBoundaryForDrag < dropMarkerLeft
  3821. && dropMarkerLeft <= escalator.getInnerWidth()) {
  3822. dropMarkerLeft = rightBoundaryForDrag - dropMarkerWidthOffset;
  3823. }
  3824. // Check if the drop marker shouldn't be shown at all
  3825. else if (dropMarkerLeft < frozenColumnsWidth
  3826. || dropMarkerLeft > Math.min(rightBoundaryForDrag,
  3827. escalator.getInnerWidth())
  3828. || dropMarkerLeft < 0) {
  3829. dropMarkerLeft = -10000000;
  3830. }
  3831. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  3832. }
  3833. private void resolveDragElementHorizontalPosition(final int clientX) {
  3834. double left = clientX - table.getAbsoluteLeft();
  3835. // Do not show the drag element beyond a spanned header cell
  3836. // limitation
  3837. final Double leftBound = possibleDropPositions.firstKey();
  3838. final Double rightBound = possibleDropPositions.lastKey();
  3839. final double scrollLeft = getScrollLeft();
  3840. if (left + scrollLeft < leftBound) {
  3841. left = leftBound - scrollLeft + autoScrollX;
  3842. } else if (left + scrollLeft > rightBound) {
  3843. left = rightBound - scrollLeft + autoScrollX;
  3844. }
  3845. // Do not show the drag element beyond the grid
  3846. final double sidebarBoundary = getSidebarBoundaryComparedTo(left);
  3847. final double gridBoundary = escalator.getInnerWidth();
  3848. final double rightBoundary = Math.min(sidebarBoundary,
  3849. gridBoundary);
  3850. // Do not show on left of the frozen columns (even if scrolled)
  3851. final int frozenColumnsWidth = (int) autoScroller
  3852. .getFrozenColumnsWidth();
  3853. left = Math.max(frozenColumnsWidth, Math.min(left, rightBoundary));
  3854. left -= dragElement.getClientWidth() / 2;
  3855. dragElement.getStyle().setLeft(left, Unit.PX);
  3856. }
  3857. private boolean isSidebarOnDraggedRow() {
  3858. return eventCell.getRowIndex() == 0 && sidebar.isInDOM()
  3859. && !sidebar.isOpen();
  3860. }
  3861. /**
  3862. * Returns the sidebar left coordinate, in relation to the grid. Or
  3863. * Double.MAX_VALUE if it doesn't cause a boundary.
  3864. */
  3865. private double getSidebarBoundaryComparedTo(double left) {
  3866. if (isSidebarOnDraggedRow()) {
  3867. double absoluteLeft = left + getElement().getAbsoluteLeft();
  3868. double sidebarLeft = sidebar.getElement().getAbsoluteLeft();
  3869. double diff = absoluteLeft - sidebarLeft;
  3870. if (diff > 0) {
  3871. return left - diff;
  3872. }
  3873. }
  3874. return Double.MAX_VALUE;
  3875. }
  3876. @Override
  3877. public boolean onDragStart(Event e) {
  3878. calculatePossibleDropPositions();
  3879. if (possibleDropPositions.isEmpty()) {
  3880. return false;
  3881. }
  3882. initHeaderDragElementDOM();
  3883. // needs to clone focus and sorting indicators too (UX)
  3884. dragElement = DOM.clone(eventCell.getElement(), true);
  3885. dragElement.getStyle().clearWidth();
  3886. dropMarker.getStyle().setProperty("height",
  3887. dragElement.getStyle().getHeight());
  3888. tableHeader.appendChild(dragElement);
  3889. // mark the column being dragged for styling
  3890. eventCell.getElement().addClassName("dragged");
  3891. // mark the floating cell, for styling & testing
  3892. dragElement.addClassName("dragged-column-header");
  3893. // start the auto scroll handler
  3894. autoScroller.setScrollArea(60);
  3895. autoScroller.start(e, ScrollAxis.HORIZONTAL, autoScrollerCallback);
  3896. return true;
  3897. }
  3898. @Override
  3899. public void onDragEnd() {
  3900. table.removeFromParent();
  3901. dragElement.removeFromParent();
  3902. eventCell.getElement().removeClassName("dragged");
  3903. }
  3904. @Override
  3905. public void onDrop() {
  3906. final int draggedColumnIndex = eventCell.getColumnIndex();
  3907. final int colspan = header.getRow(eventCell.getRowIndex())
  3908. .getCell(eventCell.getColumn()).getColspan();
  3909. if (latestColumnDropIndex != draggedColumnIndex
  3910. && latestColumnDropIndex != draggedColumnIndex + colspan) {
  3911. List<Column<?, T>> columns = getColumns();
  3912. List<Column<?, T>> reordered = new ArrayList<Column<?, T>>();
  3913. if (draggedColumnIndex < latestColumnDropIndex) {
  3914. reordered.addAll(columns.subList(0, draggedColumnIndex));
  3915. reordered.addAll(
  3916. columns.subList(draggedColumnIndex + colspan,
  3917. latestColumnDropIndex));
  3918. reordered.addAll(columns.subList(draggedColumnIndex,
  3919. draggedColumnIndex + colspan));
  3920. reordered.addAll(columns.subList(latestColumnDropIndex,
  3921. columns.size()));
  3922. } else {
  3923. reordered.addAll(columns.subList(0, latestColumnDropIndex));
  3924. reordered.addAll(columns.subList(draggedColumnIndex,
  3925. draggedColumnIndex + colspan));
  3926. reordered.addAll(columns.subList(latestColumnDropIndex,
  3927. draggedColumnIndex));
  3928. reordered.addAll(columns.subList(
  3929. draggedColumnIndex + colspan, columns.size()));
  3930. }
  3931. // since setColumnOrder will // add it anyway!
  3932. reordered.remove(selectionColumn);
  3933. // capture focused cell column before reorder
  3934. Cell focusedCell = cellFocusHandler.getFocusedCell();
  3935. if (focusedCell != null) {
  3936. // take hidden columns into account
  3937. focusedColumnIndex = getColumns()
  3938. .indexOf(getVisibleColumn(focusedCell.getColumn()));
  3939. }
  3940. Column<?, T>[] array = reordered
  3941. .toArray(new Column[reordered.size()]);
  3942. setColumnOrder(array);
  3943. transferCellFocusOnDrop();
  3944. } // else no reordering
  3945. }
  3946. private void transferCellFocusOnDrop() {
  3947. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  3948. if (focusedCell != null) {
  3949. final int focusedColumnIndexDOM = focusedCell.getColumn();
  3950. final int focusedRowIndex = focusedCell.getRow();
  3951. final int draggedColumnIndex = eventCell.getColumnIndex();
  3952. // transfer focus if it was effected by the new column order
  3953. final RowContainer rowContainer = escalator
  3954. .findRowContainer(focusedCell.getElement());
  3955. if (focusedColumnIndex == draggedColumnIndex) {
  3956. // move with the dragged column
  3957. int adjustedDropIndex = latestColumnDropIndex > draggedColumnIndex
  3958. ? latestColumnDropIndex - 1 : latestColumnDropIndex;
  3959. // remove hidden columns from indexing
  3960. adjustedDropIndex = getVisibleColumns()
  3961. .indexOf(getColumn(adjustedDropIndex));
  3962. cellFocusHandler.setCellFocus(focusedRowIndex,
  3963. adjustedDropIndex, rowContainer);
  3964. } else if (latestColumnDropIndex <= focusedColumnIndex
  3965. && draggedColumnIndex > focusedColumnIndex) {
  3966. cellFocusHandler.setCellFocus(focusedRowIndex,
  3967. focusedColumnIndexDOM + 1, rowContainer);
  3968. } else if (latestColumnDropIndex > focusedColumnIndex
  3969. && draggedColumnIndex < focusedColumnIndex) {
  3970. cellFocusHandler.setCellFocus(focusedRowIndex,
  3971. focusedColumnIndexDOM - 1, rowContainer);
  3972. }
  3973. }
  3974. }
  3975. @Override
  3976. public void onDragCancel() {
  3977. // cancel next click so that we may prevent column sorting if
  3978. // mouse was released on top of the dragged cell
  3979. if (columnSortPreventRegistration == null) {
  3980. columnSortPreventRegistration = Event
  3981. .addNativePreviewHandler(new NativePreviewHandler() {
  3982. @Override
  3983. public void onPreviewNativeEvent(
  3984. NativePreviewEvent event) {
  3985. if (event.getTypeInt() == Event.ONCLICK) {
  3986. event.cancel();
  3987. event.getNativeEvent().preventDefault();
  3988. columnSortPreventRegistration
  3989. .removeHandler();
  3990. columnSortPreventRegistration = null;
  3991. }
  3992. }
  3993. });
  3994. }
  3995. autoScroller.stop();
  3996. }
  3997. /**
  3998. * Returns the amount of frozen columns. The selection column is always
  3999. * considered frozen, since it can't be moved.
  4000. */
  4001. private int getSelectionAndFrozenColumnCount() {
  4002. // no matter if selection column is frozen or not, it is considered
  4003. // frozen for column dnd reorder
  4004. if (getSelectionModel().getSelectionColumnRenderer() != null) {
  4005. return Math.max(0, getFrozenColumnCount()) + 1;
  4006. } else {
  4007. return Math.max(0, getFrozenColumnCount());
  4008. }
  4009. }
  4010. @SuppressWarnings("boxing")
  4011. private void calculatePossibleDropPositions() {
  4012. possibleDropPositions.clear();
  4013. final int draggedColumnIndex = eventCell.getColumnIndex();
  4014. final StaticRow<?> draggedCellRow = header
  4015. .getRow(eventCell.getRowIndex());
  4016. final int draggedColumnRightIndex = draggedColumnIndex
  4017. + draggedCellRow.getCell(eventCell.getColumn())
  4018. .getColspan();
  4019. final int frozenColumns = getSelectionAndFrozenColumnCount();
  4020. final Range draggedCellRange = Range.between(draggedColumnIndex,
  4021. draggedColumnRightIndex);
  4022. /*
  4023. * If the dragged cell intersects with a spanned cell in any other
  4024. * header or footer row, then the drag is limited inside that
  4025. * spanned cell. The same rules apply: the cell can't be dropped
  4026. * inside another spanned cell. The left and right bounds keep track
  4027. * of the edges of the most limiting spanned cell.
  4028. */
  4029. int leftBound = -1;
  4030. int rightBound = getColumnCount() + 1;
  4031. final HashSet<Integer> unavailableColumnDropIndices = new HashSet<Integer>();
  4032. final List<StaticRow<?>> rows = new ArrayList<StaticRow<?>>();
  4033. rows.addAll(header.getRows());
  4034. rows.addAll(footer.getRows());
  4035. for (StaticRow<?> row : rows) {
  4036. if (!row.hasSpannedCells()) {
  4037. continue;
  4038. }
  4039. final boolean isDraggedCellRow = row.equals(draggedCellRow);
  4040. for (int cellColumnIndex = frozenColumns; cellColumnIndex < getColumnCount(); cellColumnIndex++) {
  4041. StaticCell cell = row.getCell(getColumn(cellColumnIndex));
  4042. int colspan = cell.getColspan();
  4043. if (colspan <= 1) {
  4044. continue;
  4045. }
  4046. final int cellColumnRightIndex = cellColumnIndex + colspan;
  4047. final Range cellRange = Range.between(cellColumnIndex,
  4048. cellColumnRightIndex);
  4049. final boolean intersects = draggedCellRange
  4050. .intersects(cellRange);
  4051. if (intersects && !isDraggedCellRow) {
  4052. // if the currently iterated cell is inside or same as
  4053. // the dragged cell, then it doesn't restrict the drag
  4054. if (cellRange.isSubsetOf(draggedCellRange)) {
  4055. cellColumnIndex = cellColumnRightIndex - 1;
  4056. continue;
  4057. }
  4058. /*
  4059. * if the dragged cell is a spanned cell and it crosses
  4060. * with the currently iterated cell without sharing
  4061. * either start or end then not possible to drag the
  4062. * cell.
  4063. */
  4064. if (!draggedCellRange.isSubsetOf(cellRange)) {
  4065. return;
  4066. }
  4067. // the spanned cell overlaps the dragged cell (but is
  4068. // not the dragged cell)
  4069. if (cellColumnIndex <= draggedColumnIndex
  4070. && cellColumnIndex > leftBound) {
  4071. leftBound = cellColumnIndex;
  4072. }
  4073. if (cellColumnRightIndex < rightBound) {
  4074. rightBound = cellColumnRightIndex;
  4075. }
  4076. cellColumnIndex = cellColumnRightIndex - 1;
  4077. } else {
  4078. // can't drop inside a spanned cell, or this is the
  4079. // dragged cell
  4080. while (colspan > 1) {
  4081. cellColumnIndex++;
  4082. colspan--;
  4083. unavailableColumnDropIndices.add(cellColumnIndex);
  4084. }
  4085. }
  4086. }
  4087. }
  4088. if (leftBound == rightBound - 1) {
  4089. return;
  4090. }
  4091. double position = autoScroller.getFrozenColumnsWidth();
  4092. // iterate column indices and add possible drop positions
  4093. for (int i = frozenColumns; i < getColumnCount(); i++) {
  4094. Column<?, T> column = getColumn(i);
  4095. if (!unavailableColumnDropIndices.contains(i)
  4096. && !column.isHidden()) {
  4097. if (leftBound != -1) {
  4098. if (i >= leftBound && i <= rightBound) {
  4099. possibleDropPositions.put(position, i);
  4100. }
  4101. } else {
  4102. possibleDropPositions.put(position, i);
  4103. }
  4104. }
  4105. position += column.getWidthActual();
  4106. }
  4107. if (leftBound == -1) {
  4108. // add the right side of the last column as columns.size()
  4109. possibleDropPositions.put(position, getColumnCount());
  4110. }
  4111. }
  4112. };
  4113. /**
  4114. * Enumeration for easy setting of selection mode.
  4115. */
  4116. public enum SelectionMode {
  4117. /**
  4118. * Shortcut for {@link SelectionModelSingle}.
  4119. */
  4120. SINGLE {
  4121. @Override
  4122. protected <T> SelectionModel<T> createModel() {
  4123. return GWT.create(SelectionModelSingle.class);
  4124. }
  4125. },
  4126. /**
  4127. * Shortcut for {@link SelectionModelMulti}.
  4128. */
  4129. MULTI {
  4130. @Override
  4131. protected <T> SelectionModel<T> createModel() {
  4132. return GWT.create(SelectionModelMulti.class);
  4133. }
  4134. },
  4135. /**
  4136. * Shortcut for {@link SelectionModelNone}.
  4137. */
  4138. NONE {
  4139. @Override
  4140. protected <T> SelectionModel<T> createModel() {
  4141. return GWT.create(SelectionModelNone.class);
  4142. }
  4143. };
  4144. protected abstract <T> SelectionModel<T> createModel();
  4145. }
  4146. /**
  4147. * Base class for grid columns internally used by the Grid. The user should
  4148. * use {@link Column} when creating new columns.
  4149. *
  4150. * @param <C>
  4151. * the column type
  4152. *
  4153. * @param <T>
  4154. * the row type
  4155. */
  4156. public abstract static class Column<C, T> {
  4157. /**
  4158. * Default renderer for GridColumns. Renders everything into text
  4159. * through {@link Object#toString()}.
  4160. */
  4161. private final class DefaultTextRenderer implements Renderer<Object> {
  4162. boolean warned = false;
  4163. private static final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  4164. + "A more suitable renderer should be set using the setRenderer() method.";
  4165. @Override
  4166. public void render(RendererCellReference cell, Object data) {
  4167. if (!warned && !(data instanceof String)) {
  4168. getLogger().warning(Column.this.toString() + ": "
  4169. + DEFAULT_RENDERER_WARNING);
  4170. warned = true;
  4171. }
  4172. final String text;
  4173. if (data == null) {
  4174. text = "";
  4175. } else {
  4176. text = data.toString();
  4177. }
  4178. cell.getElement().setInnerText(text);
  4179. }
  4180. }
  4181. /**
  4182. * the column is associated with
  4183. */
  4184. private Grid<T> grid;
  4185. /**
  4186. * Width of column in pixels as {@link #setWidth(double)} has been called.
  4187. */
  4188. protected double widthUser = GridConstants.DEFAULT_COLUMN_WIDTH_PX;
  4189. /**
  4190. * Renderer for rendering a value into the cell
  4191. */
  4192. private Renderer<? super C> bodyRenderer;
  4193. /**
  4194. * The sortable state of this column.
  4195. */
  4196. protected boolean sortable = false;
  4197. /**
  4198. * The editable state of this column.
  4199. */
  4200. protected boolean editable = true;
  4201. /**
  4202. * The resizable state of this column.
  4203. */
  4204. protected boolean resizable = true;
  4205. /**
  4206. * The hidden state of this column.
  4207. */
  4208. protected boolean hidden = false;
  4209. /**
  4210. * The hidable state of this column.
  4211. */
  4212. protected boolean hidable = false;
  4213. /**
  4214. * The header-caption of this column.
  4215. */
  4216. protected String headerCaption = "";
  4217. /**
  4218. * The hiding-toggle-caption of this column.
  4219. */
  4220. protected String hidingToggleCaption = null;
  4221. /**
  4222. * The minimum width in pixels of this column.
  4223. */
  4224. protected double minimumWidthPx = GridConstants.DEFAULT_MIN_WIDTH;
  4225. /**
  4226. * The maximum width in pixels of this column.
  4227. */
  4228. protected double maximumWidthPx = GridConstants.DEFAULT_MAX_WIDTH;
  4229. /**
  4230. * The expand ratio of this column.
  4231. */
  4232. protected int expandRatio = GridConstants.DEFAULT_EXPAND_RATIO;
  4233. /**
  4234. * Constructs a new column with a simple TextRenderer.
  4235. */
  4236. public Column() {
  4237. setRenderer(new DefaultTextRenderer());
  4238. }
  4239. /**
  4240. * Constructs a new column with a simple TextRenderer.
  4241. *
  4242. * @param caption
  4243. * The header caption for this column
  4244. *
  4245. * @throws IllegalArgumentException
  4246. * if given header caption is null
  4247. */
  4248. public Column(String caption) throws IllegalArgumentException {
  4249. this();
  4250. setHeaderCaption(caption);
  4251. }
  4252. /**
  4253. * Constructs a new column with a custom renderer.
  4254. *
  4255. * @param renderer
  4256. * The renderer to use for rendering the cells
  4257. *
  4258. * @throws IllegalArgumentException
  4259. * if given Renderer is null
  4260. */
  4261. public Column(Renderer<? super C> renderer)
  4262. throws IllegalArgumentException {
  4263. setRenderer(renderer);
  4264. }
  4265. /**
  4266. * Constructs a new column with a custom renderer.
  4267. *
  4268. * @param renderer
  4269. * The renderer to use for rendering the cells
  4270. * @param caption
  4271. * The header caption for this column
  4272. *
  4273. * @throws IllegalArgumentException
  4274. * if given Renderer or header caption is null
  4275. */
  4276. public Column(String caption, Renderer<? super C> renderer)
  4277. throws IllegalArgumentException {
  4278. this(renderer);
  4279. setHeaderCaption(caption);
  4280. }
  4281. /**
  4282. * Internally used by the grid to set itself
  4283. *
  4284. * @param grid
  4285. */
  4286. private void setGrid(Grid<T> grid) {
  4287. if (this.grid != null && grid != null) {
  4288. // Trying to replace grid
  4289. throw new IllegalStateException("Column already is attached "
  4290. + "to a grid. Remove the column first from the grid "
  4291. + "and then add it. (in: " + toString() + ")");
  4292. }
  4293. if (this.grid != null) {
  4294. this.grid.recalculateColumnWidths();
  4295. }
  4296. this.grid = grid;
  4297. if (this.grid != null) {
  4298. this.grid.recalculateColumnWidths();
  4299. }
  4300. }
  4301. /**
  4302. * Sets a header caption for this column.
  4303. *
  4304. * @param caption
  4305. * The header caption for this column
  4306. * @return the column itself
  4307. *
  4308. */
  4309. public Column<C, T> setHeaderCaption(String caption) {
  4310. if (caption == null) {
  4311. caption = "";
  4312. }
  4313. if (!this.headerCaption.equals(caption)) {
  4314. this.headerCaption = caption;
  4315. if (grid != null) {
  4316. updateHeader();
  4317. }
  4318. }
  4319. return this;
  4320. }
  4321. /**
  4322. * Returns the current header caption for this column.
  4323. *
  4324. * @since 7.6
  4325. * @return the header caption string
  4326. */
  4327. public String getHeaderCaption() {
  4328. return headerCaption;
  4329. }
  4330. private void updateHeader() {
  4331. HeaderRow row = grid.getHeader().getDefaultRow();
  4332. if (row != null) {
  4333. row.getCell(this).setText(headerCaption);
  4334. if (isHidable()) {
  4335. grid.columnHider.updateHidingToggle(this);
  4336. }
  4337. }
  4338. }
  4339. /**
  4340. * Returns the data that should be rendered into the cell. By default
  4341. * returning Strings and Widgets are supported. If the return type is a
  4342. * String then it will be treated as preformatted text.
  4343. * <p>
  4344. * To support other types you will need to pass a custom renderer to the
  4345. * column via the column constructor.
  4346. *
  4347. * @param row
  4348. * The row object that provides the cell content.
  4349. *
  4350. * @return The cell content
  4351. */
  4352. public abstract C getValue(T row);
  4353. /**
  4354. * The renderer to render the cell with. By default renders the data as
  4355. * a String or adds the widget into the cell if the column type is of
  4356. * widget type.
  4357. *
  4358. * @return The renderer to render the cell content with
  4359. */
  4360. public Renderer<? super C> getRenderer() {
  4361. return bodyRenderer;
  4362. }
  4363. /**
  4364. * Sets a custom {@link Renderer} for this column.
  4365. *
  4366. * @param renderer
  4367. * The renderer to use for rendering the cells
  4368. * @return the column itself
  4369. *
  4370. * @throws IllegalArgumentException
  4371. * if given Renderer is null
  4372. */
  4373. public Column<C, T> setRenderer(Renderer<? super C> renderer)
  4374. throws IllegalArgumentException {
  4375. if (renderer == null) {
  4376. throw new IllegalArgumentException("Renderer cannot be null.");
  4377. }
  4378. if (renderer != bodyRenderer) {
  4379. // Variables used to restore removed column.
  4380. boolean columnRemoved = false;
  4381. double widthInConfiguration = 0.0d;
  4382. ColumnConfiguration conf = null;
  4383. int index = 0;
  4384. if (grid != null && (bodyRenderer instanceof WidgetRenderer
  4385. || renderer instanceof WidgetRenderer)) {
  4386. // Column needs to be recreated.
  4387. index = grid.getColumns().indexOf(this);
  4388. conf = grid.escalator.getColumnConfiguration();
  4389. widthInConfiguration = conf.getColumnWidth(index);
  4390. conf.removeColumns(index, 1);
  4391. columnRemoved = true;
  4392. }
  4393. // Complex renderers need to be destroyed.
  4394. if (bodyRenderer instanceof ComplexRenderer) {
  4395. ((ComplexRenderer) bodyRenderer).destroy();
  4396. }
  4397. bodyRenderer = renderer;
  4398. if (columnRemoved) {
  4399. // Restore the column.
  4400. conf.insertColumns(index, 1);
  4401. conf.setColumnWidth(index, widthInConfiguration);
  4402. }
  4403. if (grid != null) {
  4404. grid.refreshBody();
  4405. }
  4406. }
  4407. return this;
  4408. }
  4409. /**
  4410. * Sets the pixel width of the column. Use a negative value for the grid
  4411. * to autosize column based on content and available space.
  4412. * <p>
  4413. * This action is done "finally", once the current execution loop
  4414. * returns. This is done to reduce overhead of unintentionally always
  4415. * recalculate all columns, when modifying several columns at once.
  4416. * <p>
  4417. * If the column is currently {@link #isHidden() hidden}, then this set
  4418. * width has effect only once the column has been made visible again.
  4419. *
  4420. * @param pixels
  4421. * the width in pixels or negative for auto sizing
  4422. */
  4423. public Column<C, T> setWidth(double pixels) {
  4424. if (!WidgetUtil.pixelValuesEqual(widthUser, pixels)) {
  4425. widthUser = pixels;
  4426. if (!isHidden()) {
  4427. scheduleColumnWidthRecalculator();
  4428. }
  4429. }
  4430. return this;
  4431. }
  4432. void doSetWidth(double pixels) {
  4433. assert !isHidden() : "applying width for a hidden column";
  4434. if (grid != null) {
  4435. int index = grid.getVisibleColumns().indexOf(this);
  4436. ColumnConfiguration conf = grid.escalator
  4437. .getColumnConfiguration();
  4438. conf.setColumnWidth(index, pixels);
  4439. }
  4440. }
  4441. /**
  4442. * Returns the pixel width of the column as given by the user.
  4443. * <p>
  4444. * <em>Note:</em> If a negative value was given to
  4445. * {@link #setWidth(double)}, that same negative value is returned here.
  4446. * <p>
  4447. * <em>Note:</em> Returns the value, even if the column is currently
  4448. * {@link #isHidden() hidden}.
  4449. *
  4450. * @return pixel width of the column, or a negative number if the column
  4451. * width has been automatically calculated.
  4452. * @see #setWidth(double)
  4453. * @see #getWidthActual()
  4454. */
  4455. public double getWidth() {
  4456. return widthUser;
  4457. }
  4458. /**
  4459. * Returns the effective pixel width of the column.
  4460. * <p>
  4461. * This differs from {@link #getWidth()} only when the column has been
  4462. * automatically resized, or when the column is currently
  4463. * {@link #isHidden() hidden}, when the value is 0.
  4464. *
  4465. * @return pixel width of the column.
  4466. */
  4467. public double getWidthActual() {
  4468. if (isHidden()) {
  4469. return 0;
  4470. }
  4471. return grid.escalator.getColumnConfiguration().getColumnWidthActual(
  4472. grid.getVisibleColumns().indexOf(this));
  4473. }
  4474. void reapplyWidth() {
  4475. scheduleColumnWidthRecalculator();
  4476. }
  4477. /**
  4478. * Sets whether the column should be sortable by the user. The grid can
  4479. * be sorted by a sortable column by clicking or tapping the column's
  4480. * default header. Programmatic sorting using the Grid#sort methods is
  4481. * not affected by this setting.
  4482. *
  4483. * @param sortable
  4484. * {@code true} if the user should be able to sort the
  4485. * column, {@code false} otherwise
  4486. * @return the column itself
  4487. */
  4488. public Column<C, T> setSortable(boolean sortable) {
  4489. if (this.sortable != sortable) {
  4490. this.sortable = sortable;
  4491. if (grid != null) {
  4492. grid.refreshHeader();
  4493. }
  4494. }
  4495. return this;
  4496. }
  4497. /**
  4498. * Returns whether the user can sort the grid by this column.
  4499. * <p>
  4500. * <em>Note:</em> it is possible to sort by this column programmatically
  4501. * using the Grid#sort methods regardless of the returned value.
  4502. *
  4503. * @return {@code true} if the column is sortable by the user,
  4504. * {@code false} otherwise
  4505. */
  4506. public boolean isSortable() {
  4507. return sortable;
  4508. }
  4509. /**
  4510. * Sets whether this column can be resized by the user.
  4511. *
  4512. * @since 7.6
  4513. *
  4514. * @param resizable
  4515. * {@code true} if this column should be resizable,
  4516. * {@code false} otherwise
  4517. */
  4518. public Column<C, T> setResizable(boolean resizable) {
  4519. if (this.resizable != resizable) {
  4520. this.resizable = resizable;
  4521. if (grid != null) {
  4522. grid.refreshHeader();
  4523. }
  4524. }
  4525. return this;
  4526. }
  4527. /**
  4528. * Returns whether this column can be resized by the user. Default is
  4529. * {@code true}.
  4530. * <p>
  4531. * <em>Note:</em> the column can be programmatically resized using
  4532. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  4533. * of the returned value.
  4534. *
  4535. * @since 7.6
  4536. *
  4537. * @return {@code true} if this column is resizable, {@code false}
  4538. * otherwise
  4539. */
  4540. public boolean isResizable() {
  4541. return resizable;
  4542. }
  4543. /**
  4544. * Hides or shows the column. By default columns are visible before
  4545. * explicitly hiding them.
  4546. *
  4547. * @since 7.5.0
  4548. * @param hidden
  4549. * <code>true</code> to hide the column, <code>false</code>
  4550. * to show
  4551. */
  4552. public Column<C, T> setHidden(boolean hidden) {
  4553. setHidden(hidden, false);
  4554. return this;
  4555. }
  4556. private void setHidden(boolean hidden, boolean userOriginated) {
  4557. if (this.hidden != hidden) {
  4558. if (hidden) {
  4559. grid.escalator.getColumnConfiguration().removeColumns(
  4560. grid.getVisibleColumns().indexOf(this), 1);
  4561. this.hidden = hidden;
  4562. } else {
  4563. this.hidden = hidden;
  4564. final int columnIndex = grid.getVisibleColumns()
  4565. .indexOf(this);
  4566. grid.escalator.getColumnConfiguration()
  4567. .insertColumns(columnIndex, 1);
  4568. // make sure column is set to frozen if it needs to be,
  4569. // escalator doesn't handle situation where the added column
  4570. // would be the last frozen column
  4571. int gridFrozenColumns = grid.getFrozenColumnCount();
  4572. int escalatorFrozenColumns = grid.escalator
  4573. .getColumnConfiguration().getFrozenColumnCount();
  4574. if (gridFrozenColumns > escalatorFrozenColumns
  4575. && escalatorFrozenColumns == columnIndex) {
  4576. grid.escalator.getColumnConfiguration()
  4577. .setFrozenColumnCount(++escalatorFrozenColumns);
  4578. }
  4579. }
  4580. grid.columnHider.updateHidingToggle(this);
  4581. grid.header.updateColSpans();
  4582. grid.footer.updateColSpans();
  4583. scheduleColumnWidthRecalculator();
  4584. this.grid.fireEvent(new ColumnVisibilityChangeEvent<T>(this,
  4585. hidden, userOriginated));
  4586. }
  4587. }
  4588. /**
  4589. * Returns whether this column is hidden. Default is {@code false}.
  4590. *
  4591. * @since 7.5.0
  4592. * @return {@code true} if the column is currently hidden, {@code false}
  4593. * otherwise
  4594. */
  4595. public boolean isHidden() {
  4596. return hidden;
  4597. }
  4598. /**
  4599. * Set whether it is possible for the user to hide this column or not.
  4600. * Default is {@code false}.
  4601. * <p>
  4602. * <em>Note:</em> it is still possible to hide the column
  4603. * programmatically using {@link #setHidden(boolean)}.
  4604. *
  4605. * @since 7.5.0
  4606. * @param hidable
  4607. * {@code true} the user can hide this column, {@code false}
  4608. * otherwise
  4609. */
  4610. public Column<C, T> setHidable(boolean hidable) {
  4611. if (this.hidable != hidable) {
  4612. this.hidable = hidable;
  4613. grid.columnHider.updateColumnHidable(this);
  4614. }
  4615. return this;
  4616. }
  4617. /**
  4618. * Is it possible for the the user to hide this column. Default is
  4619. * {@code false}.
  4620. * <p>
  4621. * <em>Note:</em> the column can be programmatically hidden using
  4622. * {@link #setHidden(boolean)} regardless of the returned value.
  4623. *
  4624. * @since 7.5.0
  4625. * @return <code>true</code> if the user can hide the column,
  4626. * <code>false</code> if not
  4627. */
  4628. public boolean isHidable() {
  4629. return hidable;
  4630. }
  4631. /**
  4632. * Sets the hiding toggle's caption for this column. Shown in the toggle
  4633. * for this column in the grid's sidebar when the column is
  4634. * {@link #isHidable() hidable}.
  4635. * <p>
  4636. * The default value is <code>null</code>. In this case the header
  4637. * caption is used, see {@link #setHeaderCaption(String)}.
  4638. *
  4639. * @since 7.5.0
  4640. * @param hidingToggleCaption
  4641. * the caption for the hiding toggle for this column
  4642. */
  4643. public Column<C, T> setHidingToggleCaption(String hidingToggleCaption) {
  4644. this.hidingToggleCaption = hidingToggleCaption;
  4645. if (isHidable()) {
  4646. grid.columnHider.updateHidingToggle(this);
  4647. }
  4648. return this;
  4649. }
  4650. /**
  4651. * Gets the hiding toggle caption for this column.
  4652. *
  4653. * @since 7.5.0
  4654. * @see #setHidingToggleCaption(String)
  4655. * @return the hiding toggle's caption for this column
  4656. */
  4657. public String getHidingToggleCaption() {
  4658. return hidingToggleCaption;
  4659. }
  4660. @Override
  4661. public String toString() {
  4662. String details = "";
  4663. if (headerCaption != null && !headerCaption.isEmpty()) {
  4664. details += "header:\"" + headerCaption + "\" ";
  4665. } else {
  4666. details += "header:empty ";
  4667. }
  4668. if (grid != null) {
  4669. int index = grid.getColumns().indexOf(this);
  4670. if (index != -1) {
  4671. details += "attached:#" + index + " ";
  4672. } else {
  4673. details += "attached:unindexed ";
  4674. }
  4675. } else {
  4676. details += "detached ";
  4677. }
  4678. details += "sortable:" + sortable + " ";
  4679. return getClass().getSimpleName() + "[" + details.trim() + "]";
  4680. }
  4681. /**
  4682. * Sets the minimum width for this column.
  4683. * <p>
  4684. * This defines the minimum guaranteed pixel width of the column
  4685. * <em>when it is set to expand</em>.
  4686. * <p>
  4687. * This action is done "finally", once the current execution loop
  4688. * returns. This is done to reduce overhead of unintentionally always
  4689. * recalculate all columns, when modifying several columns at once.
  4690. *
  4691. * @param pixels
  4692. * the minimum width
  4693. * @return this column
  4694. */
  4695. public Column<C, T> setMinimumWidth(double pixels) {
  4696. final double maxwidth = getMaximumWidth();
  4697. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  4698. throw new IllegalArgumentException("New minimum width ("
  4699. + pixels + ") was greater than maximum width ("
  4700. + maxwidth + ")");
  4701. }
  4702. if (minimumWidthPx != pixels) {
  4703. minimumWidthPx = pixels;
  4704. scheduleColumnWidthRecalculator();
  4705. }
  4706. return this;
  4707. }
  4708. /**
  4709. * Sets the maximum width for this column.
  4710. * <p>
  4711. * This defines the maximum allowed pixel width of the column <em>when
  4712. * it is set to expand</em>.
  4713. * <p>
  4714. * This action is done "finally", once the current execution loop
  4715. * returns. This is done to reduce overhead of unintentionally always
  4716. * recalculate all columns, when modifying several columns at once.
  4717. *
  4718. * @param pixels
  4719. * the maximum width
  4720. * @return this column
  4721. */
  4722. public Column<C, T> setMaximumWidth(double pixels) {
  4723. final double minwidth = getMinimumWidth();
  4724. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  4725. throw new IllegalArgumentException("New maximum width ("
  4726. + pixels + ") was less than minimum width (" + minwidth
  4727. + ")");
  4728. }
  4729. if (maximumWidthPx != pixels) {
  4730. maximumWidthPx = pixels;
  4731. scheduleColumnWidthRecalculator();
  4732. }
  4733. return this;
  4734. }
  4735. /**
  4736. * Sets the ratio with which the column expands.
  4737. * <p>
  4738. * By default, all columns expand equally (treated as if all of them had
  4739. * an expand ratio of 1). Once at least one column gets a defined expand
  4740. * ratio, the implicit expand ratio is removed, and only the defined
  4741. * expand ratios are taken into account.
  4742. * <p>
  4743. * If a column has a defined width ({@link #setWidth(double)}), it
  4744. * overrides this method's effects.
  4745. * <p>
  4746. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  4747. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  4748. * as wide as its contents requires</strong>. The column with a ratio of
  4749. * 1 is as wide as it needs, <strong>plus a third of any excess
  4750. * space</strong>, bceause we have 3 parts total, and this column
  4751. * reservs only one of those. The column with a ratio of 2, is as wide
  4752. * as it needs to be, <strong>plus two thirds</strong> of the excess
  4753. * width.
  4754. * <p>
  4755. * This action is done "finally", once the current execution loop
  4756. * returns. This is done to reduce overhead of unintentionally always
  4757. * recalculate all columns, when modifying several columns at once.
  4758. *
  4759. * @param ratio
  4760. * the expand ratio of this column. {@code 0} to not have it
  4761. * expand at all. A negative number to clear the expand
  4762. * value.
  4763. * @return this column
  4764. */
  4765. public Column<C, T> setExpandRatio(int ratio) {
  4766. if (expandRatio != ratio) {
  4767. expandRatio = ratio;
  4768. scheduleColumnWidthRecalculator();
  4769. }
  4770. return this;
  4771. }
  4772. /**
  4773. * Clears the column's expand ratio.
  4774. * <p>
  4775. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  4776. *
  4777. * @return this column
  4778. */
  4779. public Column<C, T> clearExpandRatio() {
  4780. return setExpandRatio(-1);
  4781. }
  4782. /**
  4783. * Gets the minimum width for this column.
  4784. *
  4785. * @return the minimum width for this column
  4786. * @see #setMinimumWidth(double)
  4787. */
  4788. public double getMinimumWidth() {
  4789. return minimumWidthPx;
  4790. }
  4791. /**
  4792. * Gets the maximum width for this column.
  4793. *
  4794. * @return the maximum width for this column
  4795. * @see #setMaximumWidth(double)
  4796. */
  4797. public double getMaximumWidth() {
  4798. return maximumWidthPx;
  4799. }
  4800. /**
  4801. * Gets the expand ratio for this column.
  4802. *
  4803. * @return the expand ratio for this column
  4804. * @see #setExpandRatio(int)
  4805. */
  4806. public int getExpandRatio() {
  4807. return expandRatio;
  4808. }
  4809. /**
  4810. * Sets whether the values in this column should be editable by the user
  4811. * when the row editor is active. By default columns are editable.
  4812. *
  4813. * @param editable
  4814. * {@code true} to set this column editable, {@code false}
  4815. * otherwise
  4816. * @return this column
  4817. *
  4818. * @throws IllegalStateException
  4819. * if the editor is currently active
  4820. *
  4821. * @see Grid#editRow(int)
  4822. * @see Grid#isEditorActive()
  4823. */
  4824. public Column<C, T> setEditable(boolean editable) {
  4825. if (editable != this.editable && grid.isEditorActive()) {
  4826. throw new IllegalStateException(
  4827. "Cannot change column editable status while the editor is active");
  4828. }
  4829. this.editable = editable;
  4830. return this;
  4831. }
  4832. /**
  4833. * Returns whether the values in this column are editable by the user
  4834. * when the row editor is active.
  4835. *
  4836. * @return {@code true} if this column is editable, {@code false}
  4837. * otherwise
  4838. *
  4839. * @see #setEditable(boolean)
  4840. */
  4841. public boolean isEditable() {
  4842. return editable;
  4843. }
  4844. private void scheduleColumnWidthRecalculator() {
  4845. if (grid != null) {
  4846. grid.recalculateColumnWidths();
  4847. } else {
  4848. /*
  4849. * NOOP
  4850. *
  4851. * Since setGrid() will call reapplyWidths as the colum is
  4852. * attached to a grid, it will call setWidth, which, in turn,
  4853. * will call this method again. Therefore, it's guaranteed that
  4854. * the recalculation is scheduled eventually, once the column is
  4855. * attached to a grid.
  4856. */
  4857. }
  4858. }
  4859. /**
  4860. * Resets the default header cell contents to column header captions.
  4861. *
  4862. * @since 7.5.1
  4863. * @param cell
  4864. * default header cell for this column
  4865. */
  4866. protected void setDefaultHeaderContent(HeaderCell cell) {
  4867. cell.setText(headerCaption);
  4868. }
  4869. }
  4870. protected class BodyUpdater implements EscalatorUpdater {
  4871. @Override
  4872. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  4873. int rowIndex = row.getRow();
  4874. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  4875. row.getElement());
  4876. for (FlyweightCell cell : cellsToAttach) {
  4877. Renderer<?> renderer = findRenderer(cell);
  4878. if (renderer instanceof ComplexRenderer) {
  4879. try {
  4880. Column<?, T> column = getVisibleColumn(
  4881. cell.getColumn());
  4882. rendererCellReference.set(cell,
  4883. getColumns().indexOf(column), column);
  4884. ((ComplexRenderer<?>) renderer)
  4885. .init(rendererCellReference);
  4886. } catch (RuntimeException e) {
  4887. getLogger().log(Level.SEVERE,
  4888. "Error initing cell in column "
  4889. + cell.getColumn(),
  4890. e);
  4891. }
  4892. }
  4893. }
  4894. }
  4895. @Override
  4896. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  4897. for (FlyweightCell cell : attachedCells) {
  4898. Renderer<?> renderer = findRenderer(cell);
  4899. if (renderer instanceof WidgetRenderer) {
  4900. try {
  4901. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  4902. Widget widget = widgetRenderer.createWidget();
  4903. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  4904. assert widget
  4905. .getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  4906. assert cell.getElement()
  4907. .getChildCount() == 0 : "Cell content should be empty when adding Widget";
  4908. // Physical attach
  4909. cell.getElement().appendChild(widget.getElement());
  4910. // Logical attach
  4911. setParent(widget, Grid.this);
  4912. } catch (RuntimeException e) {
  4913. getLogger().log(Level.SEVERE,
  4914. "Error attaching child widget in column "
  4915. + cell.getColumn(),
  4916. e);
  4917. }
  4918. }
  4919. }
  4920. }
  4921. @Override
  4922. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4923. int rowIndex = row.getRow();
  4924. TableRowElement rowElement = row.getElement();
  4925. T rowData = dataSource.getRow(rowIndex);
  4926. boolean hasData = rowData != null;
  4927. /*
  4928. * TODO could be more efficient to build a list of all styles that
  4929. * should be used and update the element only once instead of
  4930. * attempting to update only the ones that have changed.
  4931. */
  4932. // Assign stylename for rows with data
  4933. boolean usedToHaveData = rowElement
  4934. .hasClassName(rowHasDataStyleName);
  4935. if (usedToHaveData != hasData) {
  4936. setStyleName(rowElement, rowHasDataStyleName, hasData);
  4937. }
  4938. boolean isEvenIndex = row.getRow() % 2 == 0;
  4939. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  4940. rowReference.set(rowIndex, rowData, rowElement);
  4941. if (hasData) {
  4942. setStyleName(rowElement, rowSelectedStyleName,
  4943. isSelected(rowData));
  4944. if (rowStyleGenerator != null) {
  4945. try {
  4946. String rowStylename = rowStyleGenerator
  4947. .getStyle(rowReference);
  4948. setCustomStyleName(rowElement, rowStylename);
  4949. } catch (RuntimeException e) {
  4950. getLogger().log(Level.SEVERE,
  4951. "Error generating styles for row "
  4952. + row.getRow(),
  4953. e);
  4954. }
  4955. } else {
  4956. // Remove in case there was a generator previously
  4957. setCustomStyleName(rowElement, null);
  4958. }
  4959. } else if (usedToHaveData) {
  4960. setStyleName(rowElement, rowSelectedStyleName, false);
  4961. setCustomStyleName(rowElement, null);
  4962. }
  4963. cellFocusHandler.updateFocusedRowStyle(row);
  4964. for (FlyweightCell cell : cellsToUpdate) {
  4965. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4966. final int columnIndex = getColumns().indexOf(column);
  4967. assert column != null : "Column was not found from cell ("
  4968. + cell.getColumn() + "," + cell.getRow() + ")";
  4969. cellFocusHandler.updateFocusedCellStyle(cell,
  4970. escalator.getBody());
  4971. if (hasData && cellStyleGenerator != null) {
  4972. try {
  4973. cellReference.set(cell.getColumn(), columnIndex,
  4974. column);
  4975. String generatedStyle = cellStyleGenerator
  4976. .getStyle(cellReference);
  4977. setCustomStyleName(cell.getElement(), generatedStyle);
  4978. } catch (RuntimeException e) {
  4979. getLogger().log(Level.SEVERE,
  4980. "Error generating style for cell in column "
  4981. + cell.getColumn(),
  4982. e);
  4983. }
  4984. } else if (hasData || usedToHaveData) {
  4985. setCustomStyleName(cell.getElement(), null);
  4986. }
  4987. Renderer renderer = column.getRenderer();
  4988. try {
  4989. rendererCellReference.set(cell, columnIndex, column);
  4990. if (renderer instanceof ComplexRenderer) {
  4991. // Hide cell content if needed
  4992. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  4993. if (hasData) {
  4994. if (!usedToHaveData) {
  4995. // Prepare cell for rendering
  4996. clxRenderer.setContentVisible(
  4997. rendererCellReference, true);
  4998. }
  4999. Object value = column.getValue(rowData);
  5000. clxRenderer.render(rendererCellReference, value);
  5001. } else {
  5002. // Prepare cell for no data
  5003. clxRenderer.setContentVisible(rendererCellReference,
  5004. false);
  5005. }
  5006. } else if (hasData) {
  5007. // Simple renderers just render
  5008. Object value = column.getValue(rowData);
  5009. renderer.render(rendererCellReference, value);
  5010. } else {
  5011. // Clear cell if there is no data
  5012. cell.getElement().removeAllChildren();
  5013. }
  5014. } catch (RuntimeException e) {
  5015. getLogger().log(Level.SEVERE,
  5016. "Error rendering cell in column "
  5017. + cell.getColumn(),
  5018. e);
  5019. }
  5020. }
  5021. }
  5022. @Override
  5023. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5024. for (FlyweightCell cell : cellsToDetach) {
  5025. Renderer<?> renderer = findRenderer(cell);
  5026. if (renderer instanceof WidgetRenderer) {
  5027. try {
  5028. Widget w = WidgetUtil.findWidget(
  5029. cell.getElement().getFirstChildElement());
  5030. if (w != null) {
  5031. // Logical detach
  5032. setParent(w, null);
  5033. // Physical detach
  5034. cell.getElement().removeChild(w.getElement());
  5035. }
  5036. } catch (RuntimeException e) {
  5037. getLogger().log(Level.SEVERE,
  5038. "Error detaching widget in column "
  5039. + cell.getColumn(),
  5040. e);
  5041. }
  5042. }
  5043. }
  5044. }
  5045. @Override
  5046. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5047. int rowIndex = row.getRow();
  5048. // Passing null row data since it might not exist in the data source
  5049. // any more
  5050. rowReference.set(rowIndex, null, row.getElement());
  5051. for (FlyweightCell cell : detachedCells) {
  5052. Renderer<?> renderer = findRenderer(cell);
  5053. if (renderer instanceof ComplexRenderer) {
  5054. try {
  5055. Column<?, T> column = getVisibleColumn(
  5056. cell.getColumn());
  5057. rendererCellReference.set(cell,
  5058. getColumns().indexOf(column), column);
  5059. ((ComplexRenderer) renderer)
  5060. .destroy(rendererCellReference);
  5061. } catch (RuntimeException e) {
  5062. getLogger().log(Level.SEVERE,
  5063. "Error destroying cell in column "
  5064. + cell.getColumn(),
  5065. e);
  5066. }
  5067. }
  5068. }
  5069. }
  5070. }
  5071. protected class StaticSectionUpdater implements EscalatorUpdater {
  5072. private StaticSection<?> section;
  5073. private RowContainer container;
  5074. public StaticSectionUpdater(StaticSection<?> section,
  5075. RowContainer container) {
  5076. super();
  5077. this.section = section;
  5078. this.container = container;
  5079. }
  5080. @Override
  5081. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  5082. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  5083. final List<Column<?, T>> columns = getVisibleColumns();
  5084. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  5085. for (FlyweightCell cell : cellsToUpdate) {
  5086. final StaticSection.StaticCell metadata = staticRow
  5087. .getCell(columns.get(cell.getColumn()));
  5088. // Decorate default row with sorting indicators
  5089. if (staticRow instanceof HeaderRow) {
  5090. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow,
  5091. cell);
  5092. }
  5093. // Assign colspan to cell before rendering
  5094. cell.setColSpan(metadata.getColspan());
  5095. Element td = cell.getElement();
  5096. td.removeAllChildren();
  5097. setCustomStyleName(td, metadata.getStyleName());
  5098. Element content;
  5099. // Wrap text or html content in default header to isolate
  5100. // the content from the possible column resize drag handle
  5101. // next to it
  5102. if (metadata.getType() != GridStaticCellType.WIDGET) {
  5103. content = DOM.createDiv();
  5104. if (staticRow instanceof HeaderRow) {
  5105. content.setClassName(getStylePrimaryName()
  5106. + "-column-header-content");
  5107. if (((HeaderRow) staticRow).isDefault()) {
  5108. content.setClassName(content.getClassName() + " "
  5109. + getStylePrimaryName()
  5110. + "-column-default-header-content");
  5111. }
  5112. } else if (staticRow instanceof FooterRow) {
  5113. content.setClassName(getStylePrimaryName()
  5114. + "-column-footer-content");
  5115. } else {
  5116. getLogger().severe("Unhandled static row type "
  5117. + staticRow.getClass().getCanonicalName());
  5118. }
  5119. td.appendChild(content);
  5120. } else {
  5121. content = td;
  5122. }
  5123. switch (metadata.getType()) {
  5124. case TEXT:
  5125. content.setInnerText(metadata.getText());
  5126. break;
  5127. case HTML:
  5128. content.setInnerHTML(metadata.getHtml());
  5129. break;
  5130. case WIDGET:
  5131. preDetach(row, Arrays.asList(cell));
  5132. content.setInnerHTML("");
  5133. postAttach(row, Arrays.asList(cell));
  5134. break;
  5135. }
  5136. // XXX: Should add only once in preAttach/postAttach or when
  5137. // resizable status changes
  5138. // Only add resize handles to default header row for now
  5139. if (columns.get(cell.getColumn()).isResizable()
  5140. && staticRow instanceof HeaderRow
  5141. && ((HeaderRow) staticRow).isDefault()) {
  5142. final DivElement resizeElement = Document.get()
  5143. .createDivElement();
  5144. resizeElement.addClassName(getStylePrimaryName()
  5145. + "-column-resize-simple-indicator");
  5146. final int column = cell.getColumn();
  5147. final DragHandle dragger = new DragHandle(
  5148. getStylePrimaryName() + "-column-resize-handle");
  5149. dragger.addTo(td);
  5150. // Common functionality for drag handle callback
  5151. // implementations
  5152. abstract class AbstractDHCallback
  5153. implements DragHandleCallback {
  5154. protected Column<?, T> col = getVisibleColumn(column);
  5155. protected double initialWidth = 0;
  5156. protected double minCellWidth;
  5157. protected double width;
  5158. protected void dragStarted() {
  5159. initialWidth = col.getWidthActual();
  5160. width = initialWidth;
  5161. minCellWidth = escalator.getMinCellWidth(
  5162. getVisibleColumns().indexOf(col));
  5163. for (Column<?, T> c : getVisibleColumns()) {
  5164. if (selectionColumn == c) {
  5165. // Don't modify selection column.
  5166. continue;
  5167. }
  5168. if (c.getWidth() < 0) {
  5169. c.setWidth(c.getWidthActual());
  5170. fireEvent(new ColumnResizeEvent<T>(c));
  5171. }
  5172. }
  5173. WidgetUtil.setTextSelectionEnabled(getElement(),
  5174. false);
  5175. }
  5176. protected void dragEnded() {
  5177. WidgetUtil.setTextSelectionEnabled(getElement(),
  5178. true);
  5179. }
  5180. }
  5181. final DragHandleCallback simpleResizeMode = new AbstractDHCallback() {
  5182. @Override
  5183. protected void dragEnded() {
  5184. super.dragEnded();
  5185. dragger.getElement().removeChild(resizeElement);
  5186. }
  5187. @Override
  5188. public void onStart() {
  5189. dragStarted();
  5190. dragger.getElement().appendChild(resizeElement);
  5191. resizeElement.getStyle().setLeft(
  5192. (dragger.getElement().getOffsetWidth()
  5193. - resizeElement.getOffsetWidth())
  5194. * .5,
  5195. Unit.PX);
  5196. resizeElement.getStyle().setHeight(
  5197. col.grid.getOffsetHeight(), Unit.PX);
  5198. }
  5199. @Override
  5200. public void onUpdate(double deltaX, double deltaY) {
  5201. width = Math.max(minCellWidth,
  5202. initialWidth + deltaX);
  5203. resizeElement.getStyle().setLeft(
  5204. (dragger.getElement().getOffsetWidth()
  5205. - resizeElement.getOffsetWidth())
  5206. * .5 + (width - initialWidth),
  5207. Unit.PX);
  5208. }
  5209. @Override
  5210. public void onCancel() {
  5211. dragEnded();
  5212. }
  5213. @Override
  5214. public void onComplete() {
  5215. dragEnded();
  5216. col.setWidth(width);
  5217. // Need to wait for column width recalculation
  5218. // scheduled by setWidth() before firing the event
  5219. Scheduler.get().scheduleDeferred(
  5220. new ScheduledCommand() {
  5221. @Override
  5222. public void execute() {
  5223. fireEvent(new ColumnResizeEvent<T>(col));
  5224. }
  5225. });
  5226. }
  5227. };
  5228. final DragHandleCallback animatedResizeMode = new AbstractDHCallback() {
  5229. @Override
  5230. public void onStart() {
  5231. dragStarted();
  5232. }
  5233. @Override
  5234. public void onUpdate(double deltaX, double deltaY) {
  5235. width = Math.max(minCellWidth,
  5236. initialWidth + deltaX);
  5237. col.setWidth(width);
  5238. }
  5239. @Override
  5240. public void onCancel() {
  5241. dragEnded();
  5242. col.setWidth(initialWidth);
  5243. }
  5244. @Override
  5245. public void onComplete() {
  5246. dragEnded();
  5247. col.setWidth(width);
  5248. fireEvent(new ColumnResizeEvent<T>(col));
  5249. }
  5250. };
  5251. // DragHandle gets assigned a 'master callback' that
  5252. // delegates
  5253. // functionality to the correct case-specific implementation
  5254. dragger.setCallback(new DragHandleCallback() {
  5255. private DragHandleCallback currentCallback;
  5256. @Override
  5257. public void onStart() {
  5258. switch (getColumnResizeMode()) {
  5259. case SIMPLE:
  5260. currentCallback = simpleResizeMode;
  5261. break;
  5262. case ANIMATED:
  5263. currentCallback = animatedResizeMode;
  5264. break;
  5265. default:
  5266. throw new UnsupportedOperationException(
  5267. "Support for current column resize mode is not yet implemented");
  5268. }
  5269. currentCallback.onStart();
  5270. }
  5271. @Override
  5272. public void onUpdate(double deltaX, double deltaY) {
  5273. currentCallback.onUpdate(deltaX, deltaY);
  5274. }
  5275. @Override
  5276. public void onCancel() {
  5277. currentCallback.onCancel();
  5278. }
  5279. @Override
  5280. public void onComplete() {
  5281. currentCallback.onComplete();
  5282. }
  5283. });
  5284. }
  5285. cellFocusHandler.updateFocusedCellStyle(cell, container);
  5286. }
  5287. }
  5288. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  5289. FlyweightCell cell) {
  5290. Element cellElement = cell.getElement();
  5291. boolean sortedBefore = cellElement.hasClassName("sort-asc")
  5292. || cellElement.hasClassName("sort-desc");
  5293. cleanup(cell);
  5294. if (!headerRow.isDefault()) {
  5295. // Nothing more to do if not in the default row
  5296. return;
  5297. }
  5298. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5299. SortOrder sortingOrder = getSortOrder(column);
  5300. boolean sortable = column.isSortable();
  5301. if (sortable) {
  5302. cellElement.addClassName("sortable");
  5303. }
  5304. if (!sortable || sortingOrder == null) {
  5305. // Only apply sorting indicators to sortable header columns
  5306. return;
  5307. }
  5308. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  5309. cellElement.addClassName("sort-asc");
  5310. } else {
  5311. cellElement.addClassName("sort-desc");
  5312. }
  5313. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  5314. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  5315. // Show sort order indicator if column is
  5316. // sorted and other sorted columns also exists.
  5317. cellElement.setAttribute("sort-order",
  5318. String.valueOf(sortIndex + 1));
  5319. }
  5320. if (!sortedBefore) {
  5321. verifyColumnWidth(column);
  5322. }
  5323. }
  5324. /**
  5325. * Sort indicator requires a bit more space from the cell than normally.
  5326. * This method check that the now sorted column has enough width.
  5327. *
  5328. * @param column
  5329. * sorted column
  5330. */
  5331. private void verifyColumnWidth(Column<?, T> column) {
  5332. int colIndex = getColumns().indexOf(column);
  5333. double minWidth = escalator.getMinCellWidth(colIndex);
  5334. if (column.getWidthActual() < minWidth) {
  5335. // Fix column size
  5336. escalator.getColumnConfiguration().setColumnWidth(colIndex,
  5337. minWidth);
  5338. fireEvent(new ColumnResizeEvent<T>(column));
  5339. }
  5340. }
  5341. /**
  5342. * Finds the sort order for this column
  5343. */
  5344. private SortOrder getSortOrder(Column<?, ?> column) {
  5345. for (SortOrder order : Grid.this.getSortOrder()) {
  5346. if (order.getColumn() == column) {
  5347. return order;
  5348. }
  5349. }
  5350. return null;
  5351. }
  5352. private void cleanup(FlyweightCell cell) {
  5353. Element cellElement = cell.getElement();
  5354. cellElement.removeAttribute("sort-order");
  5355. cellElement.removeClassName("sort-desc");
  5356. cellElement.removeClassName("sort-asc");
  5357. cellElement.removeClassName("sortable");
  5358. }
  5359. @Override
  5360. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5361. }
  5362. @Override
  5363. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5364. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  5365. List<Column<?, T>> columns = getVisibleColumns();
  5366. for (FlyweightCell cell : attachedCells) {
  5367. StaticSection.StaticCell metadata = gridRow
  5368. .getCell(columns.get(cell.getColumn()));
  5369. /*
  5370. * If the cell contains widgets that are not currently attached
  5371. * then attach them now.
  5372. */
  5373. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  5374. final Widget widget = metadata.getWidget();
  5375. if (widget != null && !widget.isAttached()) {
  5376. getGrid().attachWidget(metadata.getWidget(),
  5377. cell.getElement());
  5378. }
  5379. }
  5380. }
  5381. }
  5382. @Override
  5383. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5384. if (section.getRowCount() > row.getRow()) {
  5385. StaticSection.StaticRow<?> gridRow = section
  5386. .getRow(row.getRow());
  5387. List<Column<?, T>> columns = getVisibleColumns();
  5388. for (FlyweightCell cell : cellsToDetach) {
  5389. StaticSection.StaticCell metadata = gridRow
  5390. .getCell(columns.get(cell.getColumn()));
  5391. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  5392. && metadata.getWidget() != null
  5393. && metadata.getWidget().isAttached()) {
  5394. getGrid().detachWidget(metadata.getWidget());
  5395. }
  5396. }
  5397. }
  5398. }
  5399. protected Grid getGrid() {
  5400. return section.grid;
  5401. }
  5402. @Override
  5403. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5404. }
  5405. };
  5406. /**
  5407. * Creates a new instance.
  5408. */
  5409. public Grid() {
  5410. initWidget(escalator);
  5411. getElement().setTabIndex(0);
  5412. cellFocusHandler = new CellFocusHandler();
  5413. setStylePrimaryName(STYLE_NAME);
  5414. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  5415. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  5416. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  5417. header.setGrid(this);
  5418. HeaderRow defaultRow = header.appendRow();
  5419. header.setDefaultRow(defaultRow);
  5420. footer.setGrid(this);
  5421. editor.setGrid(this);
  5422. setSelectionMode(SelectionMode.SINGLE);
  5423. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  5424. escalator.addScrollHandler(new ScrollHandler() {
  5425. @Override
  5426. public void onScroll(ScrollEvent event) {
  5427. fireEvent(new ScrollEvent());
  5428. }
  5429. });
  5430. escalator.addRowVisibilityChangeHandler(
  5431. new RowVisibilityChangeHandler() {
  5432. @Override
  5433. public void onRowVisibilityChange(
  5434. RowVisibilityChangeEvent event) {
  5435. if (dataSource != null && dataSource.size() != 0) {
  5436. dataSource.ensureAvailability(
  5437. event.getFirstVisibleRow(),
  5438. event.getVisibleRowCount());
  5439. }
  5440. }
  5441. });
  5442. // Default action on SelectionEvents. Refresh the body so changed
  5443. // become visible.
  5444. addSelectionHandler(new SelectionHandler<T>() {
  5445. @Override
  5446. public void onSelect(SelectionEvent<T> event) {
  5447. refreshBody();
  5448. }
  5449. });
  5450. // Sink header events and key events
  5451. sinkEvents(getHeader().getConsumedEvents());
  5452. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  5453. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  5454. BrowserEvents.MOUSEDOWN, BrowserEvents.CLICK));
  5455. // Make ENTER and SHIFT+ENTER in the header perform sorting
  5456. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  5457. @Override
  5458. public void onKeyUp(GridKeyUpEvent event) {
  5459. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  5460. return;
  5461. }
  5462. if (getHeader().getRow(event.getFocusedCell().getRowIndex())
  5463. .isDefault()) {
  5464. // Only sort for enter on the default header
  5465. sorter.sort(event.getFocusedCell().getColumn(),
  5466. event.isShiftKeyDown());
  5467. }
  5468. }
  5469. });
  5470. browserEventHandlers.addAll(Arrays.asList(
  5471. // Opening, closing and navigating in the editor
  5472. new EditorEventHandler(),
  5473. // Keyboard and click handlers, Escalator events
  5474. new SuperEventHandler(),
  5475. // Column reordering via header drag&drop
  5476. new HeaderCellDragStartHandler(),
  5477. // Column sorting via header click
  5478. new HeaderDefaultRowEventHandler(),
  5479. // Invoking event-aware renderers
  5480. new RendererEventHandler(),
  5481. // Moving cell focus by keyboard or mouse
  5482. new CellFocusEventHandler()));
  5483. }
  5484. @Override
  5485. public boolean isEnabled() {
  5486. return enabled;
  5487. }
  5488. @Override
  5489. public void setEnabled(boolean enabled) {
  5490. if (enabled == this.enabled) {
  5491. return;
  5492. }
  5493. this.enabled = enabled;
  5494. getElement().setTabIndex(enabled ? 0 : -1);
  5495. // Editor save and cancel buttons need to be disabled.
  5496. boolean editorOpen = editor.getState() != State.INACTIVE;
  5497. if (editorOpen) {
  5498. editor.setGridEnabled(enabled);
  5499. }
  5500. sidebar.setEnabled(enabled);
  5501. getEscalator().setScrollLocked(Direction.VERTICAL,
  5502. !enabled || editorOpen);
  5503. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  5504. fireEvent(new GridEnabledEvent(enabled));
  5505. }
  5506. /**
  5507. * Sets the column resize mode to use. The default mode is
  5508. * {@link ColumnResizeMode.ANIMATED}.
  5509. *
  5510. * @param mode
  5511. * a ColumnResizeMode value
  5512. * @since 7.7.5
  5513. */
  5514. public void setColumnResizeMode(ColumnResizeMode mode) {
  5515. columnResizeMode = mode;
  5516. }
  5517. /**
  5518. * Returns the current column resize mode. The default mode is
  5519. * {@link ColumnResizeMode.ANIMATED}.
  5520. *
  5521. * @return a ColumnResizeMode value
  5522. *
  5523. * @since 7.7.5
  5524. */
  5525. public ColumnResizeMode getColumnResizeMode() {
  5526. return columnResizeMode;
  5527. }
  5528. @Override
  5529. public void setStylePrimaryName(String style) {
  5530. super.setStylePrimaryName(style);
  5531. escalator.setStylePrimaryName(style);
  5532. editor.setStylePrimaryName(style);
  5533. sidebar.setStylePrimaryName(style + "-sidebar");
  5534. sidebar.addStyleName("v-contextmenu");
  5535. String rowStyle = getStylePrimaryName() + "-row";
  5536. rowHasDataStyleName = rowStyle + "-has-data";
  5537. rowSelectedStyleName = rowStyle + "-selected";
  5538. rowStripeStyleName = rowStyle + "-stripe";
  5539. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  5540. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  5541. if (isAttached()) {
  5542. refreshHeader();
  5543. refreshBody();
  5544. refreshFooter();
  5545. }
  5546. }
  5547. /**
  5548. * Creates the escalator updater used to update the header rows in this
  5549. * grid. The updater is invoked when header rows or columns are added or
  5550. * removed, or the content of existing header cells is changed.
  5551. *
  5552. * @return the new header updater instance
  5553. *
  5554. * @see GridHeader
  5555. * @see Grid#getHeader()
  5556. */
  5557. protected EscalatorUpdater createHeaderUpdater() {
  5558. return new StaticSectionUpdater(header, escalator.getHeader());
  5559. }
  5560. /**
  5561. * Creates the escalator updater used to update the body rows in this grid.
  5562. * The updater is invoked when body rows or columns are added or removed,
  5563. * the content of body cells is changed, or the body is scrolled to expose
  5564. * previously hidden content.
  5565. *
  5566. * @return the new body updater instance
  5567. */
  5568. protected EscalatorUpdater createBodyUpdater() {
  5569. return new BodyUpdater();
  5570. }
  5571. /**
  5572. * Creates the escalator updater used to update the footer rows in this
  5573. * grid. The updater is invoked when header rows or columns are added or
  5574. * removed, or the content of existing header cells is changed.
  5575. *
  5576. * @return the new footer updater instance
  5577. *
  5578. * @see GridFooter
  5579. * @see #getFooter()
  5580. */
  5581. protected EscalatorUpdater createFooterUpdater() {
  5582. return new StaticSectionUpdater(footer, escalator.getFooter());
  5583. }
  5584. /**
  5585. * Refreshes header or footer rows on demand
  5586. *
  5587. * @param rows
  5588. * The row container
  5589. * @param firstRowIsVisible
  5590. * is the first row visible
  5591. * @param isHeader
  5592. * <code>true</code> if we refreshing the header, else assumed
  5593. * the footer
  5594. */
  5595. private void refreshRowContainer(RowContainer rows,
  5596. StaticSection<?> section) {
  5597. // Add or Remove rows on demand
  5598. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  5599. if (rowDiff > 0) {
  5600. rows.insertRows(0, rowDiff);
  5601. } else if (rowDiff < 0) {
  5602. rows.removeRows(0, -rowDiff);
  5603. }
  5604. // Refresh all the rows
  5605. if (rows.getRowCount() > 0) {
  5606. rows.refreshRows(0, rows.getRowCount());
  5607. }
  5608. }
  5609. /**
  5610. * Focus a body cell by row and column index.
  5611. *
  5612. * @param rowIndex
  5613. * index of row to focus
  5614. * @param columnIndexDOM
  5615. * index (excluding hidden columns) of cell to focus
  5616. */
  5617. void focusCell(int rowIndex, int columnIndexDOM) {
  5618. final Range rowRange = Range.between(0, dataSource.size());
  5619. final Range columnRange = Range.between(0, getVisibleColumns().size());
  5620. assert rowRange.contains(
  5621. rowIndex) : "Illegal row index. Should be in range " + rowRange;
  5622. assert columnRange.contains(
  5623. columnIndexDOM) : "Illegal column index. Should be in range "
  5624. + columnRange;
  5625. if (rowRange.contains(rowIndex)
  5626. && columnRange.contains(columnIndexDOM)) {
  5627. cellFocusHandler.setCellFocus(rowIndex, columnIndexDOM,
  5628. escalator.getBody());
  5629. WidgetUtil.focus(getElement());
  5630. }
  5631. }
  5632. /**
  5633. * Refreshes all header rows
  5634. */
  5635. void refreshHeader() {
  5636. refreshRowContainer(escalator.getHeader(), header);
  5637. }
  5638. /**
  5639. * Refreshes all body rows
  5640. */
  5641. private void refreshBody() {
  5642. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  5643. }
  5644. /**
  5645. * Refreshes all footer rows
  5646. */
  5647. void refreshFooter() {
  5648. refreshRowContainer(escalator.getFooter(), footer);
  5649. }
  5650. /**
  5651. * Adds columns as the last columns in the grid.
  5652. *
  5653. * @param columns
  5654. * the columns to add
  5655. */
  5656. public void addColumns(Column<?, T>... columns) {
  5657. final int count = getColumnCount();
  5658. for (Column<?, T> column : columns) {
  5659. checkColumnIsValidToAdd(column, count);
  5660. }
  5661. addColumnsSkipSelectionColumnCheck(Arrays.asList(columns), count);
  5662. }
  5663. /**
  5664. * Checks the given column is valid to add at the given index.
  5665. */
  5666. private void checkColumnIsValidToAdd(Column<?, T> column, int index) {
  5667. if (column == this.selectionColumn) {
  5668. throw new IllegalArgumentException(
  5669. "The selection column may not be added manually");
  5670. } else if (this.selectionColumn != null && index == 0) {
  5671. throw new IllegalStateException("A column cannot be inserted "
  5672. + "before the selection column");
  5673. }
  5674. }
  5675. /**
  5676. * Adds a column as the last column in the grid.
  5677. *
  5678. * @param column
  5679. * the column to add
  5680. * @return given column
  5681. */
  5682. public <C extends Column<?, T>> C addColumn(C column) {
  5683. addColumn(column, getColumnCount());
  5684. return column;
  5685. }
  5686. /**
  5687. * Inserts a column into a specific position in the grid.
  5688. *
  5689. * @param index
  5690. * the index where the column should be inserted into
  5691. * @param column
  5692. * the column to add
  5693. * @return given column
  5694. *
  5695. * @throws IllegalStateException
  5696. * if Grid's current selection model renders a selection column,
  5697. * and {@code index} is 0.
  5698. */
  5699. public <C extends Column<?, T>> C addColumn(C column, int index) {
  5700. checkColumnIsValidToAdd(column, index);
  5701. addColumnsSkipSelectionColumnCheck(Collections.singleton(column), index);
  5702. return column;
  5703. }
  5704. private <C extends Column<?, T>> void addColumnsSkipSelectionColumnCheck(Collection<C> columnCollection, int index) {
  5705. int visibleNewColumns = 0;
  5706. int currentIndex = index;
  5707. //prevent updates of hiding toggles.
  5708. //it will be updated finally all at once.
  5709. this.columnHider.hidingColumn = true;
  5710. for (final Column<?, T> column : columnCollection) {
  5711. // Register column with grid
  5712. this.columns.add(currentIndex++, column);
  5713. this.footer.addColumn(column);
  5714. this.header.addColumn(column);
  5715. // Register this grid instance with the column
  5716. column.setGrid(this);
  5717. if (!column.isHidden()) {
  5718. visibleNewColumns++;
  5719. }
  5720. }
  5721. if (visibleNewColumns > 0) {
  5722. final ColumnConfiguration columnConfiguration = this.escalator.getColumnConfiguration();
  5723. columnConfiguration.insertColumns(index, visibleNewColumns);
  5724. }
  5725. for (final Column<?, T> column : columnCollection) {
  5726. // Reapply column width
  5727. column.reapplyWidth();
  5728. // Sink all renderer events
  5729. final Set<String> events = new HashSet<String>();
  5730. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  5731. if (column.isHidable()) {
  5732. this.columnHider.updateColumnHidable(column);
  5733. }
  5734. sinkEvents(events);
  5735. }
  5736. //now we do the update of the hiding toggles.
  5737. this.columnHider.hidingColumn = false;
  5738. this.columnHider.updateTogglesOrder();
  5739. refreshHeader();
  5740. this.header.updateColSpans();
  5741. this.footer.updateColSpans();
  5742. }
  5743. private void sinkEvents(Collection<String> events) {
  5744. assert events != null;
  5745. int eventsToSink = 0;
  5746. for (String typeName : events) {
  5747. int typeInt = Event.getTypeInt(typeName);
  5748. if (typeInt < 0) {
  5749. // Type not recognized by typeInt
  5750. sinkBitlessEvent(typeName);
  5751. } else {
  5752. eventsToSink |= typeInt;
  5753. }
  5754. }
  5755. if (eventsToSink > 0) {
  5756. sinkEvents(eventsToSink);
  5757. }
  5758. }
  5759. private Renderer<?> findRenderer(FlyweightCell cell) {
  5760. Column<?, T> column = getVisibleColumn(cell.getColumn());
  5761. assert column != null : "Could not find column at index:"
  5762. + cell.getColumn();
  5763. return column.getRenderer();
  5764. }
  5765. /**
  5766. * Removes a column from the grid.
  5767. *
  5768. * @param column
  5769. * the column to remove
  5770. */
  5771. public void removeColumn(Column<?, T> column) {
  5772. if (column != null && column.equals(selectionColumn)) {
  5773. throw new IllegalArgumentException(
  5774. "The selection column may not be removed manually.");
  5775. }
  5776. removeColumnSkipSelectionColumnCheck(column);
  5777. }
  5778. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  5779. int columnIndex = columns.indexOf(column);
  5780. // Remove from column configuration
  5781. int visibleColumnIndex = getVisibleColumns().indexOf(column);
  5782. if (visibleColumnIndex < 0) {
  5783. assert column.isHidden();
  5784. // Hidden columns are not included in Escalator
  5785. } else {
  5786. getEscalator().getColumnConfiguration()
  5787. .removeColumns(visibleColumnIndex, 1);
  5788. }
  5789. updateFrozenColumns();
  5790. header.removeColumn(column);
  5791. footer.removeColumn(column);
  5792. // de-register column with grid
  5793. ((Column<?, T>) column).setGrid(null);
  5794. columns.remove(columnIndex);
  5795. if (column.isHidable()) {
  5796. columnHider.removeColumnHidingToggle(column);
  5797. }
  5798. }
  5799. /**
  5800. * Returns the amount of columns in the grid.
  5801. * <p>
  5802. * <em>NOTE:</em> this includes the hidden columns in the count.
  5803. *
  5804. * @return The number of columns in the grid
  5805. */
  5806. public int getColumnCount() {
  5807. return columns.size();
  5808. }
  5809. /**
  5810. * Returns a list columns in the grid, including hidden columns.
  5811. * <p>
  5812. * For currently visible columns, use {@link #getVisibleColumns()}.
  5813. *
  5814. * @return A unmodifiable list of the columns in the grid
  5815. */
  5816. public List<Column<?, T>> getColumns() {
  5817. return Collections
  5818. .unmodifiableList(new ArrayList<Column<?, T>>(columns));
  5819. }
  5820. /**
  5821. * Returns a list of the currently visible columns in the grid.
  5822. * <p>
  5823. * No {@link Column#isHidden() hidden} columns included.
  5824. *
  5825. * @since 7.5.0
  5826. * @return A unmodifiable list of the currently visible columns in the grid
  5827. */
  5828. public List<Column<?, T>> getVisibleColumns() {
  5829. ArrayList<Column<?, T>> visible = new ArrayList<Column<?, T>>();
  5830. for (Column<?, T> c : columns) {
  5831. if (!c.isHidden()) {
  5832. visible.add(c);
  5833. }
  5834. }
  5835. return Collections.unmodifiableList(visible);
  5836. }
  5837. /**
  5838. * Returns a column by its index in the grid.
  5839. * <p>
  5840. * <em>NOTE:</em> The indexing includes hidden columns.
  5841. *
  5842. * @param index
  5843. * the index of the column
  5844. * @return The column in the given index
  5845. * @throws IllegalArgumentException
  5846. * if the column index does not exist in the grid
  5847. */
  5848. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  5849. if (index < 0 || index >= columns.size()) {
  5850. throw new IllegalStateException("Column not found.");
  5851. }
  5852. return columns.get(index);
  5853. }
  5854. private Column<?, T> getVisibleColumn(int columnIndexDOM)
  5855. throws IllegalArgumentException {
  5856. List<Column<?, T>> visibleColumns = getVisibleColumns();
  5857. if (columnIndexDOM < 0 || columnIndexDOM >= visibleColumns.size()) {
  5858. throw new IllegalStateException("Column not found.");
  5859. }
  5860. return visibleColumns.get(columnIndexDOM);
  5861. }
  5862. /**
  5863. * Returns the header section of this grid. The default header contains a
  5864. * single row displaying the column captions.
  5865. *
  5866. * @return the header
  5867. */
  5868. protected Header getHeader() {
  5869. return header;
  5870. }
  5871. /**
  5872. * Gets the header row at given index.
  5873. *
  5874. * @param rowIndex
  5875. * 0 based index for row. Counted from top to bottom
  5876. * @return header row at given index
  5877. * @throws IllegalArgumentException
  5878. * if no row exists at given index
  5879. */
  5880. public HeaderRow getHeaderRow(int rowIndex) {
  5881. return header.getRow(rowIndex);
  5882. }
  5883. /**
  5884. * Inserts a new row at the given position to the header section. Shifts the
  5885. * row currently at that position and any subsequent rows down (adds one to
  5886. * their indices).
  5887. *
  5888. * @param index
  5889. * the position at which to insert the row
  5890. * @return the new row
  5891. *
  5892. * @throws IllegalArgumentException
  5893. * if the index is less than 0 or greater than row count
  5894. * @see #appendHeaderRow()
  5895. * @see #prependHeaderRow()
  5896. * @see #removeHeaderRow(HeaderRow)
  5897. * @see #removeHeaderRow(int)
  5898. */
  5899. public HeaderRow addHeaderRowAt(int index) {
  5900. return header.addRowAt(index);
  5901. }
  5902. /**
  5903. * Adds a new row at the bottom of the header section.
  5904. *
  5905. * @return the new row
  5906. * @see #prependHeaderRow()
  5907. * @see #addHeaderRowAt(int)
  5908. * @see #removeHeaderRow(HeaderRow)
  5909. * @see #removeHeaderRow(int)
  5910. */
  5911. public HeaderRow appendHeaderRow() {
  5912. return header.appendRow();
  5913. }
  5914. /**
  5915. * Returns the current default row of the header section. The default row is
  5916. * a special header row providing a user interface for sorting columns.
  5917. * Setting a header caption for column updates cells in the default header.
  5918. *
  5919. * @return the default row or null if no default row set
  5920. */
  5921. public HeaderRow getDefaultHeaderRow() {
  5922. return header.getDefaultRow();
  5923. }
  5924. /**
  5925. * Gets the row count for the header section.
  5926. *
  5927. * @return row count
  5928. */
  5929. public int getHeaderRowCount() {
  5930. return header.getRowCount();
  5931. }
  5932. /**
  5933. * Adds a new row at the top of the header section.
  5934. *
  5935. * @return the new row
  5936. * @see #appendHeaderRow()
  5937. * @see #addHeaderRowAt(int)
  5938. * @see #removeHeaderRow(HeaderRow)
  5939. * @see #removeHeaderRow(int)
  5940. */
  5941. public HeaderRow prependHeaderRow() {
  5942. return header.prependRow();
  5943. }
  5944. /**
  5945. * Removes the given row from the header section.
  5946. *
  5947. * @param row
  5948. * the row to be removed
  5949. *
  5950. * @throws IllegalArgumentException
  5951. * if the row does not exist in this section
  5952. * @see #removeHeaderRow(int)
  5953. * @see #addHeaderRowAt(int)
  5954. * @see #appendHeaderRow()
  5955. * @see #prependHeaderRow()
  5956. */
  5957. public void removeHeaderRow(HeaderRow row) {
  5958. header.removeRow(row);
  5959. }
  5960. /**
  5961. * Removes the row at the given position from the header section.
  5962. *
  5963. * @param rowIndex
  5964. * the index of the row
  5965. *
  5966. * @throws IllegalArgumentException
  5967. * if no row exists at given index
  5968. * @see #removeHeaderRow(HeaderRow)
  5969. * @see #addHeaderRowAt(int)
  5970. * @see #appendHeaderRow()
  5971. * @see #prependHeaderRow()
  5972. */
  5973. public void removeHeaderRow(int rowIndex) {
  5974. header.removeRow(rowIndex);
  5975. }
  5976. /**
  5977. * Sets the default row of the header. The default row is a special header
  5978. * row providing a user interface for sorting columns.
  5979. * <p>
  5980. * Note: Setting the default header row will reset all cell contents to
  5981. * Column defaults.
  5982. *
  5983. * @param row
  5984. * the new default row, or null for no default row
  5985. *
  5986. * @throws IllegalArgumentException
  5987. * header does not contain the row
  5988. */
  5989. public void setDefaultHeaderRow(HeaderRow row) {
  5990. header.setDefaultRow(row);
  5991. }
  5992. /**
  5993. * Sets the visibility of the header section.
  5994. *
  5995. * @param visible
  5996. * true to show header section, false to hide
  5997. */
  5998. public void setHeaderVisible(boolean visible) {
  5999. header.setVisible(visible);
  6000. }
  6001. /**
  6002. * Returns the visibility of the header section.
  6003. *
  6004. * @return true if visible, false otherwise.
  6005. */
  6006. public boolean isHeaderVisible() {
  6007. return header.isVisible();
  6008. }
  6009. /* Grid Footers */
  6010. /**
  6011. * Returns the footer section of this grid. The default footer is empty.
  6012. *
  6013. * @return the footer
  6014. */
  6015. protected Footer getFooter() {
  6016. return footer;
  6017. }
  6018. /**
  6019. * Gets the footer row at given index.
  6020. *
  6021. * @param rowIndex
  6022. * 0 based index for row. Counted from top to bottom
  6023. * @return footer row at given index
  6024. * @throws IllegalArgumentException
  6025. * if no row exists at given index
  6026. */
  6027. public FooterRow getFooterRow(int rowIndex) {
  6028. return footer.getRow(rowIndex);
  6029. }
  6030. /**
  6031. * Inserts a new row at the given position to the footer section. Shifts the
  6032. * row currently at that position and any subsequent rows down (adds one to
  6033. * their indices).
  6034. *
  6035. * @param index
  6036. * the position at which to insert the row
  6037. * @return the new row
  6038. *
  6039. * @throws IllegalArgumentException
  6040. * if the index is less than 0 or greater than row count
  6041. * @see #appendFooterRow()
  6042. * @see #prependFooterRow()
  6043. * @see #removeFooterRow(FooterRow)
  6044. * @see #removeFooterRow(int)
  6045. */
  6046. public FooterRow addFooterRowAt(int index) {
  6047. return footer.addRowAt(index);
  6048. }
  6049. /**
  6050. * Adds a new row at the bottom of the footer section.
  6051. *
  6052. * @return the new row
  6053. * @see #prependFooterRow()
  6054. * @see #addFooterRowAt(int)
  6055. * @see #removeFooterRow(FooterRow)
  6056. * @see #removeFooterRow(int)
  6057. */
  6058. public FooterRow appendFooterRow() {
  6059. return footer.appendRow();
  6060. }
  6061. /**
  6062. * Gets the row count for the footer.
  6063. *
  6064. * @return row count
  6065. */
  6066. public int getFooterRowCount() {
  6067. return footer.getRowCount();
  6068. }
  6069. /**
  6070. * Adds a new row at the top of the footer section.
  6071. *
  6072. * @return the new row
  6073. * @see #appendFooterRow()
  6074. * @see #addFooterRowAt(int)
  6075. * @see #removeFooterRow(FooterRow)
  6076. * @see #removeFooterRow(int)
  6077. */
  6078. public FooterRow prependFooterRow() {
  6079. return footer.prependRow();
  6080. }
  6081. /**
  6082. * Removes the given row from the footer section.
  6083. *
  6084. * @param row
  6085. * the row to be removed
  6086. *
  6087. * @throws IllegalArgumentException
  6088. * if the row does not exist in this section
  6089. * @see #removeFooterRow(int)
  6090. * @see #addFooterRowAt(int)
  6091. * @see #appendFooterRow()
  6092. * @see #prependFooterRow()
  6093. */
  6094. public void removeFooterRow(FooterRow row) {
  6095. footer.removeRow(row);
  6096. }
  6097. /**
  6098. * Removes the row at the given position from the footer section.
  6099. *
  6100. * @param rowIndex
  6101. * the position of the row
  6102. *
  6103. * @throws IllegalArgumentException
  6104. * if no row exists at given index
  6105. * @see #removeFooterRow(FooterRow)
  6106. * @see #addFooterRowAt(int)
  6107. * @see #appendFooterRow()
  6108. * @see #prependFooterRow()
  6109. */
  6110. public void removeFooterRow(int rowIndex) {
  6111. footer.removeRow(rowIndex);
  6112. }
  6113. /**
  6114. * Sets the visibility of the footer section.
  6115. *
  6116. * @param visible
  6117. * true to show footer section, false to hide
  6118. */
  6119. public void setFooterVisible(boolean visible) {
  6120. footer.setVisible(visible);
  6121. }
  6122. /**
  6123. * Returns the visibility of the footer section.
  6124. *
  6125. * @return true if visible, false otherwise.
  6126. */
  6127. public boolean isFooterVisible() {
  6128. return footer.isVisible();
  6129. }
  6130. public Editor<T> getEditor() {
  6131. return editor;
  6132. }
  6133. /**
  6134. * Gets the {@link Escalator} used by this Grid instance.
  6135. *
  6136. * @return the escalator instance, never <code>null</code>
  6137. */
  6138. public Escalator getEscalator() {
  6139. return escalator;
  6140. }
  6141. /**
  6142. * {@inheritDoc}
  6143. * <p>
  6144. * <em>Note:</em> This method will change the widget's size in the browser
  6145. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  6146. *
  6147. * @see #setHeightMode(HeightMode)
  6148. */
  6149. @Override
  6150. public void setHeight(String height) {
  6151. escalator.setHeight(height);
  6152. }
  6153. @Override
  6154. public void setWidth(String width) {
  6155. escalator.setWidth(width);
  6156. }
  6157. /**
  6158. * Sets the data source used by this grid.
  6159. *
  6160. * @param dataSource
  6161. * the data source to use, not null
  6162. * @throws IllegalArgumentException
  6163. * if <code>dataSource</code> is <code>null</code>
  6164. */
  6165. public void setDataSource(final DataSource<T> dataSource)
  6166. throws IllegalArgumentException {
  6167. if (dataSource == null) {
  6168. throw new IllegalArgumentException("dataSource can't be null.");
  6169. }
  6170. selectionModel.reset();
  6171. if (this.dataSource != null) {
  6172. this.dataSource.addDataChangeHandler((DataChangeHandler) null);
  6173. }
  6174. this.dataSource = dataSource;
  6175. dataSource.addDataChangeHandler(new DataChangeHandler() {
  6176. @Override
  6177. public void dataUpdated(int firstIndex, int numberOfItems) {
  6178. escalator.getBody().refreshRows(firstIndex, numberOfItems);
  6179. }
  6180. @Override
  6181. public void dataRemoved(int firstIndex, int numberOfItems) {
  6182. escalator.getBody().removeRows(firstIndex, numberOfItems);
  6183. Range removed = Range.withLength(firstIndex, numberOfItems);
  6184. cellFocusHandler.rowsRemovedFromBody(removed);
  6185. }
  6186. @Override
  6187. public void dataAdded(int firstIndex, int numberOfItems) {
  6188. escalator.getBody().insertRows(firstIndex, numberOfItems);
  6189. Range added = Range.withLength(firstIndex, numberOfItems);
  6190. cellFocusHandler.rowsAddedToBody(added);
  6191. }
  6192. @Override
  6193. public void dataAvailable(int firstIndex, int numberOfItems) {
  6194. currentDataAvailable = Range.withLength(firstIndex,
  6195. numberOfItems);
  6196. fireEvent(new DataAvailableEvent(currentDataAvailable));
  6197. }
  6198. @Override
  6199. public void resetDataAndSize(int newSize) {
  6200. RowContainer body = escalator.getBody();
  6201. int oldSize = body.getRowCount();
  6202. // Hide all details.
  6203. Set<Integer> oldDetails = new HashSet<Integer>(visibleDetails);
  6204. for (int i : oldDetails) {
  6205. setDetailsVisible(i, false);
  6206. }
  6207. if (newSize > oldSize) {
  6208. body.insertRows(oldSize, newSize - oldSize);
  6209. cellFocusHandler.rowsAddedToBody(
  6210. Range.withLength(oldSize, newSize - oldSize));
  6211. } else if (newSize < oldSize) {
  6212. body.removeRows(newSize, oldSize - newSize);
  6213. cellFocusHandler.rowsRemovedFromBody(
  6214. Range.withLength(newSize, oldSize - newSize));
  6215. }
  6216. if (newSize > 0) {
  6217. Range visibleRowRange = escalator.getVisibleRowRange();
  6218. dataSource.ensureAvailability(visibleRowRange.getStart(),
  6219. visibleRowRange.length());
  6220. } else {
  6221. // We won't expect any data more data updates, so just make
  6222. // the bookkeeping happy
  6223. dataAvailable(0, 0);
  6224. }
  6225. assert body.getRowCount() == newSize;
  6226. }
  6227. });
  6228. int previousRowCount = escalator.getBody().getRowCount();
  6229. if (previousRowCount != 0) {
  6230. escalator.getBody().removeRows(0, previousRowCount);
  6231. }
  6232. setEscalatorSizeFromDataSource();
  6233. }
  6234. private void setEscalatorSizeFromDataSource() {
  6235. assert escalator.getBody().getRowCount() == 0;
  6236. int size = dataSource.size();
  6237. if (size == -1 && isAttached()) {
  6238. // Exact size is not yet known, start with some reasonable guess
  6239. // just to get an initial backend request going
  6240. size = getEscalator().getMaxVisibleRowCount();
  6241. }
  6242. if (size > 0) {
  6243. escalator.getBody().insertRows(0, size);
  6244. }
  6245. }
  6246. /**
  6247. * Gets the {@Link DataSource} for this Grid.
  6248. *
  6249. * @return the data source used by this grid
  6250. */
  6251. public DataSource<T> getDataSource() {
  6252. return dataSource;
  6253. }
  6254. /**
  6255. * Sets the number of frozen columns in this grid. Setting the count to 0
  6256. * means that no data columns will be frozen, but the built-in selection
  6257. * checkbox column will still be frozen if it's in use. Setting the count to
  6258. * -1 will also disable the selection column.
  6259. * <p>
  6260. * The default value is 0.
  6261. *
  6262. * @param numberOfColumns
  6263. * the number of columns that should be frozen
  6264. *
  6265. * @throws IllegalArgumentException
  6266. * if the column count is < -1 or > the number of visible
  6267. * columns
  6268. */
  6269. public void setFrozenColumnCount(int numberOfColumns) {
  6270. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  6271. throw new IllegalArgumentException(
  6272. "count must be between -1 and the current number of columns ("
  6273. + getColumnCount() + ")");
  6274. }
  6275. frozenColumnCount = numberOfColumns;
  6276. updateFrozenColumns();
  6277. }
  6278. private void updateFrozenColumns() {
  6279. escalator.getColumnConfiguration()
  6280. .setFrozenColumnCount(getVisibleFrozenColumnCount());
  6281. }
  6282. private int getVisibleFrozenColumnCount() {
  6283. int numberOfColumns = getFrozenColumnCount();
  6284. // for the escalator the hidden columns are not in the frozen column
  6285. // count, but for grid they are. thus need to convert the index
  6286. for (int i = 0; i < frozenColumnCount; i++) {
  6287. if (getColumn(i).isHidden()) {
  6288. numberOfColumns--;
  6289. }
  6290. }
  6291. if (numberOfColumns == -1) {
  6292. numberOfColumns = 0;
  6293. } else if (selectionColumn != null) {
  6294. numberOfColumns++;
  6295. }
  6296. return numberOfColumns;
  6297. }
  6298. /**
  6299. * Gets the number of frozen columns in this grid. 0 means that no data
  6300. * columns will be frozen, but the built-in selection checkbox column will
  6301. * still be frozen if it's in use. -1 means that not even the selection
  6302. * column is frozen.
  6303. * <p>
  6304. * <em>NOTE:</em> This includes {@link Column#isHidden() hidden columns} in
  6305. * the count.
  6306. *
  6307. * @return the number of frozen columns
  6308. */
  6309. public int getFrozenColumnCount() {
  6310. return frozenColumnCount;
  6311. }
  6312. public HandlerRegistration addRowVisibilityChangeHandler(
  6313. RowVisibilityChangeHandler handler) {
  6314. /*
  6315. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  6316. * concept is too abstract. e.g. the event needs to be re-sent when the
  6317. * widget is resized.
  6318. */
  6319. return escalator.addRowVisibilityChangeHandler(handler);
  6320. }
  6321. /**
  6322. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  6323. * <p>
  6324. * If the details for that row are visible, those will be taken into account
  6325. * as well.
  6326. *
  6327. * @param rowIndex
  6328. * zero-based index of the row to scroll to.
  6329. * @throws IllegalArgumentException
  6330. * if rowIndex is below zero, or above the maximum value
  6331. * supported by the data source.
  6332. */
  6333. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  6334. scrollToRow(rowIndex, ScrollDestination.ANY,
  6335. GridConstants.DEFAULT_PADDING);
  6336. }
  6337. /**
  6338. * Scrolls to a certain row, using user-specified scroll destination.
  6339. * <p>
  6340. * If the details for that row are visible, those will be taken into account
  6341. * as well.
  6342. *
  6343. * @param rowIndex
  6344. * zero-based index of the row to scroll to.
  6345. * @param destination
  6346. * desired destination placement of scrolled-to-row. See
  6347. * {@link ScrollDestination} for more information.
  6348. * @throws IllegalArgumentException
  6349. * if rowIndex is below zero, or above the maximum value
  6350. * supported by the data source.
  6351. */
  6352. public void scrollToRow(int rowIndex, ScrollDestination destination)
  6353. throws IllegalArgumentException {
  6354. scrollToRow(rowIndex, destination,
  6355. destination == ScrollDestination.MIDDLE ? 0
  6356. : GridConstants.DEFAULT_PADDING);
  6357. }
  6358. /**
  6359. * Scrolls to a certain row using only user-specified parameters.
  6360. * <p>
  6361. * If the details for that row are visible, those will be taken into account
  6362. * as well.
  6363. *
  6364. * @param rowIndex
  6365. * zero-based index of the row to scroll to.
  6366. * @param destination
  6367. * desired destination placement of scrolled-to-row. See
  6368. * {@link ScrollDestination} for more information.
  6369. * @param paddingPx
  6370. * number of pixels to overscroll. Behavior depends on
  6371. * destination.
  6372. * @throws IllegalArgumentException
  6373. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6374. * and padding is nonzero, because having a padding on a
  6375. * centered row is undefined behavior, or if rowIndex is below
  6376. * zero or above the row count of the data source.
  6377. */
  6378. private void scrollToRow(int rowIndex, ScrollDestination destination,
  6379. int paddingPx) throws IllegalArgumentException {
  6380. int maxsize = escalator.getBody().getRowCount() - 1;
  6381. if (rowIndex < 0) {
  6382. throw new IllegalArgumentException(
  6383. "Row index (" + rowIndex + ") is below zero!");
  6384. }
  6385. if (rowIndex > maxsize) {
  6386. throw new IllegalArgumentException("Row index (" + rowIndex
  6387. + ") is above maximum (" + maxsize + ")!");
  6388. }
  6389. escalator.scrollToRowAndSpacer(rowIndex, destination, paddingPx);
  6390. }
  6391. /**
  6392. * Scrolls to the beginning of the very first row.
  6393. */
  6394. public void scrollToStart() {
  6395. scrollToRow(0, ScrollDestination.START);
  6396. }
  6397. /**
  6398. * Scrolls to the end of the very last row.
  6399. */
  6400. public void scrollToEnd() {
  6401. scrollToRow(escalator.getBody().getRowCount() - 1,
  6402. ScrollDestination.END);
  6403. }
  6404. /**
  6405. * Sets the vertical scroll offset.
  6406. *
  6407. * @param px
  6408. * the number of pixels this grid should be scrolled down
  6409. */
  6410. public void setScrollTop(double px) {
  6411. escalator.setScrollTop(px);
  6412. }
  6413. /**
  6414. * Gets the vertical scroll offset.
  6415. *
  6416. * @return the number of pixels this grid is scrolled down
  6417. */
  6418. public double getScrollTop() {
  6419. return escalator.getScrollTop();
  6420. }
  6421. /**
  6422. * Sets the horizontal scroll offset.
  6423. *
  6424. * @since 7.5.0
  6425. * @param px
  6426. * the number of pixels this grid should be scrolled right
  6427. */
  6428. public void setScrollLeft(double px) {
  6429. escalator.setScrollLeft(px);
  6430. }
  6431. /**
  6432. * Gets the horizontal scroll offset.
  6433. *
  6434. * @return the number of pixels this grid is scrolled to the right
  6435. */
  6436. public double getScrollLeft() {
  6437. return escalator.getScrollLeft();
  6438. }
  6439. /**
  6440. * Returns the height of the scrollable area in pixels.
  6441. *
  6442. * @since 7.5.0
  6443. * @return the height of the scrollable area in pixels
  6444. */
  6445. public double getScrollHeight() {
  6446. return escalator.getScrollHeight();
  6447. }
  6448. /**
  6449. * Returns the width of the scrollable area in pixels.
  6450. *
  6451. * @since 7.5.0
  6452. * @return the width of the scrollable area in pixels.
  6453. */
  6454. public double getScrollWidth() {
  6455. return escalator.getScrollWidth();
  6456. }
  6457. private static final Logger getLogger() {
  6458. return Logger.getLogger(Grid.class.getName());
  6459. }
  6460. /**
  6461. * Sets the number of rows that should be visible in Grid's body, while
  6462. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6463. * <p>
  6464. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  6465. * remembered, and applied once the mode is applied.
  6466. *
  6467. * @param rows
  6468. * The height in terms of number of rows displayed in Grid's
  6469. * body. If Grid doesn't contain enough rows, white space is
  6470. * displayed instead.
  6471. * @throws IllegalArgumentException
  6472. * if {@code rows} is zero or less
  6473. * @throws IllegalArgumentException
  6474. * if {@code rows} is {@link Double#isInifinite(double)
  6475. * infinite}
  6476. * @throws IllegalArgumentException
  6477. * if {@code rows} is {@link Double#isNaN(double) NaN}
  6478. *
  6479. * @see #setHeightMode(HeightMode)
  6480. */
  6481. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6482. escalator.setHeightByRows(rows);
  6483. }
  6484. /**
  6485. * Gets the amount of rows in Grid's body that are shown, while
  6486. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6487. * <p>
  6488. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  6489. *
  6490. * @return the amount of rows that should be shown in Grid's body, while in
  6491. * {@link HeightMode#ROW}.
  6492. * @see #setHeightByRows(double)
  6493. */
  6494. public double getHeightByRows() {
  6495. return escalator.getHeightByRows();
  6496. }
  6497. /**
  6498. * Defines the mode in which the Grid widget's height is calculated.
  6499. * <p>
  6500. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  6501. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  6502. * <p>
  6503. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  6504. * will display as many rows as {@link #getHeightByRows()} defines.
  6505. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  6506. * will resize itself to still display the required amount of rows in its
  6507. * body. It also takes the horizontal scrollbar into account.
  6508. *
  6509. * @param heightMode
  6510. * the mode in to which Grid should be set
  6511. */
  6512. public void setHeightMode(HeightMode heightMode) {
  6513. /*
  6514. * This method is a workaround for the fact that Vaadin re-applies
  6515. * widget dimensions (height/width) on each state change event. The
  6516. * original design was to have setHeight an setHeightByRow be equals,
  6517. * and whichever was called the latest was considered in effect.
  6518. *
  6519. * But, because of Vaadin always calling setHeight on the widget, this
  6520. * approach doesn't work.
  6521. */
  6522. escalator.setHeightMode(heightMode);
  6523. }
  6524. /**
  6525. * Returns the current {@link HeightMode} the Grid is in.
  6526. * <p>
  6527. * Defaults to {@link HeightMode#CSS}.
  6528. *
  6529. * @return the current HeightMode
  6530. */
  6531. public HeightMode getHeightMode() {
  6532. return escalator.getHeightMode();
  6533. }
  6534. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  6535. Set<String> events = new HashSet<String>();
  6536. if (renderer instanceof ComplexRenderer) {
  6537. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  6538. .getConsumedEvents();
  6539. if (consumedEvents != null) {
  6540. events.addAll(consumedEvents);
  6541. }
  6542. }
  6543. return events;
  6544. }
  6545. @Override
  6546. public void onBrowserEvent(Event event) {
  6547. if (!isEnabled()) {
  6548. return;
  6549. }
  6550. String eventType = event.getType();
  6551. if (eventType.equals(BrowserEvents.FOCUS)
  6552. || eventType.equals(BrowserEvents.BLUR)) {
  6553. super.onBrowserEvent(event);
  6554. return;
  6555. }
  6556. EventTarget target = event.getEventTarget();
  6557. if (!Element.is(target) || isOrContainsInSpacer(Element.as(target))) {
  6558. return;
  6559. }
  6560. Element e = Element.as(target);
  6561. RowContainer container = escalator.findRowContainer(e);
  6562. Cell cell;
  6563. if (container == null) {
  6564. if (eventType.equals(BrowserEvents.KEYDOWN)
  6565. || eventType.equals(BrowserEvents.KEYUP)
  6566. || eventType.equals(BrowserEvents.KEYPRESS)) {
  6567. cell = cellFocusHandler.getFocusedCell();
  6568. container = cellFocusHandler.containerWithFocus;
  6569. } else {
  6570. // Click might be in an editor cell, should still map.
  6571. if (editor.editorOverlay != null
  6572. && editor.editorOverlay.isOrHasChild(e)) {
  6573. container = escalator.getBody();
  6574. int rowIndex = editor.getRow();
  6575. int colIndex = editor.getElementColumn(e);
  6576. if (colIndex < 0) {
  6577. // Click in editor, but not for any column.
  6578. return;
  6579. }
  6580. TableCellElement cellElement = container
  6581. .getRowElement(rowIndex).getCells()
  6582. .getItem(colIndex);
  6583. cell = new Cell(rowIndex, colIndex, cellElement);
  6584. } else {
  6585. if (escalator.getElement().isOrHasChild(e)) {
  6586. eventCell.set(new Cell(-1, -1, null), Section.BODY);
  6587. // Fire native events.
  6588. super.onBrowserEvent(event);
  6589. }
  6590. return;
  6591. }
  6592. }
  6593. } else {
  6594. cell = container.getCell(e);
  6595. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  6596. cellOnPrevMouseDown = cell;
  6597. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  6598. /*
  6599. * Chrome has an interesting idea on click targets (see
  6600. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  6601. * the mousedown target as the click target.
  6602. */
  6603. cell = cellOnPrevMouseDown;
  6604. }
  6605. }
  6606. assert cell != null : "received " + eventType
  6607. + "-event with a null cell target";
  6608. eventCell.set(cell, getSectionFromContainer(container));
  6609. GridEvent<T> gridEvent = new GridEvent<T>(event, eventCell);
  6610. for (GridEventHandler<T> handler : browserEventHandlers) {
  6611. handler.onEvent(gridEvent);
  6612. }
  6613. }
  6614. private Section getSectionFromContainer(RowContainer container) {
  6615. assert container != null : "RowContainer should not be null";
  6616. if (container == escalator.getBody()) {
  6617. return Section.BODY;
  6618. } else if (container == escalator.getFooter()) {
  6619. return Section.FOOTER;
  6620. } else if (container == escalator.getHeader()) {
  6621. return Section.HEADER;
  6622. }
  6623. assert false : "RowContainer was not header, footer or body.";
  6624. return null;
  6625. }
  6626. private boolean isOrContainsInSpacer(Node node) {
  6627. Node n = node;
  6628. while (n != null && n != getElement()) {
  6629. boolean isElement = Element.is(n);
  6630. if (isElement) {
  6631. String className = Element.as(n).getClassName();
  6632. if (className.contains(getStylePrimaryName() + "-spacer")) {
  6633. return true;
  6634. }
  6635. }
  6636. n = n.getParentNode();
  6637. }
  6638. return false;
  6639. }
  6640. private boolean isElementInChildWidget(Element e) {
  6641. Widget w = WidgetUtil.findWidget(e);
  6642. if (w == this) {
  6643. return false;
  6644. }
  6645. /*
  6646. * If e is directly inside this grid, but the grid is wrapped in a
  6647. * Composite, findWidget is not going to find this, only the wrapper.
  6648. * Thus we need to check its parents to see if we encounter this; if we
  6649. * don't, the found widget is actually a parent of this, so we should
  6650. * return false.
  6651. */
  6652. while (w != null && w != this) {
  6653. w = w.getParent();
  6654. }
  6655. return w != null;
  6656. }
  6657. private class EditorEventHandler implements GridEventHandler<T> {
  6658. @Override
  6659. public void onEvent(GridEvent<T> event) {
  6660. if (!isEditorEnabled()) {
  6661. return;
  6662. }
  6663. Widget widget;
  6664. if (editor.focusedColumnIndexDOM < 0) {
  6665. widget = null;
  6666. } else {
  6667. widget = editor.getWidget(
  6668. getVisibleColumn(editor.focusedColumnIndexDOM));
  6669. }
  6670. EditorDomEvent<T> editorEvent = new EditorDomEvent<T>(
  6671. event.getDomEvent(), event.getCell(), widget);
  6672. event.setHandled(
  6673. getEditor().getEventHandler().handleEvent(editorEvent));
  6674. }
  6675. };
  6676. private class SuperEventHandler implements GridEventHandler<T> {
  6677. @Override
  6678. public void onEvent(GridEvent<T> event) {
  6679. if (event.isHandled()) {
  6680. return;
  6681. }
  6682. Grid.super.onBrowserEvent(event.getDomEvent());
  6683. }
  6684. };
  6685. private abstract class AbstractGridEventHandler
  6686. implements GridEventHandler<T> {
  6687. @Override
  6688. public void onEvent(GridEvent<T> event) {
  6689. if (event.isHandled()) {
  6690. return;
  6691. }
  6692. event.setHandled(isElementInChildWidget(
  6693. Element.as(event.getDomEvent().getEventTarget())));
  6694. }
  6695. };
  6696. private class RendererEventHandler extends AbstractGridEventHandler {
  6697. @Override
  6698. public void onEvent(GridEvent<T> event) {
  6699. super.onEvent(event);
  6700. if (event.isHandled()) {
  6701. return;
  6702. }
  6703. if (!event.getCell().isBody()) {
  6704. return;
  6705. }
  6706. Column<?, T> gridColumn = event.getCell().getColumn();
  6707. boolean enterKey = event.getDomEvent().getType()
  6708. .equals(BrowserEvents.KEYDOWN)
  6709. && event.getDomEvent().getKeyCode() == KeyCodes.KEY_ENTER;
  6710. boolean doubleClick = event.getDomEvent().getType()
  6711. .equals(BrowserEvents.DBLCLICK);
  6712. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  6713. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  6714. .getRenderer();
  6715. if (cplxRenderer.getConsumedEvents()
  6716. .contains(event.getDomEvent().getType())) {
  6717. if (cplxRenderer.onBrowserEvent(event.getCell(),
  6718. event.getDomEvent())) {
  6719. event.setHandled(true);
  6720. }
  6721. }
  6722. // Calls onActivate if KeyDown and Enter or double click
  6723. if ((enterKey || doubleClick)
  6724. && cplxRenderer.onActivate(event.getCell())) {
  6725. event.setHandled(true);
  6726. }
  6727. }
  6728. }
  6729. };
  6730. private class CellFocusEventHandler extends AbstractGridEventHandler {
  6731. @Override
  6732. public void onEvent(GridEvent<T> event) {
  6733. super.onEvent(event);
  6734. if (event.isHandled()) {
  6735. return;
  6736. }
  6737. Collection<String> navigation = cellFocusHandler
  6738. .getNavigationEvents();
  6739. if (navigation.contains(event.getDomEvent().getType())) {
  6740. cellFocusHandler.handleNavigationEvent(event.getDomEvent(),
  6741. event.getCell());
  6742. }
  6743. }
  6744. };
  6745. private class HeaderCellDragStartHandler extends AbstractGridEventHandler {
  6746. @Override
  6747. public void onEvent(GridEvent<T> event) {
  6748. super.onEvent(event);
  6749. if (event.isHandled()) {
  6750. return;
  6751. }
  6752. if (!isColumnReorderingAllowed()) {
  6753. return;
  6754. }
  6755. if (!event.getCell().isHeader()) {
  6756. return;
  6757. }
  6758. if (event.getCell().getColumnIndex() < getFrozenColumnCount()) {
  6759. return;
  6760. }
  6761. if (event.getDomEvent().getTypeInt() == Event.ONMOUSEDOWN
  6762. && event.getDomEvent()
  6763. .getButton() == NativeEvent.BUTTON_LEFT
  6764. || event.getDomEvent().getTypeInt() == Event.ONTOUCHSTART) {
  6765. dndHandler.onDragStartOnDraggableElement(event.getDomEvent(),
  6766. headerCellDndCallback);
  6767. event.getDomEvent().preventDefault();
  6768. event.getDomEvent().stopPropagation();
  6769. event.setHandled(true);
  6770. }
  6771. }
  6772. };
  6773. private class HeaderDefaultRowEventHandler
  6774. extends AbstractGridEventHandler {
  6775. private Point rowEventTouchStartingPoint;
  6776. @Override
  6777. public void onEvent(GridEvent<T> event) {
  6778. super.onEvent(event);
  6779. if (event.isHandled()) {
  6780. return;
  6781. }
  6782. if (!event.getCell().isHeader()) {
  6783. return;
  6784. }
  6785. if (!getHeader().getRow(event.getCell().getRowIndex())
  6786. .isDefault()) {
  6787. return;
  6788. }
  6789. if (!event.getCell().getColumn().isSortable()) {
  6790. // Only handle sorting events if the column is sortable
  6791. return;
  6792. }
  6793. if (BrowserEvents.MOUSEDOWN.equals(event.getDomEvent().getType())
  6794. && event.getDomEvent().getShiftKey()) {
  6795. // Don't select text when shift clicking on a header.
  6796. event.getDomEvent().preventDefault();
  6797. }
  6798. if (BrowserEvents.TOUCHSTART
  6799. .equals(event.getDomEvent().getType())) {
  6800. if (event.getDomEvent().getTouches().length() > 1) {
  6801. return;
  6802. }
  6803. event.getDomEvent().preventDefault();
  6804. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  6805. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  6806. touch.getClientY());
  6807. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, true);
  6808. event.setHandled(true);
  6809. } else if (BrowserEvents.TOUCHMOVE
  6810. .equals(event.getDomEvent().getType())) {
  6811. if (event.getDomEvent().getTouches().length() > 1) {
  6812. return;
  6813. }
  6814. event.getDomEvent().preventDefault();
  6815. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  6816. double diffX = Math.abs(
  6817. touch.getClientX() - rowEventTouchStartingPoint.getX());
  6818. double diffY = Math.abs(
  6819. touch.getClientY() - rowEventTouchStartingPoint.getY());
  6820. // Cancel long tap if finger strays too far from
  6821. // starting point
  6822. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  6823. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  6824. sorter.cancelDelayedSort();
  6825. }
  6826. event.setHandled(true);
  6827. } else if (BrowserEvents.TOUCHEND
  6828. .equals(event.getDomEvent().getType())) {
  6829. if (event.getDomEvent().getTouches().length() > 1) {
  6830. return;
  6831. }
  6832. if (sorter.isDelayedSortScheduled()) {
  6833. // Not a long tap yet, perform single sort
  6834. sorter.cancelDelayedSort();
  6835. sorter.sort(event.getCell().getColumn(), false);
  6836. }
  6837. event.setHandled(true);
  6838. } else if (BrowserEvents.TOUCHCANCEL
  6839. .equals(event.getDomEvent().getType())) {
  6840. if (event.getDomEvent().getTouches().length() > 1) {
  6841. return;
  6842. }
  6843. sorter.cancelDelayedSort();
  6844. event.setHandled(true);
  6845. } else if (BrowserEvents.CLICK
  6846. .equals(event.getDomEvent().getType())) {
  6847. sorter.sort(event.getCell().getColumn(),
  6848. event.getDomEvent().getShiftKey());
  6849. }
  6850. }
  6851. };
  6852. @Override
  6853. @SuppressWarnings("deprecation")
  6854. public com.google.gwt.user.client.Element getSubPartElement(
  6855. String subPart) {
  6856. /*
  6857. * handles details[] (translated to spacer[] for Escalator), cell[],
  6858. * header[] and footer[]
  6859. */
  6860. // "#header[0][0]/DRAGhANDLE"
  6861. Element escalatorElement = escalator.getSubPartElement(
  6862. subPart.replaceFirst("^details\\[", "spacer["));
  6863. if (escalatorElement != null) {
  6864. int detailIdx = subPart.indexOf("/");
  6865. if (detailIdx > 0) {
  6866. String detail = subPart.substring(detailIdx + 1);
  6867. getLogger().severe("Looking up detail from index " + detailIdx
  6868. + " onward: \"" + detail + "\"");
  6869. if (detail.equalsIgnoreCase("content")) {
  6870. // XXX: Fix this to look up by class name!
  6871. return DOM.asOld(Element.as(escalatorElement.getChild(0)));
  6872. }
  6873. if (detail.equalsIgnoreCase("draghandle")) {
  6874. // XXX: Fix this to look up by class name!
  6875. return DOM.asOld(Element.as(escalatorElement.getChild(1)));
  6876. }
  6877. }
  6878. return DOM.asOld(escalatorElement);
  6879. }
  6880. SubPartArguments args = SubPartArguments.create(subPart);
  6881. Element editor = getSubPartElementEditor(args);
  6882. if (editor != null) {
  6883. return DOM.asOld(editor);
  6884. }
  6885. return null;
  6886. }
  6887. private Element getSubPartElementEditor(SubPartArguments args) {
  6888. if (!args.getType().equalsIgnoreCase("editor")
  6889. || editor.getState() != State.ACTIVE) {
  6890. return null;
  6891. }
  6892. if (args.getIndicesLength() == 0) {
  6893. return editor.editorOverlay;
  6894. } else if (args.getIndicesLength() == 1) {
  6895. int index = args.getIndex(0);
  6896. if (index >= columns.size()) {
  6897. return null;
  6898. }
  6899. escalator.scrollToColumn(index, ScrollDestination.ANY, 0);
  6900. Widget widget = editor.getWidget(columns.get(index));
  6901. if (widget != null) {
  6902. return widget.getElement();
  6903. }
  6904. // No widget for the column.
  6905. return null;
  6906. }
  6907. return null;
  6908. }
  6909. @Override
  6910. @SuppressWarnings("deprecation")
  6911. public String getSubPartName(
  6912. com.google.gwt.user.client.Element subElement) {
  6913. String escalatorStructureName = escalator.getSubPartName(subElement);
  6914. if (escalatorStructureName != null) {
  6915. return escalatorStructureName.replaceFirst("^spacer", "details");
  6916. }
  6917. String editorName = getSubPartNameEditor(subElement);
  6918. if (editorName != null) {
  6919. return editorName;
  6920. }
  6921. return null;
  6922. }
  6923. private String getSubPartNameEditor(Element subElement) {
  6924. if (editor.getState() != State.ACTIVE
  6925. || !editor.editorOverlay.isOrHasChild(subElement)) {
  6926. return null;
  6927. }
  6928. int i = 0;
  6929. for (Column<?, T> column : columns) {
  6930. if (editor.getWidget(column).getElement()
  6931. .isOrHasChild(subElement)) {
  6932. return "editor[" + i + "]";
  6933. }
  6934. ++i;
  6935. }
  6936. return "editor";
  6937. }
  6938. private void setSelectColumnRenderer(
  6939. final Renderer<Boolean> selectColumnRenderer) {
  6940. if (this.selectColumnRenderer == selectColumnRenderer) {
  6941. return;
  6942. }
  6943. if (this.selectColumnRenderer != null) {
  6944. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  6945. // End of Life for the old selection column renderer.
  6946. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  6947. }
  6948. // Clear field so frozen column logic in the remove method knows
  6949. // what to do
  6950. Column<?, T> colToRemove = selectionColumn;
  6951. selectionColumn = null;
  6952. removeColumnSkipSelectionColumnCheck(colToRemove);
  6953. cellFocusHandler.offsetRangeBy(-1);
  6954. }
  6955. this.selectColumnRenderer = selectColumnRenderer;
  6956. if (selectColumnRenderer != null) {
  6957. cellFocusHandler.offsetRangeBy(1);
  6958. selectionColumn = new SelectionColumn(selectColumnRenderer);
  6959. addColumnsSkipSelectionColumnCheck(Collections.singleton(selectionColumn), 0);
  6960. selectionColumn.setEnabled(isEnabled());
  6961. selectionColumn.initDone();
  6962. } else {
  6963. selectionColumn = null;
  6964. refreshBody();
  6965. }
  6966. updateFrozenColumns();
  6967. }
  6968. /**
  6969. * Sets the current selection model.
  6970. * <p>
  6971. * This function will call {@link SelectionModel#setGrid(Grid)}.
  6972. *
  6973. * @param selectionModel
  6974. * a selection model implementation.
  6975. * @throws IllegalArgumentException
  6976. * if selection model argument is null
  6977. */
  6978. public void setSelectionModel(SelectionModel<T> selectionModel) {
  6979. if (selectionModel == null) {
  6980. throw new IllegalArgumentException("Selection model can't be null");
  6981. }
  6982. if (this.selectionModel != null) {
  6983. // Detach selection model from Grid.
  6984. this.selectionModel.setGrid(null);
  6985. }
  6986. this.selectionModel = selectionModel;
  6987. selectionModel.setGrid(this);
  6988. setSelectColumnRenderer(
  6989. this.selectionModel.getSelectionColumnRenderer());
  6990. // Refresh rendered rows to update selection, if it has changed
  6991. refreshBody();
  6992. }
  6993. /**
  6994. * Gets a reference to the current selection model.
  6995. *
  6996. * @return the currently used SelectionModel instance.
  6997. */
  6998. public SelectionModel<T> getSelectionModel() {
  6999. return selectionModel;
  7000. }
  7001. /**
  7002. * Sets current selection mode.
  7003. * <p>
  7004. * This is a shorthand method for {@link Grid#setSelectionModel}.
  7005. *
  7006. * @param mode
  7007. * a selection mode value
  7008. * @see SelectionMode
  7009. */
  7010. public void setSelectionMode(SelectionMode mode) {
  7011. SelectionModel<T> model = mode.createModel();
  7012. setSelectionModel(model);
  7013. }
  7014. /**
  7015. * Test if a row is selected.
  7016. *
  7017. * @param row
  7018. * a row object
  7019. * @return true, if the current selection model considers the provided row
  7020. * object selected.
  7021. */
  7022. public boolean isSelected(T row) {
  7023. return selectionModel.isSelected(row);
  7024. }
  7025. /**
  7026. * Select a row using the current selection model.
  7027. * <p>
  7028. * Only selection models implementing {@link SelectionModel.Single} and
  7029. * {@link SelectionModel.Multi} are supported; for anything else, an
  7030. * exception will be thrown.
  7031. *
  7032. * @param row
  7033. * a row object
  7034. * @return <code>true</code> if the current selection changed
  7035. * @throws IllegalStateException
  7036. * if the current selection model is not an instance of
  7037. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7038. */
  7039. public boolean select(T row) {
  7040. if (selectionModel instanceof SelectionModel.Single<?>) {
  7041. return ((SelectionModel.Single<T>) selectionModel).select(row);
  7042. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  7043. return ((SelectionModel.Multi<T>) selectionModel)
  7044. .select(Collections.singleton(row));
  7045. } else {
  7046. throw new IllegalStateException("Unsupported selection model");
  7047. }
  7048. }
  7049. /**
  7050. * Deselect a row using the current selection model.
  7051. * <p>
  7052. * Only selection models implementing {@link SelectionModel.Single} and
  7053. * {@link SelectionModel.Multi} are supported; for anything else, an
  7054. * exception will be thrown.
  7055. *
  7056. * @param row
  7057. * a row object
  7058. * @return <code>true</code> if the current selection changed
  7059. * @throws IllegalStateException
  7060. * if the current selection model is not an instance of
  7061. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7062. */
  7063. public boolean deselect(T row) {
  7064. if (selectionModel instanceof SelectionModel.Single<?>) {
  7065. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  7066. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  7067. return ((SelectionModel.Multi<T>) selectionModel)
  7068. .deselect(Collections.singleton(row));
  7069. } else {
  7070. throw new IllegalStateException("Unsupported selection model");
  7071. }
  7072. }
  7073. /**
  7074. * Deselect all rows using the current selection model.
  7075. *
  7076. * @return <code>true</code> if the current selection changed
  7077. * @throws IllegalStateException
  7078. * if the current selection model is not an instance of
  7079. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7080. */
  7081. public boolean deselectAll() {
  7082. if (selectionModel instanceof SelectionModel.Single<?>) {
  7083. Single<T> single = (SelectionModel.Single<T>) selectionModel;
  7084. if (single.getSelectedRow() != null) {
  7085. return single.deselect(single.getSelectedRow());
  7086. } else {
  7087. return false;
  7088. }
  7089. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  7090. return ((SelectionModel.Multi<T>) selectionModel).deselectAll();
  7091. } else {
  7092. throw new IllegalStateException("Unsupported selection model");
  7093. }
  7094. }
  7095. /**
  7096. * Gets last selected row from the current SelectionModel.
  7097. * <p>
  7098. * Only selection models implementing {@link SelectionModel.Single} are
  7099. * valid for this method; for anything else, use the
  7100. * {@link Grid#getSelectedRows()} method.
  7101. *
  7102. * @return a selected row reference, or null, if no row is selected
  7103. * @throws IllegalStateException
  7104. * if the current selection model is not an instance of
  7105. * {@link SelectionModel.Single}
  7106. */
  7107. public T getSelectedRow() {
  7108. if (selectionModel instanceof SelectionModel.Single<?>) {
  7109. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  7110. } else {
  7111. throw new IllegalStateException(
  7112. "Unsupported selection model; can not get single selected row");
  7113. }
  7114. }
  7115. /**
  7116. * Gets currently selected rows from the current selection model.
  7117. *
  7118. * @return a non-null collection containing all currently selected rows.
  7119. */
  7120. public Collection<T> getSelectedRows() {
  7121. return selectionModel.getSelectedRows();
  7122. }
  7123. @Override
  7124. public HandlerRegistration addSelectionHandler(
  7125. final SelectionHandler<T> handler) {
  7126. return addHandler(handler, SelectionEvent.getType());
  7127. }
  7128. /**
  7129. * Sets the current sort order using the fluid Sort API. Read the
  7130. * documentation for {@link Sort} for more information.
  7131. *
  7132. * @param s
  7133. * a sort instance
  7134. */
  7135. public void sort(Sort s) {
  7136. setSortOrder(s.build());
  7137. }
  7138. /**
  7139. * Sorts the Grid data in ascending order along one column.
  7140. *
  7141. * @param column
  7142. * a grid column reference
  7143. */
  7144. public <C> void sort(Column<C, T> column) {
  7145. sort(column, SortDirection.ASCENDING);
  7146. }
  7147. /**
  7148. * Sorts the Grid data along one column.
  7149. *
  7150. * @param column
  7151. * a grid column reference
  7152. * @param direction
  7153. * a sort direction value
  7154. */
  7155. public <C> void sort(Column<C, T> column, SortDirection direction) {
  7156. sort(Sort.by(column, direction));
  7157. }
  7158. /**
  7159. * Sets the sort order to use. Setting this causes the Grid to re-sort
  7160. * itself.
  7161. *
  7162. * @param order
  7163. * a sort order list. If set to null, the sort order is cleared.
  7164. */
  7165. public void setSortOrder(List<SortOrder> order) {
  7166. setSortOrder(order, false);
  7167. }
  7168. /**
  7169. * Clears the sort order and indicators without re-sorting.
  7170. */
  7171. private void clearSortOrder() {
  7172. sortOrder.clear();
  7173. refreshHeader();
  7174. }
  7175. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  7176. if (order != sortOrder) {
  7177. sortOrder.clear();
  7178. if (order != null) {
  7179. sortOrder.addAll(order);
  7180. }
  7181. }
  7182. sort(userOriginated);
  7183. }
  7184. /**
  7185. * Get a copy of the current sort order array.
  7186. *
  7187. * @return a copy of the current sort order array
  7188. */
  7189. public List<SortOrder> getSortOrder() {
  7190. return Collections.unmodifiableList(sortOrder);
  7191. }
  7192. /**
  7193. * Finds the sorting order for this column
  7194. */
  7195. private SortOrder getSortOrder(Column<?, ?> column) {
  7196. for (SortOrder order : getSortOrder()) {
  7197. if (order.getColumn() == column) {
  7198. return order;
  7199. }
  7200. }
  7201. return null;
  7202. }
  7203. /**
  7204. * Register a GWT event handler for a sorting event. This handler gets
  7205. * called whenever this Grid needs its data source to provide data sorted in
  7206. * a specific order.
  7207. *
  7208. * @param handler
  7209. * a sort event handler
  7210. * @return the registration for the event
  7211. */
  7212. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  7213. return addHandler(handler, SortEvent.getType());
  7214. }
  7215. /**
  7216. * Register a GWT event handler for a select all event. This handler gets
  7217. * called whenever Grid needs all rows selected.
  7218. *
  7219. * @param handler
  7220. * a select all event handler
  7221. */
  7222. public HandlerRegistration addSelectAllHandler(
  7223. SelectAllHandler<T> handler) {
  7224. return addHandler(handler, SelectAllEvent.getType());
  7225. }
  7226. /**
  7227. * Register a GWT event handler for a data available event. This handler
  7228. * gets called whenever the {@link DataSource} for this Grid has new data
  7229. * available.
  7230. * <p>
  7231. * This handle will be fired with the current available data after
  7232. * registration is done.
  7233. *
  7234. * @param handler
  7235. * a data available event handler
  7236. * @return the registartion for the event
  7237. */
  7238. public HandlerRegistration addDataAvailableHandler(
  7239. final DataAvailableHandler handler) {
  7240. // Deferred call to handler with current row range
  7241. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7242. @Override
  7243. public void execute() {
  7244. if (!dataSource.isWaitingForData()) {
  7245. handler.onDataAvailable(
  7246. new DataAvailableEvent(currentDataAvailable));
  7247. }
  7248. }
  7249. });
  7250. return addHandler(handler, DataAvailableEvent.TYPE);
  7251. }
  7252. /**
  7253. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  7254. * fired when a KeyDown event occurs while cell focus is in the Body of this
  7255. * Grid.
  7256. *
  7257. * @param handler
  7258. * the key handler to register
  7259. * @return the registration for the event
  7260. */
  7261. public HandlerRegistration addBodyKeyDownHandler(
  7262. BodyKeyDownHandler handler) {
  7263. return addHandler(handler, GridKeyDownEvent.TYPE);
  7264. }
  7265. /**
  7266. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  7267. * fired when a KeyUp event occurs while cell focus is in the Body of this
  7268. * Grid.
  7269. *
  7270. * @param handler
  7271. * the key handler to register
  7272. * @return the registration for the event
  7273. */
  7274. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  7275. return addHandler(handler, GridKeyUpEvent.TYPE);
  7276. }
  7277. /**
  7278. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  7279. * is fired when a KeyPress event occurs while cell focus is in the Body of
  7280. * this Grid.
  7281. *
  7282. * @param handler
  7283. * the key handler to register
  7284. * @return the registration for the event
  7285. */
  7286. public HandlerRegistration addBodyKeyPressHandler(
  7287. BodyKeyPressHandler handler) {
  7288. return addHandler(handler, GridKeyPressEvent.TYPE);
  7289. }
  7290. /**
  7291. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  7292. * is fired when a KeyDown event occurs while cell focus is in the Header of
  7293. * this Grid.
  7294. *
  7295. * @param handler
  7296. * the key handler to register
  7297. * @return the registration for the event
  7298. */
  7299. public HandlerRegistration addHeaderKeyDownHandler(
  7300. HeaderKeyDownHandler handler) {
  7301. return addHandler(handler, GridKeyDownEvent.TYPE);
  7302. }
  7303. /**
  7304. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  7305. * fired when a KeyUp event occurs while cell focus is in the Header of this
  7306. * Grid.
  7307. *
  7308. * @param handler
  7309. * the key handler to register
  7310. * @return the registration for the event
  7311. */
  7312. public HandlerRegistration addHeaderKeyUpHandler(
  7313. HeaderKeyUpHandler handler) {
  7314. return addHandler(handler, GridKeyUpEvent.TYPE);
  7315. }
  7316. /**
  7317. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  7318. * is fired when a KeyPress event occurs while cell focus is in the Header
  7319. * of this Grid.
  7320. *
  7321. * @param handler
  7322. * the key handler to register
  7323. * @return the registration for the event
  7324. */
  7325. public HandlerRegistration addHeaderKeyPressHandler(
  7326. HeaderKeyPressHandler handler) {
  7327. return addHandler(handler, GridKeyPressEvent.TYPE);
  7328. }
  7329. /**
  7330. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  7331. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  7332. * this Grid.
  7333. *
  7334. * @param handler
  7335. * the key handler to register
  7336. * @return the registration for the event
  7337. */
  7338. public HandlerRegistration addFooterKeyDownHandler(
  7339. FooterKeyDownHandler handler) {
  7340. return addHandler(handler, GridKeyDownEvent.TYPE);
  7341. }
  7342. /**
  7343. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  7344. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  7345. * Grid.
  7346. *
  7347. * @param handler
  7348. * the key handler to register
  7349. * @return the registration for the event
  7350. */
  7351. public HandlerRegistration addFooterKeyUpHandler(
  7352. FooterKeyUpHandler handler) {
  7353. return addHandler(handler, GridKeyUpEvent.TYPE);
  7354. }
  7355. /**
  7356. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  7357. * is fired when a KeyPress event occurs while cell focus is in the Footer
  7358. * of this Grid.
  7359. *
  7360. * @param handler
  7361. * the key handler to register
  7362. * @return the registration for the event
  7363. */
  7364. public HandlerRegistration addFooterKeyPressHandler(
  7365. FooterKeyPressHandler handler) {
  7366. return addHandler(handler, GridKeyPressEvent.TYPE);
  7367. }
  7368. /**
  7369. * Register a BodyClickHandler to this Grid. The event for this handler is
  7370. * fired when a Click event occurs in the Body of this Grid.
  7371. *
  7372. * @param handler
  7373. * the click handler to register
  7374. * @return the registration for the event
  7375. */
  7376. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  7377. return addHandler(handler, GridClickEvent.TYPE);
  7378. }
  7379. /**
  7380. * Register a HeaderClickHandler to this Grid. The event for this handler is
  7381. * fired when a Click event occurs in the Header of this Grid.
  7382. *
  7383. * @param handler
  7384. * the click handler to register
  7385. * @return the registration for the event
  7386. */
  7387. public HandlerRegistration addHeaderClickHandler(
  7388. HeaderClickHandler handler) {
  7389. return addHandler(handler, GridClickEvent.TYPE);
  7390. }
  7391. /**
  7392. * Register a FooterClickHandler to this Grid. The event for this handler is
  7393. * fired when a Click event occurs in the Footer of this Grid.
  7394. *
  7395. * @param handler
  7396. * the click handler to register
  7397. * @return the registration for the event
  7398. */
  7399. public HandlerRegistration addFooterClickHandler(
  7400. FooterClickHandler handler) {
  7401. return addHandler(handler, GridClickEvent.TYPE);
  7402. }
  7403. /**
  7404. * Register a BodyDoubleClickHandler to this Grid. The event for this
  7405. * handler is fired when a double click event occurs in the Body of this
  7406. * Grid.
  7407. *
  7408. * @param handler
  7409. * the double click handler to register
  7410. * @return the registration for the event
  7411. */
  7412. public HandlerRegistration addBodyDoubleClickHandler(
  7413. BodyDoubleClickHandler handler) {
  7414. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7415. }
  7416. /**
  7417. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  7418. * handler is fired when a double click event occurs in the Header of this
  7419. * Grid.
  7420. *
  7421. * @param handler
  7422. * the double click handler to register
  7423. * @return the registration for the event
  7424. */
  7425. public HandlerRegistration addHeaderDoubleClickHandler(
  7426. HeaderDoubleClickHandler handler) {
  7427. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7428. }
  7429. /**
  7430. * Register a FooterDoubleClickHandler to this Grid. The event for this
  7431. * handler is fired when a double click event occurs in the Footer of this
  7432. * Grid.
  7433. *
  7434. * @param handler
  7435. * the double click handler to register
  7436. * @return the registration for the event
  7437. */
  7438. public HandlerRegistration addFooterDoubleClickHandler(
  7439. FooterDoubleClickHandler handler) {
  7440. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7441. }
  7442. /**
  7443. * Register a column reorder handler to this Grid. The event for this
  7444. * handler is fired when the Grid's columns are reordered.
  7445. *
  7446. * @since 7.5.0
  7447. * @param handler
  7448. * the handler for the event
  7449. * @return the registration for the event
  7450. */
  7451. public HandlerRegistration addColumnReorderHandler(
  7452. ColumnReorderHandler<T> handler) {
  7453. return addHandler(handler, ColumnReorderEvent.getType());
  7454. }
  7455. /**
  7456. * Register a column visibility change handler to this Grid. The event for
  7457. * this handler is fired when the Grid's columns change visibility.
  7458. *
  7459. * @since 7.5.0
  7460. * @param handler
  7461. * the handler for the event
  7462. * @return the registration for the event
  7463. */
  7464. public HandlerRegistration addColumnVisibilityChangeHandler(
  7465. ColumnVisibilityChangeHandler<T> handler) {
  7466. return addHandler(handler, ColumnVisibilityChangeEvent.getType());
  7467. }
  7468. /**
  7469. * Register a column resize handler to this Grid. The event for this handler
  7470. * is fired when the Grid's columns are resized.
  7471. *
  7472. * @since 7.6
  7473. * @param handler
  7474. * the handler for the event
  7475. * @return the registration for the event
  7476. */
  7477. public HandlerRegistration addColumnResizeHandler(
  7478. ColumnResizeHandler<T> handler) {
  7479. return addHandler(handler, ColumnResizeEvent.getType());
  7480. }
  7481. /**
  7482. * Register a enabled status change handler to this Grid. The event for this
  7483. * handler is fired when the Grid changes from disabled to enabled and
  7484. * vice-versa.
  7485. *
  7486. * @param handler
  7487. * the handler for the event
  7488. * @return the registration for the event
  7489. */
  7490. public HandlerRegistration addEnabledHandler(GridEnabledHandler handler) {
  7491. return addHandler(handler, GridEnabledEvent.TYPE);
  7492. }
  7493. public HandlerRegistration addRowHeightChangedHandler(
  7494. RowHeightChangedHandler handler) {
  7495. return escalator.addHandler(handler, RowHeightChangedEvent.TYPE);
  7496. }
  7497. /**
  7498. * Adds a spacer visibility changed handler to the underlying escalator.
  7499. *
  7500. * @param handler
  7501. * the handler to be called when a spacer's visibility changes
  7502. * @return the registration object with which the handler can be removed
  7503. * @since 7.7.13
  7504. */
  7505. public HandlerRegistration addSpacerVisibilityChangedHandler(
  7506. SpacerVisibilityChangedHandler handler) {
  7507. return escalator.addHandler(handler, SpacerVisibilityChangedEvent.TYPE);
  7508. }
  7509. /**
  7510. * Adds a low-level DOM event handler to this Grid. The handler is inserted
  7511. * into the given position in the list of handlers. The handlers are invoked
  7512. * in order. If the
  7513. * {@link GridEventHandler#onEvent(Event, EventCellReference) onEvent}
  7514. * method of a handler returns true, subsequent handlers are not invoked.
  7515. *
  7516. * @param index
  7517. * the index to insert the handler to
  7518. * @param handler
  7519. * the handler to add
  7520. */
  7521. public void addBrowserEventHandler(int index, GridEventHandler<T> handler) {
  7522. browserEventHandlers.add(index, handler);
  7523. }
  7524. /**
  7525. * Apply sorting to data source.
  7526. */
  7527. private void sort(boolean userOriginated) {
  7528. refreshHeader();
  7529. fireEvent(new SortEvent<T>(this,
  7530. Collections.unmodifiableList(sortOrder), userOriginated));
  7531. }
  7532. private int getLastVisibleRowIndex() {
  7533. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  7534. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  7535. Element lastRow;
  7536. do {
  7537. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  7538. } while (lastRow.getAbsoluteTop() > footerTop);
  7539. return lastRowIndex;
  7540. }
  7541. private int getFirstVisibleRowIndex() {
  7542. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  7543. int headerBottom = escalator.getHeader().getElement()
  7544. .getAbsoluteBottom();
  7545. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  7546. while (firstRow.getAbsoluteBottom() < headerBottom) {
  7547. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  7548. }
  7549. return firstRowIndex;
  7550. }
  7551. /**
  7552. * Adds a scroll handler to this grid.
  7553. *
  7554. * @param handler
  7555. * the scroll handler to add
  7556. * @return a handler registration for the registered scroll handler
  7557. */
  7558. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7559. return addHandler(handler, ScrollEvent.TYPE);
  7560. }
  7561. @Override
  7562. public boolean isWorkPending() {
  7563. return escalator.isWorkPending() || dataSource.isWaitingForData()
  7564. || autoColumnWidthsRecalculator.isScheduled()
  7565. || editor.isWorkPending();
  7566. }
  7567. /**
  7568. * Returns whether columns can be reordered with drag and drop.
  7569. *
  7570. * @since 7.5.0
  7571. * @return <code>true</code> if columns can be reordered, false otherwise
  7572. */
  7573. public boolean isColumnReorderingAllowed() {
  7574. return columnReorderingAllowed;
  7575. }
  7576. /**
  7577. * Sets whether column reordering with drag and drop is allowed or not.
  7578. *
  7579. * @since 7.5.0
  7580. * @param columnReorderingAllowed
  7581. * specifies whether column reordering is allowed
  7582. */
  7583. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  7584. this.columnReorderingAllowed = columnReorderingAllowed;
  7585. }
  7586. /**
  7587. * Sets a new column order for the grid. All columns which are not ordered
  7588. * here will remain in the order they were before as the last columns of
  7589. * grid.
  7590. *
  7591. * @param orderedColumns
  7592. * array of columns in wanted order
  7593. */
  7594. public void setColumnOrder(Column<?, T>... orderedColumns) {
  7595. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  7596. // Trigger ComplexRenderer.destroy for old content
  7597. conf.removeColumns(0, conf.getColumnCount());
  7598. List<Column<?, T>> newOrder = new ArrayList<Column<?, T>>();
  7599. if (selectionColumn != null) {
  7600. newOrder.add(selectionColumn);
  7601. }
  7602. int i = 0;
  7603. for (Column<?, T> column : orderedColumns) {
  7604. if (columns.contains(column)) {
  7605. newOrder.add(column);
  7606. ++i;
  7607. } else {
  7608. throw new IllegalArgumentException("Given column at index " + i
  7609. + " does not exist in Grid");
  7610. }
  7611. }
  7612. if (columns.size() != newOrder.size()) {
  7613. columns.removeAll(newOrder);
  7614. newOrder.addAll(columns);
  7615. }
  7616. columns = newOrder;
  7617. List<Column<?, T>> visibleColumns = getVisibleColumns();
  7618. // Do ComplexRenderer.init and render new content
  7619. conf.insertColumns(0, visibleColumns.size());
  7620. // Number of frozen columns should be kept same #16901
  7621. updateFrozenColumns();
  7622. // Update column widths.
  7623. for (Column<?, T> column : columns) {
  7624. column.reapplyWidth();
  7625. }
  7626. // Recalculate all the colspans
  7627. for (HeaderRow row : header.getRows()) {
  7628. row.calculateColspans();
  7629. }
  7630. for (FooterRow row : footer.getRows()) {
  7631. row.calculateColspans();
  7632. }
  7633. columnHider.updateTogglesOrder();
  7634. fireEvent(new ColumnReorderEvent<T>());
  7635. }
  7636. /**
  7637. * Sets the style generator that is used for generating styles for cells.
  7638. *
  7639. * @param cellStyleGenerator
  7640. * the cell style generator to set, or <code>null</code> to
  7641. * remove a previously set generator
  7642. */
  7643. public void setCellStyleGenerator(
  7644. CellStyleGenerator<T> cellStyleGenerator) {
  7645. this.cellStyleGenerator = cellStyleGenerator;
  7646. refreshBody();
  7647. }
  7648. /**
  7649. * Gets the style generator that is used for generating styles for cells.
  7650. *
  7651. * @return the cell style generator, or <code>null</code> if no generator is
  7652. * set
  7653. */
  7654. public CellStyleGenerator<T> getCellStyleGenerator() {
  7655. return cellStyleGenerator;
  7656. }
  7657. /**
  7658. * Sets the style generator that is used for generating styles for rows.
  7659. *
  7660. * @param rowStyleGenerator
  7661. * the row style generator to set, or <code>null</code> to remove
  7662. * a previously set generator
  7663. */
  7664. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  7665. this.rowStyleGenerator = rowStyleGenerator;
  7666. refreshBody();
  7667. }
  7668. /**
  7669. * Gets the style generator that is used for generating styles for rows.
  7670. *
  7671. * @return the row style generator, or <code>null</code> if no generator is
  7672. * set
  7673. */
  7674. public RowStyleGenerator<T> getRowStyleGenerator() {
  7675. return rowStyleGenerator;
  7676. }
  7677. private static void setCustomStyleName(Element element, String styleName) {
  7678. assert element != null;
  7679. String oldStyleName = element
  7680. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  7681. if (!SharedUtil.equals(oldStyleName, styleName)) {
  7682. if (oldStyleName != null && !oldStyleName.isEmpty()) {
  7683. element.removeClassName(oldStyleName);
  7684. }
  7685. if (styleName != null && !styleName.isEmpty()) {
  7686. element.addClassName(styleName);
  7687. }
  7688. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  7689. }
  7690. }
  7691. /**
  7692. * Opens the editor over the row with the given index.
  7693. *
  7694. * @param rowIndex
  7695. * the index of the row to be edited
  7696. *
  7697. * @throws IllegalStateException
  7698. * if the editor is not enabled
  7699. * @throws IllegalStateException
  7700. * if the editor is already in edit mode
  7701. */
  7702. public void editRow(int rowIndex) {
  7703. editor.editRow(rowIndex);
  7704. }
  7705. /**
  7706. * Returns whether the editor is currently open on some row.
  7707. *
  7708. * @return {@code true} if the editor is active, {@code false} otherwise.
  7709. */
  7710. public boolean isEditorActive() {
  7711. return editor.getState() != State.INACTIVE;
  7712. }
  7713. /**
  7714. * Saves any unsaved changes in the editor to the data source.
  7715. *
  7716. * @throws IllegalStateException
  7717. * if the editor is not enabled
  7718. * @throws IllegalStateException
  7719. * if the editor is not in edit mode
  7720. */
  7721. public void saveEditor() {
  7722. editor.save();
  7723. }
  7724. /**
  7725. * Cancels the currently active edit and hides the editor. Any changes that
  7726. * are not {@link #saveEditor() saved} are lost.
  7727. *
  7728. * @throws IllegalStateException
  7729. * if the editor is not enabled
  7730. * @throws IllegalStateException
  7731. * if the editor is not in edit mode
  7732. */
  7733. public void cancelEditor() {
  7734. editor.cancel();
  7735. }
  7736. /**
  7737. * Returns the handler responsible for binding data and editor widgets to
  7738. * the editor.
  7739. *
  7740. * @return the editor handler or null if not set
  7741. */
  7742. public EditorHandler<T> getEditorHandler() {
  7743. return editor.getHandler();
  7744. }
  7745. /**
  7746. * Sets the handler responsible for binding data and editor widgets to the
  7747. * editor.
  7748. *
  7749. * @param handler
  7750. * the new editor handler
  7751. *
  7752. * @throws IllegalStateException
  7753. * if the editor is currently in edit mode
  7754. */
  7755. public void setEditorHandler(EditorHandler<T> handler) {
  7756. editor.setHandler(handler);
  7757. }
  7758. /**
  7759. * Returns the enabled state of the editor.
  7760. *
  7761. * @return true if editing is enabled, false otherwise
  7762. */
  7763. public boolean isEditorEnabled() {
  7764. return editor.isEnabled();
  7765. }
  7766. /**
  7767. * Sets the enabled state of the editor.
  7768. *
  7769. * @param enabled
  7770. * true to enable editing, false to disable
  7771. *
  7772. * @throws IllegalStateException
  7773. * if in edit mode and trying to disable
  7774. * @throws IllegalStateException
  7775. * if the editor handler is not set
  7776. */
  7777. public void setEditorEnabled(boolean enabled) {
  7778. editor.setEnabled(enabled);
  7779. }
  7780. /**
  7781. * Returns the editor widget associated with the given column. If the editor
  7782. * is not active, returns null.
  7783. *
  7784. * @param column
  7785. * the column
  7786. * @return the widget if the editor is open, null otherwise
  7787. */
  7788. public Widget getEditorWidget(Column<?, T> column) {
  7789. return editor.getWidget(column);
  7790. }
  7791. /**
  7792. * Sets the caption on the save button in the Grid editor.
  7793. *
  7794. * @param saveCaption
  7795. * the caption to set
  7796. * @throws IllegalArgumentException
  7797. * if {@code saveCaption} is {@code null}
  7798. */
  7799. public void setEditorSaveCaption(String saveCaption)
  7800. throws IllegalArgumentException {
  7801. editor.setSaveCaption(saveCaption);
  7802. }
  7803. /**
  7804. * Gets the current caption on the save button in the Grid editor.
  7805. *
  7806. * @return the current caption on the save button
  7807. */
  7808. public String getEditorSaveCaption() {
  7809. return editor.getSaveCaption();
  7810. }
  7811. /**
  7812. * Sets the caption on the cancel button in the Grid editor.
  7813. *
  7814. * @param cancelCaption
  7815. * the caption to set
  7816. * @throws IllegalArgumentException
  7817. * if {@code cancelCaption} is {@code null}
  7818. */
  7819. public void setEditorCancelCaption(String cancelCaption)
  7820. throws IllegalArgumentException {
  7821. editor.setCancelCaption(cancelCaption);
  7822. }
  7823. /**
  7824. * Gets the caption on the cancel button in the Grid editor.
  7825. *
  7826. * @return the current caption on the cancel button
  7827. */
  7828. public String getEditorCancelCaption() {
  7829. return editor.getCancelCaption();
  7830. }
  7831. @Override
  7832. protected void onAttach() {
  7833. super.onAttach();
  7834. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  7835. setEscalatorSizeFromDataSource();
  7836. }
  7837. // Grid was just attached to DOM. Column widths should be calculated.
  7838. recalculateColumnWidths();
  7839. for (int row : reattachVisibleDetails) {
  7840. setDetailsVisible(row, true);
  7841. }
  7842. reattachVisibleDetails.clear();
  7843. }
  7844. @Override
  7845. protected void onDetach() {
  7846. Set<Integer> details = new HashSet<Integer>(visibleDetails);
  7847. reattachVisibleDetails.clear();
  7848. reattachVisibleDetails.addAll(details);
  7849. for (int row : details) {
  7850. setDetailsVisible(row, false);
  7851. }
  7852. super.onDetach();
  7853. }
  7854. @Override
  7855. public void onResize() {
  7856. super.onResize();
  7857. /*
  7858. * Delay calculation to be deferred so Escalator can do it's magic.
  7859. */
  7860. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7861. @Override
  7862. public void execute() {
  7863. if (escalator
  7864. .getInnerWidth() != autoColumnWidthsRecalculator.lastCalculatedInnerWidth) {
  7865. recalculateColumnWidths();
  7866. }
  7867. // Vertical resizing could make editor positioning invalid so it
  7868. // needs to be recalculated on resize
  7869. if (isEditorActive()) {
  7870. editor.updateVerticalScrollPosition();
  7871. }
  7872. // if there is a resize, we need to refresh the body to avoid an
  7873. // off-by-one error which occurs when the user scrolls all the
  7874. // way to the bottom.
  7875. refreshBody();
  7876. }
  7877. });
  7878. }
  7879. /**
  7880. * Grid does not support adding Widgets this way.
  7881. * <p>
  7882. * This method is implemented only because removing widgets from Grid (added
  7883. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7884. *
  7885. * @param w
  7886. * irrelevant
  7887. * @throws UnsupportedOperationException
  7888. * always
  7889. */
  7890. @Override
  7891. @Deprecated
  7892. public void add(Widget w) {
  7893. throw new UnsupportedOperationException(
  7894. "Cannot add widgets to Grid with this method");
  7895. }
  7896. /**
  7897. * Grid does not support clearing Widgets this way.
  7898. * <p>
  7899. * This method is implemented only because removing widgets from Grid (added
  7900. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7901. *
  7902. * @throws UnsupportedOperationException
  7903. * always
  7904. */
  7905. @Override
  7906. @Deprecated
  7907. public void clear() {
  7908. throw new UnsupportedOperationException(
  7909. "Cannot clear widgets from Grid this way");
  7910. }
  7911. /**
  7912. * Grid does not support iterating through Widgets this way.
  7913. * <p>
  7914. * This method is implemented only because removing widgets from Grid (added
  7915. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7916. *
  7917. * @return never
  7918. * @throws UnsupportedOperationException
  7919. * always
  7920. */
  7921. @Override
  7922. @Deprecated
  7923. public Iterator<Widget> iterator() {
  7924. throw new UnsupportedOperationException(
  7925. "Cannot iterate through widgets in Grid this way");
  7926. }
  7927. /**
  7928. * Grid does not support removing Widgets this way.
  7929. * <p>
  7930. * This method is implemented only because removing widgets from Grid (added
  7931. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7932. *
  7933. * @return always <code>false</code>
  7934. */
  7935. @Override
  7936. @Deprecated
  7937. public boolean remove(Widget w) {
  7938. /*
  7939. * This is the method that is the sole reason to have Grid implement
  7940. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  7941. * corresponding Widget will call removeFromParent() on itself. GWT will
  7942. * check there that its parent (i.e. Grid) implements HasWidgets, and
  7943. * will call this remove(Widget) method.
  7944. *
  7945. * tl;dr: all this song and dance to make sure GWT's sanity checks
  7946. * aren't triggered, even though they effectively do nothing interesting
  7947. * from Grid's perspective.
  7948. */
  7949. return false;
  7950. }
  7951. /**
  7952. * Accesses the package private method Widget#setParent()
  7953. *
  7954. * @param widget
  7955. * The widget to access
  7956. * @param parent
  7957. * The parent to set
  7958. */
  7959. private static native final void setParent(Widget widget, Grid<?> parent)
  7960. /*-{
  7961. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  7962. }-*/;
  7963. private static native final void onAttach(Widget widget)
  7964. /*-{
  7965. widget.@Widget::onAttach()();
  7966. }-*/;
  7967. private static native final void onDetach(Widget widget)
  7968. /*-{
  7969. widget.@Widget::onDetach()();
  7970. }-*/;
  7971. @Override
  7972. protected void doAttachChildren() {
  7973. if (sidebar.getParent() == this) {
  7974. onAttach(sidebar);
  7975. }
  7976. }
  7977. @Override
  7978. protected void doDetachChildren() {
  7979. if (sidebar.getParent() == this) {
  7980. onDetach(sidebar);
  7981. }
  7982. }
  7983. private void attachWidget(Widget w, Element parent) {
  7984. assert w.getParent() == null;
  7985. parent.appendChild(w.getElement());
  7986. setParent(w, this);
  7987. }
  7988. private void detachWidget(Widget w) {
  7989. assert w.getParent() == this;
  7990. setParent(w, null);
  7991. w.getElement().removeFromParent();
  7992. }
  7993. /**
  7994. * Resets all cached pixel sizes and reads new values from the DOM. This
  7995. * methods should be used e.g. when styles affecting the dimensions of
  7996. * elements in this grid have been changed.
  7997. */
  7998. public void resetSizesFromDom() {
  7999. getEscalator().resetSizesFromDom();
  8000. }
  8001. /**
  8002. * Sets a new details generator for row details.
  8003. * <p>
  8004. * The currently opened row details will be re-rendered.
  8005. *
  8006. * @since 7.5.0
  8007. * @param detailsGenerator
  8008. * the details generator to set
  8009. * @throws IllegalArgumentException
  8010. * if detailsGenerator is <code>null</code>;
  8011. */
  8012. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  8013. throws IllegalArgumentException {
  8014. if (detailsGenerator == null) {
  8015. throw new IllegalArgumentException(
  8016. "Details generator may not be null");
  8017. }
  8018. for (Integer index : visibleDetails) {
  8019. setDetailsVisible(index, false);
  8020. }
  8021. this.detailsGenerator = detailsGenerator;
  8022. // this will refresh all visible spacers
  8023. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  8024. }
  8025. /**
  8026. * Gets the current details generator for row details.
  8027. *
  8028. * @since 7.5.0
  8029. * @return the detailsGenerator the current details generator
  8030. */
  8031. public DetailsGenerator getDetailsGenerator() {
  8032. return detailsGenerator;
  8033. }
  8034. /**
  8035. * Shows or hides the details for a specific row.
  8036. * <p>
  8037. * This method does nothing if trying to set show already-visible details,
  8038. * or hide already-hidden details.
  8039. *
  8040. * @since 7.5.0
  8041. * @param rowIndex
  8042. * the index of the affected row
  8043. * @param visible
  8044. * <code>true</code> to show the details, or <code>false</code>
  8045. * to hide them
  8046. * @see #isDetailsVisible(int)
  8047. */
  8048. public void setDetailsVisible(int rowIndex, boolean visible) {
  8049. if (DetailsGenerator.NULL.equals(detailsGenerator)) {
  8050. return;
  8051. }
  8052. Integer rowIndexInteger = Integer.valueOf(rowIndex);
  8053. /*
  8054. * We want to prevent opening a details row twice, so any subsequent
  8055. * openings (or closings) of details is a NOOP.
  8056. *
  8057. * When a details row is opened, it is given an arbitrary height
  8058. * (because Escalator requires a height upon opening). Only when it's
  8059. * opened, Escalator will ask the generator to generate a widget, which
  8060. * we then can measure. When measured, we correct the initial height by
  8061. * the original height.
  8062. *
  8063. * Without this check, we would override the measured height, and revert
  8064. * back to the initial, arbitrary, height which would most probably be
  8065. * wrong.
  8066. *
  8067. * see GridSpacerUpdater.init for implementation details.
  8068. */
  8069. boolean isVisible = isDetailsVisible(rowIndex);
  8070. if (visible && !isVisible) {
  8071. escalator.getBody().setSpacer(rowIndex, DETAILS_ROW_INITIAL_HEIGHT);
  8072. visibleDetails.add(rowIndexInteger);
  8073. }
  8074. else if (!visible && isVisible) {
  8075. escalator.getBody().setSpacer(rowIndex, -1);
  8076. visibleDetails.remove(rowIndexInteger);
  8077. }
  8078. }
  8079. /**
  8080. * Check whether the details for a row is visible or not.
  8081. *
  8082. * @since 7.5.0
  8083. * @param rowIndex
  8084. * the index of the row for which to check details
  8085. * @return <code>true</code> if the details for the given row is visible
  8086. * @see #setDetailsVisible(int, boolean)
  8087. */
  8088. public boolean isDetailsVisible(int rowIndex) {
  8089. return visibleDetails.contains(Integer.valueOf(rowIndex));
  8090. }
  8091. /**
  8092. * Update details row height.
  8093. *
  8094. * @since 7.7.11
  8095. * @param rowIndex
  8096. * the index of the row for which to update details height
  8097. * @param height
  8098. * new height of the details row
  8099. */
  8100. public void setDetailsHeight(int rowIndex, double height) {
  8101. escalator.getBody().setSpacer(rowIndex, height);
  8102. }
  8103. /**
  8104. * Requests that the column widths should be recalculated.
  8105. * <p>
  8106. * The actual recalculation is not necessarily done immediately so you
  8107. * cannot rely on the columns being the correct width after the call
  8108. * returns.
  8109. *
  8110. * @since 7.4.1
  8111. */
  8112. public void recalculateColumnWidths() {
  8113. autoColumnWidthsRecalculator.schedule();
  8114. }
  8115. /**
  8116. * Gets the customizable menu bar that is by default used for toggling
  8117. * column hidability. The application developer is allowed to add their
  8118. * custom items to the end of the menu, but should try to avoid modifying
  8119. * the items in the beginning of the menu that control the column hiding if
  8120. * any columns are marked as hidable. A toggle for opening the menu will be
  8121. * displayed whenever the menu contains at least one item.
  8122. *
  8123. * @since 7.5.0
  8124. * @return the menu bar
  8125. */
  8126. public MenuBar getSidebarMenu() {
  8127. return sidebar.menuBar;
  8128. }
  8129. /**
  8130. * Tests whether the sidebar menu is currently open.
  8131. *
  8132. * @since 7.5.0
  8133. * @see #getSidebarMenu()
  8134. * @return <code>true</code> if the sidebar is open; <code>false</code> if
  8135. * it is closed
  8136. */
  8137. public boolean isSidebarOpen() {
  8138. return sidebar.isOpen();
  8139. }
  8140. /**
  8141. * Sets whether the sidebar menu is open.
  8142. *
  8143. *
  8144. * @since 7.5.0
  8145. * @see #getSidebarMenu()
  8146. * @see #isSidebarOpen()
  8147. * @param sidebarOpen
  8148. * <code>true</code> to open the sidebar; <code>false</code> to
  8149. * close it
  8150. */
  8151. public void setSidebarOpen(boolean sidebarOpen) {
  8152. if (sidebarOpen) {
  8153. sidebar.open();
  8154. } else {
  8155. sidebar.close();
  8156. }
  8157. }
  8158. @Override
  8159. public int getTabIndex() {
  8160. return FocusUtil.getTabIndex(this);
  8161. }
  8162. @Override
  8163. public void setAccessKey(char key) {
  8164. FocusUtil.setAccessKey(this, key);
  8165. }
  8166. @Override
  8167. public void setFocus(boolean focused) {
  8168. FocusUtil.setFocus(this, focused);
  8169. }
  8170. @Override
  8171. public void setTabIndex(int index) {
  8172. FocusUtil.setTabIndex(this, index);
  8173. }
  8174. @Override
  8175. public void focus() {
  8176. setFocus(true);
  8177. }
  8178. /**
  8179. * Sets the buffered editor mode.
  8180. *
  8181. * @since 7.6
  8182. * @param editorBuffered
  8183. * {@code true} to enable buffered editor, {@code false} to
  8184. * disable it
  8185. */
  8186. public void setEditorBuffered(boolean editorBuffered) {
  8187. editor.setBuffered(editorBuffered);
  8188. }
  8189. /**
  8190. * Gets the buffered editor mode.
  8191. *
  8192. * @since 7.6
  8193. * @return <code>true</code> if buffered editor is enabled,
  8194. * <code>false</code> otherwise
  8195. */
  8196. public boolean isEditorBuffered() {
  8197. return editor.isBuffered();
  8198. }
  8199. /**
  8200. * Returns the {@link EventCellReference} for the latest event fired from
  8201. * this Grid.
  8202. * <p>
  8203. * Note: This cell reference will be updated when firing the next event.
  8204. *
  8205. * @since 7.5
  8206. * @return event cell reference
  8207. */
  8208. public EventCellReference<T> getEventCell() {
  8209. return eventCell;
  8210. }
  8211. /**
  8212. * Returns a CellReference for the cell to which the given element belongs
  8213. * to.
  8214. *
  8215. * @since 7.6
  8216. * @param element
  8217. * Element to find from the cell's content.
  8218. * @return CellReference or <code>null</code> if cell was not found.
  8219. */
  8220. public CellReference<T> getCellReference(Element element) {
  8221. RowContainer container = getEscalator().findRowContainer(element);
  8222. if (container != null) {
  8223. Cell cell = container.getCell(element);
  8224. if (cell != null) {
  8225. EventCellReference<T> cellRef = new EventCellReference<T>(this);
  8226. cellRef.set(cell, getSectionFromContainer(container));
  8227. return cellRef;
  8228. }
  8229. }
  8230. return null;
  8231. }
  8232. /**
  8233. * Checks if selection by the user is allowed in the grid.
  8234. *
  8235. * @return <code>true</code> if selection by the user is allowed by the
  8236. * selection model (the default), <code>false</code> otherwise
  8237. * @since 7.7.7
  8238. */
  8239. public boolean isUserSelectionAllowed() {
  8240. if (!(getSelectionModel() instanceof HasUserSelectionAllowed)) {
  8241. // Selection model does not support toggling user selection allowed
  8242. // - old default is to always allow selection
  8243. return true;
  8244. }
  8245. return ((HasUserSelectionAllowed) getSelectionModel())
  8246. .isUserSelectionAllowed();
  8247. }
  8248. }