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

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