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

Grid.java 327KB

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