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

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