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

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