Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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