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

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