Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Grid.java 350KB

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