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

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