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

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