You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Grid.java 309KB

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