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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.v7.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Type;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.EnumSet;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.LinkedHashMap;
  29. import java.util.LinkedHashSet;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Locale;
  33. import java.util.Map;
  34. import java.util.Map.Entry;
  35. import java.util.Set;
  36. import java.util.logging.Level;
  37. import java.util.logging.Logger;
  38. import org.jsoup.nodes.Attributes;
  39. import org.jsoup.nodes.Element;
  40. import org.jsoup.select.Elements;
  41. import com.vaadin.event.ContextClickEvent;
  42. import com.vaadin.event.FieldEvents.BlurEvent;
  43. import com.vaadin.event.FieldEvents.BlurListener;
  44. import com.vaadin.event.FieldEvents.FocusEvent;
  45. import com.vaadin.event.FieldEvents.FocusListener;
  46. import com.vaadin.server.AbstractClientConnector;
  47. import com.vaadin.server.AbstractExtension;
  48. import com.vaadin.server.EncodeResult;
  49. import com.vaadin.server.ErrorMessage;
  50. import com.vaadin.server.Extension;
  51. import com.vaadin.server.JsonCodec;
  52. import com.vaadin.server.KeyMapper;
  53. import com.vaadin.server.VaadinSession;
  54. import com.vaadin.shared.MouseEventDetails;
  55. import com.vaadin.shared.Registration;
  56. import com.vaadin.shared.data.sort.SortDirection;
  57. import com.vaadin.shared.util.SharedUtil;
  58. import com.vaadin.ui.AbstractComponent;
  59. import com.vaadin.ui.Component;
  60. import com.vaadin.ui.Component.Focusable;
  61. import com.vaadin.ui.ConnectorTracker;
  62. import com.vaadin.ui.SelectiveRenderer;
  63. import com.vaadin.ui.UI;
  64. import com.vaadin.ui.declarative.DesignAttributeHandler;
  65. import com.vaadin.ui.declarative.DesignContext;
  66. import com.vaadin.ui.declarative.DesignException;
  67. import com.vaadin.ui.declarative.DesignFormatter;
  68. import com.vaadin.util.ReflectTools;
  69. import com.vaadin.v7.data.Container;
  70. import com.vaadin.v7.data.Container.Indexed;
  71. import com.vaadin.v7.data.Container.ItemSetChangeEvent;
  72. import com.vaadin.v7.data.Container.ItemSetChangeListener;
  73. import com.vaadin.v7.data.Container.ItemSetChangeNotifier;
  74. import com.vaadin.v7.data.Container.PropertySetChangeEvent;
  75. import com.vaadin.v7.data.Container.PropertySetChangeListener;
  76. import com.vaadin.v7.data.Container.PropertySetChangeNotifier;
  77. import com.vaadin.v7.data.Container.Sortable;
  78. import com.vaadin.v7.data.Item;
  79. import com.vaadin.v7.data.Property;
  80. import com.vaadin.v7.data.Validator.InvalidValueException;
  81. import com.vaadin.v7.data.fieldgroup.DefaultFieldGroupFieldFactory;
  82. import com.vaadin.v7.data.fieldgroup.FieldGroup;
  83. import com.vaadin.v7.data.fieldgroup.FieldGroup.CommitException;
  84. import com.vaadin.v7.data.fieldgroup.FieldGroupFieldFactory;
  85. import com.vaadin.v7.data.sort.Sort;
  86. import com.vaadin.v7.data.sort.SortOrder;
  87. import com.vaadin.v7.data.util.IndexedContainer;
  88. import com.vaadin.v7.data.util.converter.Converter;
  89. import com.vaadin.v7.data.util.converter.ConverterUtil;
  90. import com.vaadin.v7.event.FieldEvents.BlurNotifier;
  91. import com.vaadin.v7.event.FieldEvents.FocusNotifier;
  92. import com.vaadin.v7.event.ItemClickEvent;
  93. import com.vaadin.v7.event.ItemClickEvent.ItemClickListener;
  94. import com.vaadin.v7.event.ItemClickEvent.ItemClickNotifier;
  95. import com.vaadin.v7.event.SelectionEvent;
  96. import com.vaadin.v7.event.SelectionEvent.SelectionListener;
  97. import com.vaadin.v7.event.SelectionEvent.SelectionNotifier;
  98. import com.vaadin.v7.event.SortEvent;
  99. import com.vaadin.v7.event.SortEvent.SortListener;
  100. import com.vaadin.v7.event.SortEvent.SortNotifier;
  101. import com.vaadin.v7.server.communication.data.DataGenerator;
  102. import com.vaadin.v7.server.communication.data.RpcDataProviderExtension;
  103. import com.vaadin.v7.shared.ui.grid.ColumnResizeMode;
  104. import com.vaadin.v7.shared.ui.grid.EditorClientRpc;
  105. import com.vaadin.v7.shared.ui.grid.EditorServerRpc;
  106. import com.vaadin.v7.shared.ui.grid.GridClientRpc;
  107. import com.vaadin.v7.shared.ui.grid.GridColumnState;
  108. import com.vaadin.v7.shared.ui.grid.GridConstants;
  109. import com.vaadin.v7.shared.ui.grid.GridConstants.Section;
  110. import com.vaadin.v7.shared.ui.grid.GridServerRpc;
  111. import com.vaadin.v7.shared.ui.grid.GridState;
  112. import com.vaadin.v7.shared.ui.grid.GridStaticCellType;
  113. import com.vaadin.v7.shared.ui.grid.GridStaticSectionState;
  114. import com.vaadin.v7.shared.ui.grid.GridStaticSectionState.CellState;
  115. import com.vaadin.v7.shared.ui.grid.GridStaticSectionState.RowState;
  116. import com.vaadin.v7.shared.ui.grid.HeightMode;
  117. import com.vaadin.v7.shared.ui.grid.ScrollDestination;
  118. import com.vaadin.v7.shared.ui.grid.selection.MultiSelectionModelServerRpc;
  119. import com.vaadin.v7.shared.ui.grid.selection.MultiSelectionModelState;
  120. import com.vaadin.v7.shared.ui.grid.selection.SingleSelectionModelServerRpc;
  121. import com.vaadin.v7.shared.ui.grid.selection.SingleSelectionModelState;
  122. import com.vaadin.v7.ui.Grid.SelectionModel.HasUserSelectionAllowed;
  123. import com.vaadin.v7.ui.renderers.HtmlRenderer;
  124. import com.vaadin.v7.ui.renderers.Renderer;
  125. import com.vaadin.v7.ui.renderers.TextRenderer;
  126. import elemental.json.Json;
  127. import elemental.json.JsonObject;
  128. import elemental.json.JsonValue;
  129. /**
  130. * A grid component for displaying tabular data.
  131. * <p>
  132. * Grid is always bound to a {@link Container.Indexed}, but is not a
  133. * {@code Container} of any kind in of itself. The contents of the given
  134. * Container is displayed with the help of {@link Renderer Renderers}.
  135. *
  136. * <h3 id="grid-headers-and-footers">Headers and Footers</h3>
  137. * <p>
  138. *
  139. *
  140. * <h3 id="grid-converters-and-renderers">Converters and Renderers</h3>
  141. * <p>
  142. * Each column has its own {@link Renderer} that displays data into something
  143. * that can be displayed in the browser. That data is first converted with a
  144. * {@link Converter} into something that the Renderer can process. This can also
  145. * be an implicit step - if a column has a simple data type, like a String, no
  146. * explicit assignment is needed.
  147. * <p>
  148. * Usually a renderer takes some kind of object, and converts it into a
  149. * HTML-formatted string.
  150. * <p>
  151. * <code><pre>
  152. * Grid grid = new Grid(myContainer);
  153. * Column column = grid.getColumn(STRING_DATE_PROPERTY);
  154. * column.setConverter(new StringToDateConverter());
  155. * column.setRenderer(new MyColorfulDateRenderer());
  156. * </pre></code>
  157. *
  158. * <h3 id="grid-lazyloading">Lazy Loading</h3>
  159. * <p>
  160. * The data is accessed as it is needed by Grid and not any sooner. In other
  161. * words, if the given Container is huge, but only the first few rows are
  162. * displayed to the user, only those (and a few more, for caching purposes) are
  163. * accessed.
  164. *
  165. * <h3 id="grid-selection-modes-and-models">Selection Modes and Models</h3>
  166. * <p>
  167. * Grid supports three selection <em>{@link SelectionMode modes}</em> (single,
  168. * multi, none), and comes bundled with one <em>{@link SelectionModel
  169. * model}</em> for each of the modes. The distinction between a selection mode
  170. * and selection model is as follows: a <em>mode</em> essentially says whether
  171. * you can have one, many or no rows selected. The model, however, has the
  172. * behavioral details of each. A single selection model may require that the
  173. * user deselects one row before selecting another one. A variant of a
  174. * multiselect might have a configurable maximum of rows that may be selected.
  175. * And so on.
  176. * <p>
  177. * <code><pre>
  178. * Grid grid = new Grid(myContainer);
  179. *
  180. * // uses the bundled SingleSelectionModel class
  181. * grid.setSelectionMode(SelectionMode.SINGLE);
  182. *
  183. * // changes the behavior to a custom selection model
  184. * grid.setSelectionModel(new MyTwoSelectionModel());
  185. * </pre></code>
  186. *
  187. * @since 7.4
  188. * @author Vaadin Ltd
  189. *
  190. * @deprecated As of 8.0 replaced by {@link com.vaadin.ui.Grid} based on the new
  191. * data binding API
  192. */
  193. @Deprecated
  194. public class Grid extends AbstractComponent
  195. implements SelectionNotifier, SortNotifier, SelectiveRenderer,
  196. ItemClickNotifier, Focusable, FocusNotifier, BlurNotifier {
  197. /**
  198. * An event listener for column visibility change events in the Grid.
  199. *
  200. * @since 7.5.0
  201. */
  202. @Deprecated
  203. public interface ColumnVisibilityChangeListener extends Serializable {
  204. /**
  205. * Called when a column has become hidden or unhidden.
  206. *
  207. * @param event
  208. */
  209. void columnVisibilityChanged(ColumnVisibilityChangeEvent event);
  210. }
  211. /**
  212. * An event that is fired when a column's visibility changes.
  213. *
  214. * @since 7.5.0
  215. */
  216. @Deprecated
  217. public static class ColumnVisibilityChangeEvent extends Component.Event {
  218. private final Column column;
  219. private final boolean userOriginated;
  220. private final boolean hidden;
  221. /**
  222. * Constructor for a column visibility change event.
  223. *
  224. * @param source
  225. * the grid from which this event originates
  226. * @param column
  227. * the column that changed its visibility
  228. * @param hidden
  229. * <code>true</code> if the column was hidden,
  230. * <code>false</code> if it became visible
  231. * @param isUserOriginated
  232. * <code>true</code> iff the event was triggered by an UI
  233. * interaction
  234. */
  235. public ColumnVisibilityChangeEvent(Grid source, Column column,
  236. boolean hidden, boolean isUserOriginated) {
  237. super(source);
  238. this.column = column;
  239. this.hidden = hidden;
  240. userOriginated = isUserOriginated;
  241. }
  242. /**
  243. * Gets the column that became hidden or visible.
  244. *
  245. * @return the column that became hidden or visible.
  246. * @see Column#isHidden()
  247. */
  248. public Column getColumn() {
  249. return column;
  250. }
  251. /**
  252. * Was the column set hidden or visible.
  253. *
  254. * @return <code>true</code> if the column was hidden <code>false</code>
  255. * if it was set visible
  256. */
  257. public boolean isHidden() {
  258. return hidden;
  259. }
  260. /**
  261. * Returns <code>true</code> if the column reorder was done by the user,
  262. * <code>false</code> if not and it was triggered by server side code.
  263. *
  264. * @return <code>true</code> if event is a result of user interaction
  265. */
  266. public boolean isUserOriginated() {
  267. return userOriginated;
  268. }
  269. }
  270. /**
  271. * A callback interface for generating details for a particular row in Grid.
  272. *
  273. * @since 7.5.0
  274. * @author Vaadin Ltd
  275. * @see DetailsGenerator#NULL
  276. */
  277. @Deprecated
  278. public interface DetailsGenerator extends Serializable {
  279. /** A details generator that provides no details */
  280. public DetailsGenerator NULL = new DetailsGenerator() {
  281. @Override
  282. public Component getDetails(RowReference rowReference) {
  283. return null;
  284. }
  285. };
  286. /**
  287. * This method is called for whenever a details row needs to be shown on
  288. * the client. Grid removes all of its references to details components
  289. * when they are no longer displayed on the client-side and will
  290. * re-request once needed again.
  291. * <p>
  292. * <em>Note:</em> If a component gets generated, it may not be manually
  293. * attached anywhere. The same details component can not be displayed
  294. * for multiple different rows.
  295. *
  296. * @param rowReference
  297. * the reference for the row for which to generate details
  298. * @return the details for the given row, or <code>null</code> to leave
  299. * the details empty.
  300. */
  301. Component getDetails(RowReference rowReference);
  302. }
  303. /**
  304. * A class that manages details components by calling
  305. * {@link DetailsGenerator} as needed. Details components are attached by
  306. * this class when the {@link RpcDataProviderExtension} is sending data to
  307. * the client. Details components are detached and forgotten when client
  308. * informs that it has dropped the corresponding item.
  309. *
  310. * @since 7.6.1
  311. */
  312. @Deprecated
  313. public static final class DetailComponentManager
  314. extends AbstractGridExtension implements DataGenerator {
  315. /**
  316. * The user-defined details generator.
  317. *
  318. * @see #setDetailsGenerator(DetailsGenerator)
  319. */
  320. private DetailsGenerator detailsGenerator;
  321. /**
  322. * This map represents all details that are currently visible on the
  323. * client. Details components get destroyed once they scroll out of
  324. * view.
  325. */
  326. private final Map<Object, Component> itemIdToDetailsComponent = new HashMap<Object, Component>();
  327. /**
  328. * Set of item ids that got <code>null</code> from DetailsGenerator when
  329. * {@link DetailsGenerator#getDetails(RowReference)} was called.
  330. */
  331. private final Set<Object> emptyDetails = new HashSet<Object>();
  332. /**
  333. * Set of item IDs for all open details rows. Contains even the ones
  334. * that are not currently visible on the client.
  335. */
  336. private final Set<Object> openDetails = new HashSet<Object>();
  337. public DetailComponentManager(Grid grid) {
  338. this(grid, DetailsGenerator.NULL);
  339. }
  340. public DetailComponentManager(Grid grid,
  341. DetailsGenerator detailsGenerator) {
  342. super(grid);
  343. setDetailsGenerator(detailsGenerator);
  344. }
  345. /**
  346. * Creates a details component with the help of the user-defined
  347. * {@link DetailsGenerator}.
  348. * <p>
  349. * This method attaches created components to the parent {@link Grid}.
  350. *
  351. * @param itemId
  352. * the item id for which to create the details component.
  353. * @throws IllegalStateException
  354. * if the current details generator provides a component
  355. * that was manually attached.
  356. */
  357. private void createDetails(Object itemId) throws IllegalStateException {
  358. assert itemId != null : "itemId was null";
  359. if (itemIdToDetailsComponent.containsKey(itemId)
  360. || emptyDetails.contains(itemId)) {
  361. // Don't overwrite existing components
  362. return;
  363. }
  364. RowReference rowReference = new RowReference(getParentGrid());
  365. rowReference.set(itemId);
  366. DetailsGenerator detailsGenerator = getParentGrid()
  367. .getDetailsGenerator();
  368. Component details = detailsGenerator.getDetails(rowReference);
  369. if (details != null) {
  370. if (details.getParent() != null) {
  371. String name = detailsGenerator.getClass().getName();
  372. throw new IllegalStateException(
  373. name + " generated a details component that already "
  374. + "was attached. (itemId: " + itemId
  375. + ", component: " + details + ")");
  376. }
  377. itemIdToDetailsComponent.put(itemId, details);
  378. addComponentToGrid(details);
  379. assert !emptyDetails.contains(itemId) : "Bookeeping thinks "
  380. + "itemId is empty even though we just created a "
  381. + "component for it (" + itemId + ")";
  382. } else {
  383. emptyDetails.add(itemId);
  384. }
  385. }
  386. /**
  387. * Destroys a details component correctly.
  388. * <p>
  389. * This method will detach the component from parent {@link Grid}.
  390. *
  391. * @param itemId
  392. * the item id for which to destroy the details component
  393. */
  394. private void destroyDetails(Object itemId) {
  395. emptyDetails.remove(itemId);
  396. Component removedComponent = itemIdToDetailsComponent
  397. .remove(itemId);
  398. if (removedComponent == null) {
  399. return;
  400. }
  401. removeComponentFromGrid(removedComponent);
  402. }
  403. /**
  404. * Recreates all visible details components.
  405. */
  406. public void refreshDetails() {
  407. Set<Object> visibleItemIds = new HashSet<Object>(
  408. itemIdToDetailsComponent.keySet());
  409. for (Object itemId : visibleItemIds) {
  410. destroyDetails(itemId);
  411. createDetails(itemId);
  412. refreshRow(itemId);
  413. }
  414. }
  415. /**
  416. * Sets details visiblity status of given item id.
  417. *
  418. * @param itemId
  419. * item id to set
  420. * @param visible
  421. * <code>true</code> if visible; <code>false</code> if not
  422. */
  423. public void setDetailsVisible(Object itemId, boolean visible) {
  424. if ((visible && openDetails.contains(itemId))
  425. || (!visible && !openDetails.contains(itemId))) {
  426. return;
  427. }
  428. if (visible) {
  429. openDetails.add(itemId);
  430. refreshRow(itemId);
  431. } else {
  432. openDetails.remove(itemId);
  433. destroyDetails(itemId);
  434. refreshRow(itemId);
  435. }
  436. }
  437. @Override
  438. public void generateData(Object itemId, Item item, JsonObject rowData) {
  439. // DetailComponentManager should not send anything if details
  440. // generator is the default null version.
  441. if (openDetails.contains(itemId)
  442. && !detailsGenerator.equals(DetailsGenerator.NULL)) {
  443. // Double check to be sure details component exists.
  444. createDetails(itemId);
  445. Component detailsComponent = itemIdToDetailsComponent
  446. .get(itemId);
  447. rowData.put(GridState.JSONKEY_DETAILS_VISIBLE,
  448. (detailsComponent != null
  449. ? detailsComponent.getConnectorId() : ""));
  450. }
  451. }
  452. @Override
  453. public void destroyData(Object itemId) {
  454. if (openDetails.contains(itemId)) {
  455. destroyDetails(itemId);
  456. }
  457. }
  458. /**
  459. * Sets a new details generator for row details.
  460. * <p>
  461. * The currently opened row details will be re-rendered.
  462. *
  463. * @param detailsGenerator
  464. * the details generator to set
  465. * @throws IllegalArgumentException
  466. * if detailsGenerator is <code>null</code>;
  467. */
  468. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  469. throws IllegalArgumentException {
  470. if (detailsGenerator == null) {
  471. throw new IllegalArgumentException(
  472. "Details generator may not be null");
  473. } else if (detailsGenerator == this.detailsGenerator) {
  474. return;
  475. }
  476. this.detailsGenerator = detailsGenerator;
  477. refreshDetails();
  478. }
  479. /**
  480. * Gets the current details generator for row details.
  481. *
  482. * @return the detailsGenerator the current details generator
  483. */
  484. public DetailsGenerator getDetailsGenerator() {
  485. return detailsGenerator;
  486. }
  487. /**
  488. * Checks whether details are visible for the given item.
  489. *
  490. * @param itemId
  491. * the id of the item for which to check details visibility
  492. * @return <code>true</code> iff the details are visible
  493. */
  494. public boolean isDetailsVisible(Object itemId) {
  495. return openDetails.contains(itemId);
  496. }
  497. }
  498. /**
  499. * Custom field group that allows finding property types before an item has
  500. * been bound.
  501. */
  502. private final class CustomFieldGroup extends FieldGroup {
  503. public CustomFieldGroup() {
  504. setFieldFactory(EditorFieldFactory.get());
  505. }
  506. @Override
  507. protected Class<?> getPropertyType(Object propertyId)
  508. throws BindException {
  509. if (getItemDataSource() == null) {
  510. return datasource.getType(propertyId);
  511. } else {
  512. return super.getPropertyType(propertyId);
  513. }
  514. }
  515. @Override
  516. protected <T extends Field> T build(String caption, Class<?> dataType,
  517. Class<T> fieldType) throws BindException {
  518. T field = super.build(caption, dataType, fieldType);
  519. if (field instanceof CheckBox) {
  520. field.setCaption(null);
  521. }
  522. return field;
  523. }
  524. @Override
  525. protected void bindFields() {
  526. List<Field<?>> fields = new ArrayList<Field<?>>(getFields());
  527. Item itemDataSource = getItemDataSource();
  528. if (itemDataSource == null) {
  529. unbindFields(fields);
  530. } else {
  531. bindFields(fields, itemDataSource);
  532. }
  533. }
  534. private void unbindFields(List<Field<?>> fields) {
  535. for (Field<?> field : fields) {
  536. clearField(field);
  537. unbind(field);
  538. field.setParent(null);
  539. }
  540. }
  541. private void bindFields(List<Field<?>> fields, Item itemDataSource) {
  542. for (Field<?> field : fields) {
  543. if (itemDataSource
  544. .getItemProperty(getPropertyId(field)) != null) {
  545. bind(field, getPropertyId(field));
  546. }
  547. }
  548. }
  549. }
  550. /**
  551. * Field factory used by default in the editor.
  552. *
  553. * Aims to fields of suitable type and with suitable size for use in the
  554. * editor row.
  555. */
  556. @Deprecated
  557. public static class EditorFieldFactory
  558. extends DefaultFieldGroupFieldFactory {
  559. private static final EditorFieldFactory INSTANCE = new EditorFieldFactory();
  560. protected EditorFieldFactory() {
  561. }
  562. /**
  563. * Returns the singleton instance
  564. *
  565. * @return the singleton instance
  566. */
  567. public static EditorFieldFactory get() {
  568. return INSTANCE;
  569. }
  570. @Override
  571. public <T extends Field> T createField(Class<?> type,
  572. Class<T> fieldType) {
  573. T f = super.createField(type, fieldType);
  574. if (f != null) {
  575. f.setWidth("100%");
  576. }
  577. return f;
  578. }
  579. @Override
  580. protected AbstractSelect createCompatibleSelect(
  581. Class<? extends AbstractSelect> fieldType) {
  582. if (anySelect(fieldType)) {
  583. return super.createCompatibleSelect(ComboBox.class);
  584. }
  585. return super.createCompatibleSelect(fieldType);
  586. }
  587. @Override
  588. protected void populateWithEnumData(AbstractSelect select,
  589. Class<? extends Enum> enumClass) {
  590. // Use enums directly and the EnumToStringConverter to be consistent
  591. // with what is shown in the Grid
  592. @SuppressWarnings("unchecked")
  593. EnumSet<?> enumSet = EnumSet.allOf(enumClass);
  594. for (Object r : enumSet) {
  595. select.addItem(r);
  596. }
  597. }
  598. }
  599. /**
  600. * Error handler for the editor
  601. */
  602. @Deprecated
  603. public interface EditorErrorHandler extends Serializable {
  604. /**
  605. * Called when an exception occurs while the editor row is being saved
  606. *
  607. * @param event
  608. * An event providing more information about the error
  609. */
  610. void commitError(CommitErrorEvent event);
  611. }
  612. /**
  613. * ContextClickEvent for the Grid Component.
  614. *
  615. * @since 7.6
  616. */
  617. @Deprecated
  618. public static class GridContextClickEvent extends ContextClickEvent {
  619. private final Object itemId;
  620. private final int rowIndex;
  621. private final Object propertyId;
  622. private final Section section;
  623. public GridContextClickEvent(Grid source,
  624. MouseEventDetails mouseEventDetails, Section section,
  625. int rowIndex, Object itemId, Object propertyId) {
  626. super(source, mouseEventDetails);
  627. this.itemId = itemId;
  628. this.propertyId = propertyId;
  629. this.section = section;
  630. this.rowIndex = rowIndex;
  631. }
  632. /**
  633. * Returns the item id of context clicked row.
  634. *
  635. * @return item id of clicked row; <code>null</code> if header or footer
  636. */
  637. public Object getItemId() {
  638. return itemId;
  639. }
  640. /**
  641. * Returns property id of clicked column.
  642. *
  643. * @return property id
  644. */
  645. public Object getPropertyId() {
  646. return propertyId;
  647. }
  648. /**
  649. * Return the clicked section of Grid.
  650. *
  651. * @return section of grid
  652. */
  653. public Section getSection() {
  654. return section;
  655. }
  656. /**
  657. * Returns the clicked row index relative to Grid section. In the body
  658. * of the Grid the index is the item index in the Container. Header and
  659. * Footer rows for index can be fetched with
  660. * {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
  661. *
  662. * @return row index in section
  663. */
  664. public int getRowIndex() {
  665. return rowIndex;
  666. }
  667. @Override
  668. public Grid getComponent() {
  669. return (Grid) super.getComponent();
  670. }
  671. }
  672. /**
  673. * An event which is fired when saving the editor fails
  674. */
  675. @Deprecated
  676. public static class CommitErrorEvent extends Component.Event {
  677. private CommitException cause;
  678. private Set<Column> errorColumns = new HashSet<Column>();
  679. private String userErrorMessage;
  680. public CommitErrorEvent(Grid grid, CommitException cause) {
  681. super(grid);
  682. this.cause = cause;
  683. userErrorMessage = cause.getLocalizedMessage();
  684. }
  685. /**
  686. * Retrieves the cause of the failure
  687. *
  688. * @return the cause of the failure
  689. */
  690. public CommitException getCause() {
  691. return cause;
  692. }
  693. @Override
  694. public Grid getComponent() {
  695. return (Grid) super.getComponent();
  696. }
  697. /**
  698. * Checks if validation exceptions caused this error
  699. *
  700. * @return true if the problem was caused by a validation error
  701. */
  702. public boolean isValidationFailure() {
  703. return cause.getCause() instanceof InvalidValueException;
  704. }
  705. /**
  706. * Marks that an error indicator should be shown for the editor of a
  707. * column.
  708. *
  709. * @param column
  710. * the column to show an error for
  711. */
  712. public void addErrorColumn(Column column) {
  713. errorColumns.add(column);
  714. }
  715. /**
  716. * Gets all the columns that have been marked as erroneous.
  717. *
  718. * @return an umodifiable collection of erroneous columns
  719. */
  720. public Collection<Column> getErrorColumns() {
  721. return Collections.unmodifiableCollection(errorColumns);
  722. }
  723. /**
  724. * Gets the error message to show to the user.
  725. *
  726. * @return error message to show
  727. */
  728. public String getUserErrorMessage() {
  729. return userErrorMessage;
  730. }
  731. /**
  732. * Sets the error message to show to the user.
  733. *
  734. * @param userErrorMessage
  735. * the user error message to set
  736. */
  737. public void setUserErrorMessage(String userErrorMessage) {
  738. this.userErrorMessage = userErrorMessage;
  739. }
  740. }
  741. /**
  742. * An event listener for column reorder events in the Grid.
  743. *
  744. * @since 7.5.0
  745. */
  746. @Deprecated
  747. public interface ColumnReorderListener extends Serializable {
  748. /**
  749. * Called when the columns of the grid have been reordered.
  750. *
  751. * @param event
  752. * An event providing more information
  753. */
  754. void columnReorder(ColumnReorderEvent event);
  755. }
  756. /**
  757. * An event that is fired when the columns are reordered.
  758. *
  759. * @since 7.5.0
  760. */
  761. @Deprecated
  762. public static class ColumnReorderEvent extends Component.Event {
  763. private final boolean userOriginated;
  764. /**
  765. *
  766. * @param source
  767. * the grid where the event originated from
  768. * @param userOriginated
  769. * <code>true</code> if event is a result of user
  770. * interaction, <code>false</code> if from API call
  771. */
  772. public ColumnReorderEvent(Grid source, boolean userOriginated) {
  773. super(source);
  774. this.userOriginated = userOriginated;
  775. }
  776. /**
  777. * Returns <code>true</code> if the column reorder was done by the user,
  778. * <code>false</code> if not and it was triggered by server side code.
  779. *
  780. * @return <code>true</code> if event is a result of user interaction
  781. */
  782. public boolean isUserOriginated() {
  783. return userOriginated;
  784. }
  785. }
  786. /**
  787. * An event listener for column resize events in the Grid.
  788. *
  789. * @since 7.6
  790. */
  791. @Deprecated
  792. public interface ColumnResizeListener extends Serializable {
  793. /**
  794. * Called when the columns of the grid have been resized.
  795. *
  796. * @param event
  797. * An event providing more information
  798. */
  799. void columnResize(ColumnResizeEvent event);
  800. }
  801. /**
  802. * An event that is fired when a column is resized, either programmatically
  803. * or by the user.
  804. *
  805. * @since 7.6
  806. */
  807. @Deprecated
  808. public static class ColumnResizeEvent extends Component.Event {
  809. private final Column column;
  810. private final boolean userOriginated;
  811. /**
  812. *
  813. * @param source
  814. * the grid where the event originated from
  815. * @param userOriginated
  816. * <code>true</code> if event is a result of user
  817. * interaction, <code>false</code> if from API call
  818. */
  819. public ColumnResizeEvent(Grid source, Column column,
  820. boolean userOriginated) {
  821. super(source);
  822. this.column = column;
  823. this.userOriginated = userOriginated;
  824. }
  825. /**
  826. * Returns the column that was resized.
  827. *
  828. * @return the resized column.
  829. */
  830. public Column getColumn() {
  831. return column;
  832. }
  833. /**
  834. * Returns <code>true</code> if the column resize was done by the user,
  835. * <code>false</code> if not and it was triggered by server side code.
  836. *
  837. * @return <code>true</code> if event is a result of user interaction
  838. */
  839. public boolean isUserOriginated() {
  840. return userOriginated;
  841. }
  842. }
  843. /**
  844. * Interface for an editor event listener
  845. */
  846. @Deprecated
  847. public interface EditorListener extends Serializable {
  848. public static final Method EDITOR_OPEN_METHOD = ReflectTools.findMethod(
  849. EditorListener.class, "editorOpened", EditorOpenEvent.class);
  850. public static final Method EDITOR_MOVE_METHOD = ReflectTools.findMethod(
  851. EditorListener.class, "editorMoved", EditorMoveEvent.class);
  852. public static final Method EDITOR_CLOSE_METHOD = ReflectTools
  853. .findMethod(EditorListener.class, "editorClosed",
  854. EditorCloseEvent.class);
  855. /**
  856. * Called when an editor is opened
  857. *
  858. * @param e
  859. * an editor open event object
  860. */
  861. public void editorOpened(EditorOpenEvent e);
  862. /**
  863. * Called when an editor is reopened without closing it first
  864. *
  865. * @param e
  866. * an editor move event object
  867. */
  868. public void editorMoved(EditorMoveEvent e);
  869. /**
  870. * Called when an editor is closed
  871. *
  872. * @param e
  873. * an editor close event object
  874. */
  875. public void editorClosed(EditorCloseEvent e);
  876. }
  877. /**
  878. * Base class for editor related events
  879. */
  880. @Deprecated
  881. public abstract static class EditorEvent extends Component.Event {
  882. private Object itemID;
  883. protected EditorEvent(Grid source, Object itemID) {
  884. super(source);
  885. this.itemID = itemID;
  886. }
  887. /**
  888. * Get the item (row) for which this editor was opened
  889. */
  890. public Object getItem() {
  891. return itemID;
  892. }
  893. }
  894. /**
  895. * This event gets fired when an editor is opened
  896. */
  897. @Deprecated
  898. public static class EditorOpenEvent extends EditorEvent {
  899. public EditorOpenEvent(Grid source, Object itemID) {
  900. super(source, itemID);
  901. }
  902. }
  903. /**
  904. * This event gets fired when an editor is opened while another row is being
  905. * edited (i.e. editor focus moves elsewhere)
  906. */
  907. @Deprecated
  908. public static class EditorMoveEvent extends EditorEvent {
  909. public EditorMoveEvent(Grid source, Object itemID) {
  910. super(source, itemID);
  911. }
  912. }
  913. /**
  914. * This event gets fired when an editor is dismissed or closed by other
  915. * means.
  916. */
  917. @Deprecated
  918. public static class EditorCloseEvent extends EditorEvent {
  919. public EditorCloseEvent(Grid source, Object itemID) {
  920. super(source, itemID);
  921. }
  922. }
  923. /**
  924. * Default error handler for the editor
  925. *
  926. */
  927. @Deprecated
  928. public class DefaultEditorErrorHandler implements EditorErrorHandler {
  929. @Override
  930. public void commitError(CommitErrorEvent event) {
  931. Map<Field<?>, InvalidValueException> invalidFields = event
  932. .getCause().getInvalidFields();
  933. if (!invalidFields.isEmpty()) {
  934. Object firstErrorPropertyId = null;
  935. Field<?> firstErrorField = null;
  936. FieldGroup fieldGroup = event.getCause().getFieldGroup();
  937. for (Column column : getColumns()) {
  938. Object propertyId = column.getPropertyId();
  939. Field<?> field = fieldGroup.getField(propertyId);
  940. if (invalidFields.keySet().contains(field)) {
  941. event.addErrorColumn(column);
  942. if (firstErrorPropertyId == null) {
  943. firstErrorPropertyId = propertyId;
  944. firstErrorField = field;
  945. }
  946. }
  947. }
  948. /*
  949. * Validation error, show first failure as
  950. * "<Column header>: <message>"
  951. */
  952. String caption = getColumn(firstErrorPropertyId)
  953. .getHeaderCaption();
  954. String message = invalidFields.get(firstErrorField)
  955. .getLocalizedMessage();
  956. event.setUserErrorMessage(caption + ": " + message);
  957. } else {
  958. com.vaadin.server.ErrorEvent.findErrorHandler(Grid.this).error(
  959. new ConnectorErrorEvent(Grid.this, event.getCause()));
  960. }
  961. }
  962. private Object getFirstPropertyId(FieldGroup fieldGroup,
  963. Set<Field<?>> keySet) {
  964. for (Column c : getColumns()) {
  965. Object propertyId = c.getPropertyId();
  966. Field<?> f = fieldGroup.getField(propertyId);
  967. if (keySet.contains(f)) {
  968. return propertyId;
  969. }
  970. }
  971. return null;
  972. }
  973. }
  974. /**
  975. * Selection modes representing built-in {@link SelectionModel
  976. * SelectionModels} that come bundled with {@link Grid}.
  977. * <p>
  978. * Passing one of these enums into
  979. * {@link Grid#setSelectionMode(SelectionMode)} is equivalent to calling
  980. * {@link Grid#setSelectionModel(SelectionModel)} with one of the built-in
  981. * implementations of {@link SelectionModel}.
  982. *
  983. * @see Grid#setSelectionMode(SelectionMode)
  984. * @see Grid#setSelectionModel(SelectionModel)
  985. */
  986. @Deprecated
  987. public enum SelectionMode {
  988. /** A SelectionMode that maps to {@link SingleSelectionModel} */
  989. SINGLE {
  990. @Override
  991. protected SelectionModel createModel() {
  992. return new SingleSelectionModel();
  993. }
  994. },
  995. /** A SelectionMode that maps to {@link MultiSelectionModel} */
  996. MULTI {
  997. @Override
  998. protected SelectionModel createModel() {
  999. return new MultiSelectionModel();
  1000. }
  1001. },
  1002. /** A SelectionMode that maps to {@link NoSelectionModel} */
  1003. NONE {
  1004. @Override
  1005. protected SelectionModel createModel() {
  1006. return new NoSelectionModel();
  1007. }
  1008. };
  1009. protected abstract SelectionModel createModel();
  1010. }
  1011. /**
  1012. * The server-side interface that controls Grid's selection state.
  1013. * SelectionModel should extend {@link AbstractGridExtension}.
  1014. */
  1015. @Deprecated
  1016. public interface SelectionModel extends Serializable, Extension {
  1017. /**
  1018. * Interface implemented by selection models which support disabling
  1019. * client side selection while still allowing programmatic selection on
  1020. * the server.
  1021. *
  1022. * @since 7.7.7
  1023. */
  1024. @Deprecated
  1025. public interface HasUserSelectionAllowed extends SelectionModel {
  1026. /**
  1027. * Checks if the user is allowed to change the selection.
  1028. *
  1029. * @return <code>true</code> if the user is allowed to change the
  1030. * selection, <code>false</code> otherwise
  1031. */
  1032. public boolean isUserSelectionAllowed();
  1033. /**
  1034. * Sets whether the user is allowed to change the selection.
  1035. *
  1036. * @param userSelectionAllowed
  1037. * <code>true</code> if the user is allowed to change the
  1038. * selection, <code>false</code> otherwise
  1039. */
  1040. public void setUserSelectionAllowed(boolean userSelectionAllowed);
  1041. }
  1042. /**
  1043. * Checks whether an item is selected or not.
  1044. *
  1045. * @param itemId
  1046. * the item id to check for
  1047. * @return <code>true</code> iff the item is selected
  1048. */
  1049. boolean isSelected(Object itemId);
  1050. /**
  1051. * Returns a collection of all the currently selected itemIds.
  1052. *
  1053. * @return a collection of all the currently selected itemIds
  1054. */
  1055. Collection<Object> getSelectedRows();
  1056. /**
  1057. * Injects the current {@link Grid} instance into the SelectionModel.
  1058. * This method should usually call the extend method of
  1059. * {@link AbstractExtension}.
  1060. * <p>
  1061. * <em>Note:</em> This method should not be called manually.
  1062. *
  1063. * @param grid
  1064. * the Grid in which the SelectionModel currently is, or
  1065. * <code>null</code> when a selection model is being detached
  1066. * from a Grid.
  1067. */
  1068. void setGrid(Grid grid);
  1069. /**
  1070. * Resets the SelectiomModel to an initial state.
  1071. * <p>
  1072. * Most often this means that the selection state is cleared, but
  1073. * implementations are free to interpret the "initial state" as they
  1074. * wish. Some, for example, may want to keep the first selected item as
  1075. * selected.
  1076. */
  1077. void reset();
  1078. /**
  1079. * A SelectionModel that supports multiple selections to be made.
  1080. * <p>
  1081. * This interface has a contract of having the same behavior, no matter
  1082. * how the selection model is interacted with. In other words, if
  1083. * something is forbidden to do in e.g. the user interface, it must also
  1084. * be forbidden to do in the server-side and client-side APIs.
  1085. */
  1086. @Deprecated
  1087. public interface Multi extends SelectionModel {
  1088. /**
  1089. * Marks items as selected.
  1090. * <p>
  1091. * This method does not clear any previous selection state, only
  1092. * adds to it.
  1093. *
  1094. * @param itemIds
  1095. * the itemId(s) to mark as selected
  1096. * @return <code>true</code> if the selection state changed.
  1097. * <code>false</code> if all the given itemIds already were
  1098. * selected
  1099. * @throws IllegalArgumentException
  1100. * if the <code>itemIds</code> varargs array is
  1101. * <code>null</code> or given itemIds don't exist in the
  1102. * container of Grid
  1103. * @see #deselect(Object...)
  1104. */
  1105. boolean select(Object... itemIds) throws IllegalArgumentException;
  1106. /**
  1107. * Marks items as selected.
  1108. * <p>
  1109. * This method does not clear any previous selection state, only
  1110. * adds to it.
  1111. *
  1112. * @param itemIds
  1113. * the itemIds to mark as selected
  1114. * @return <code>true</code> if the selection state changed.
  1115. * <code>false</code> if all the given itemIds already were
  1116. * selected
  1117. * @throws IllegalArgumentException
  1118. * if <code>itemIds</code> is <code>null</code> or given
  1119. * itemIds don't exist in the container of Grid
  1120. * @see #deselect(Collection)
  1121. */
  1122. boolean select(Collection<?> itemIds)
  1123. throws IllegalArgumentException;
  1124. /**
  1125. * Marks items as deselected.
  1126. *
  1127. * @param itemIds
  1128. * the itemId(s) to remove from being selected
  1129. * @return <code>true</code> if the selection state changed.
  1130. * <code>false</code> if none the given itemIds were
  1131. * selected previously
  1132. * @throws IllegalArgumentException
  1133. * if the <code>itemIds</code> varargs array is
  1134. * <code>null</code>
  1135. * @see #select(Object...)
  1136. */
  1137. boolean deselect(Object... itemIds) throws IllegalArgumentException;
  1138. /**
  1139. * Marks items as deselected.
  1140. *
  1141. * @param itemIds
  1142. * the itemId(s) to remove from being selected
  1143. * @return <code>true</code> if the selection state changed.
  1144. * <code>false</code> if none the given itemIds were
  1145. * selected previously
  1146. * @throws IllegalArgumentException
  1147. * if <code>itemIds</code> is <code>null</code>
  1148. * @see #select(Collection)
  1149. */
  1150. boolean deselect(Collection<?> itemIds)
  1151. throws IllegalArgumentException;
  1152. /**
  1153. * Marks all the items in the current Container as selected
  1154. *
  1155. * @return <code>true</code> iff some items were previously not
  1156. * selected
  1157. * @see #deselectAll()
  1158. */
  1159. boolean selectAll();
  1160. /**
  1161. * Marks all the items in the current Container as deselected
  1162. *
  1163. * @return <code>true</code> iff some items were previously selected
  1164. * @see #selectAll()
  1165. */
  1166. boolean deselectAll();
  1167. /**
  1168. * Marks items as selected while deselecting all items not in the
  1169. * given Collection.
  1170. *
  1171. * @param itemIds
  1172. * the itemIds to mark as selected
  1173. * @return <code>true</code> if the selection state changed.
  1174. * <code>false</code> if all the given itemIds already were
  1175. * selected
  1176. * @throws IllegalArgumentException
  1177. * if <code>itemIds</code> is <code>null</code> or given
  1178. * itemIds don't exist in the container of Grid
  1179. */
  1180. boolean setSelected(Collection<?> itemIds)
  1181. throws IllegalArgumentException;
  1182. /**
  1183. * Marks items as selected while deselecting all items not in the
  1184. * varargs array.
  1185. *
  1186. * @param itemIds
  1187. * the itemIds to mark as selected
  1188. * @return <code>true</code> if the selection state changed.
  1189. * <code>false</code> if all the given itemIds already were
  1190. * selected
  1191. * @throws IllegalArgumentException
  1192. * if the <code>itemIds</code> varargs array is
  1193. * <code>null</code> or given itemIds don't exist in the
  1194. * container of Grid
  1195. */
  1196. boolean setSelected(Object... itemIds)
  1197. throws IllegalArgumentException;
  1198. }
  1199. /**
  1200. * A SelectionModel that supports for only single rows to be selected at
  1201. * a time.
  1202. * <p>
  1203. * This interface has a contract of having the same behavior, no matter
  1204. * how the selection model is interacted with. In other words, if
  1205. * something is forbidden to do in e.g. the user interface, it must also
  1206. * be forbidden to do in the server-side and client-side APIs.
  1207. */
  1208. @Deprecated
  1209. public interface Single extends SelectionModel {
  1210. /**
  1211. * Marks an item as selected.
  1212. *
  1213. * @param itemId
  1214. * the itemId to mark as selected; <code>null</code> for
  1215. * deselect
  1216. * @return <code>true</code> if the selection state changed.
  1217. * <code>false</code> if the itemId already was selected
  1218. * @throws IllegalStateException
  1219. * if the selection was illegal. One such reason might
  1220. * be that the given id was null, indicating a deselect,
  1221. * but implementation doesn't allow deselecting.
  1222. * re-selecting something
  1223. * @throws IllegalArgumentException
  1224. * if given itemId does not exist in the container of
  1225. * Grid
  1226. */
  1227. boolean select(Object itemId)
  1228. throws IllegalStateException, IllegalArgumentException;
  1229. /**
  1230. * Gets the item id of the currently selected item.
  1231. *
  1232. * @return the item id of the currently selected item, or
  1233. * <code>null</code> if nothing is selected
  1234. */
  1235. Object getSelectedRow();
  1236. /**
  1237. * Sets whether it's allowed to deselect the selected row through
  1238. * the UI. Deselection is allowed by default.
  1239. *
  1240. * @param deselectAllowed
  1241. * <code>true</code> if the selected row can be
  1242. * deselected without selecting another row instead;
  1243. * otherwise <code>false</code>.
  1244. */
  1245. public void setDeselectAllowed(boolean deselectAllowed);
  1246. /**
  1247. * Sets whether it's allowed to deselect the selected row through
  1248. * the UI.
  1249. *
  1250. * @return <code>true</code> if deselection is allowed; otherwise
  1251. * <code>false</code>
  1252. */
  1253. public boolean isDeselectAllowed();
  1254. }
  1255. /**
  1256. * A SelectionModel that does not allow for rows to be selected.
  1257. * <p>
  1258. * This interface has a contract of having the same behavior, no matter
  1259. * how the selection model is interacted with. In other words, if the
  1260. * developer is unable to select something programmatically, it is not
  1261. * allowed for the end-user to select anything, either.
  1262. */
  1263. @Deprecated
  1264. public interface None extends SelectionModel {
  1265. /**
  1266. * {@inheritDoc}
  1267. *
  1268. * @return always <code>false</code>.
  1269. */
  1270. @Override
  1271. public boolean isSelected(Object itemId);
  1272. /**
  1273. * {@inheritDoc}
  1274. *
  1275. * @return always an empty collection.
  1276. */
  1277. @Override
  1278. public Collection<Object> getSelectedRows();
  1279. }
  1280. }
  1281. /**
  1282. * A base class for SelectionModels that contains some of the logic that is
  1283. * reusable.
  1284. */
  1285. @Deprecated
  1286. public abstract static class AbstractSelectionModel extends
  1287. AbstractGridExtension implements SelectionModel, DataGenerator {
  1288. protected final LinkedHashSet<Object> selection = new LinkedHashSet<Object>();
  1289. @Override
  1290. public boolean isSelected(final Object itemId) {
  1291. return selection.contains(itemId);
  1292. }
  1293. @Override
  1294. public Collection<Object> getSelectedRows() {
  1295. return new ArrayList<Object>(selection);
  1296. }
  1297. @Override
  1298. public void setGrid(final Grid grid) {
  1299. if (grid != null) {
  1300. extend(grid);
  1301. }
  1302. }
  1303. /**
  1304. * Sanity check for existence of item id.
  1305. *
  1306. * @param itemId
  1307. * item id to be selected / deselected
  1308. *
  1309. * @throws IllegalArgumentException
  1310. * if item Id doesn't exist in the container of Grid
  1311. */
  1312. protected void checkItemIdExists(Object itemId)
  1313. throws IllegalArgumentException {
  1314. if (!getParentGrid().getContainerDataSource().containsId(itemId)) {
  1315. throw new IllegalArgumentException("Given item id (" + itemId
  1316. + ") does not exist in the container");
  1317. }
  1318. }
  1319. /**
  1320. * Sanity check for existence of item ids in given collection.
  1321. *
  1322. * @param itemIds
  1323. * item id collection to be selected / deselected
  1324. *
  1325. * @throws IllegalArgumentException
  1326. * if at least one item id doesn't exist in the container of
  1327. * Grid
  1328. */
  1329. protected void checkItemIdsExist(Collection<?> itemIds)
  1330. throws IllegalArgumentException {
  1331. for (Object itemId : itemIds) {
  1332. checkItemIdExists(itemId);
  1333. }
  1334. }
  1335. /**
  1336. * Fires a {@link SelectionEvent} to all the {@link SelectionListener
  1337. * SelectionListeners} currently added to the Grid in which this
  1338. * SelectionModel is.
  1339. * <p>
  1340. * Note that this is only a helper method, and routes the call all the
  1341. * way to Grid. A {@link SelectionModel} is not a
  1342. * {@link SelectionNotifier}
  1343. *
  1344. * @param oldSelection
  1345. * the complete {@link Collection} of the itemIds that were
  1346. * selected <em>before</em> this event happened
  1347. * @param newSelection
  1348. * the complete {@link Collection} of the itemIds that are
  1349. * selected <em>after</em> this event happened
  1350. */
  1351. protected void fireSelectionEvent(final Collection<Object> oldSelection,
  1352. final Collection<Object> newSelection) {
  1353. getParentGrid().fireSelectionEvent(oldSelection, newSelection);
  1354. }
  1355. @Override
  1356. public void generateData(Object itemId, Item item, JsonObject rowData) {
  1357. if (isSelected(itemId)) {
  1358. rowData.put(GridState.JSONKEY_SELECTED, true);
  1359. }
  1360. }
  1361. @Override
  1362. public void destroyData(Object itemId) {
  1363. // NO-OP
  1364. }
  1365. @Override
  1366. protected Object getItemId(String rowKey) {
  1367. return rowKey != null ? super.getItemId(rowKey) : null;
  1368. }
  1369. }
  1370. /**
  1371. * A default implementation of a {@link SelectionModel.Single}
  1372. */
  1373. @Deprecated
  1374. public static class SingleSelectionModel extends AbstractSelectionModel
  1375. implements SelectionModel.Single, HasUserSelectionAllowed {
  1376. @Override
  1377. protected void extend(AbstractClientConnector target) {
  1378. super.extend(target);
  1379. registerRpc(new SingleSelectionModelServerRpc() {
  1380. @Override
  1381. public void select(String rowKey) {
  1382. if (!isUserSelectionAllowed()) {
  1383. throw new IllegalStateException(
  1384. "Client tried to select '" + rowKey
  1385. + "' although user selection is disallowed");
  1386. }
  1387. SingleSelectionModel.this.select(getItemId(rowKey), false);
  1388. }
  1389. });
  1390. }
  1391. @Override
  1392. public boolean select(final Object itemId) {
  1393. return select(itemId, true);
  1394. }
  1395. protected boolean select(final Object itemId, boolean refresh) {
  1396. if (itemId == null) {
  1397. return deselect(getSelectedRow());
  1398. }
  1399. checkItemIdExists(itemId);
  1400. final Object selectedRow = getSelectedRow();
  1401. final boolean modified = selection.add(itemId);
  1402. if (modified) {
  1403. final Collection<Object> deselected;
  1404. if (selectedRow != null) {
  1405. deselectInternal(selectedRow, false, true);
  1406. deselected = Collections.singleton(selectedRow);
  1407. } else {
  1408. deselected = Collections.emptySet();
  1409. }
  1410. fireSelectionEvent(deselected, selection);
  1411. }
  1412. if (refresh) {
  1413. refreshRow(itemId);
  1414. }
  1415. return modified;
  1416. }
  1417. private boolean deselect(final Object itemId) {
  1418. return deselectInternal(itemId, true, true);
  1419. }
  1420. private boolean deselectInternal(final Object itemId,
  1421. boolean fireEventIfNeeded, boolean refresh) {
  1422. final boolean modified = selection.remove(itemId);
  1423. if (modified) {
  1424. if (refresh) {
  1425. refreshRow(itemId);
  1426. }
  1427. if (fireEventIfNeeded) {
  1428. fireSelectionEvent(Collections.singleton(itemId),
  1429. Collections.emptySet());
  1430. }
  1431. }
  1432. return modified;
  1433. }
  1434. @Override
  1435. public Object getSelectedRow() {
  1436. if (selection.isEmpty()) {
  1437. return null;
  1438. } else {
  1439. return selection.iterator().next();
  1440. }
  1441. }
  1442. /**
  1443. * Resets the selection state.
  1444. * <p>
  1445. * If an item is selected, it will become deselected.
  1446. */
  1447. @Override
  1448. public void reset() {
  1449. deselect(getSelectedRow());
  1450. }
  1451. @Override
  1452. public void setDeselectAllowed(boolean deselectAllowed) {
  1453. getState().deselectAllowed = deselectAllowed;
  1454. }
  1455. @Override
  1456. public boolean isDeselectAllowed() {
  1457. return getState().deselectAllowed;
  1458. }
  1459. @Override
  1460. protected SingleSelectionModelState getState() {
  1461. return (SingleSelectionModelState) super.getState();
  1462. }
  1463. @Override
  1464. protected SingleSelectionModelState getState(boolean markAsDirty) {
  1465. return (SingleSelectionModelState) super.getState(markAsDirty);
  1466. }
  1467. @Override
  1468. public boolean isUserSelectionAllowed() {
  1469. return getState(false).userSelectionAllowed;
  1470. }
  1471. @Override
  1472. public void setUserSelectionAllowed(boolean userSelectionAllowed) {
  1473. getState().userSelectionAllowed = userSelectionAllowed;
  1474. }
  1475. }
  1476. /**
  1477. * A default implementation for a {@link SelectionModel.None}
  1478. */
  1479. @Deprecated
  1480. public static class NoSelectionModel extends AbstractSelectionModel
  1481. implements SelectionModel.None {
  1482. @Override
  1483. public boolean isSelected(final Object itemId) {
  1484. return false;
  1485. }
  1486. @Override
  1487. public Collection<Object> getSelectedRows() {
  1488. return Collections.emptyList();
  1489. }
  1490. /**
  1491. * Semantically resets the selection model.
  1492. * <p>
  1493. * Effectively a no-op.
  1494. */
  1495. @Override
  1496. public void reset() {
  1497. // NOOP
  1498. }
  1499. }
  1500. /**
  1501. * A default implementation of a {@link SelectionModel.Multi}
  1502. */
  1503. @Deprecated
  1504. public static class MultiSelectionModel extends AbstractSelectionModel
  1505. implements SelectionModel.Multi,
  1506. SelectionModel.HasUserSelectionAllowed {
  1507. /**
  1508. * The default selection size limit.
  1509. *
  1510. * @see #setSelectionLimit(int)
  1511. */
  1512. public static final int DEFAULT_MAX_SELECTIONS = 1000;
  1513. private int selectionLimit = DEFAULT_MAX_SELECTIONS;
  1514. @Override
  1515. protected void extend(AbstractClientConnector target) {
  1516. super.extend(target);
  1517. registerRpc(new MultiSelectionModelServerRpc() {
  1518. @Override
  1519. public void select(List<String> rowKeys) {
  1520. if (!isUserSelectionAllowed()) {
  1521. throw new IllegalStateException(
  1522. "Client tried to select '" + rowKeys
  1523. + "' although user selection is disallowed");
  1524. }
  1525. List<Object> items = new ArrayList<Object>();
  1526. for (String rowKey : rowKeys) {
  1527. items.add(getItemId(rowKey));
  1528. }
  1529. MultiSelectionModel.this.select(items, false);
  1530. }
  1531. @Override
  1532. public void deselect(List<String> rowKeys) {
  1533. if (!isUserSelectionAllowed()) {
  1534. throw new IllegalStateException(
  1535. "Client tried to deselect '" + rowKeys
  1536. + "' although user selection is disallowed");
  1537. }
  1538. List<Object> items = new ArrayList<Object>();
  1539. for (String rowKey : rowKeys) {
  1540. items.add(getItemId(rowKey));
  1541. }
  1542. MultiSelectionModel.this.deselect(items, false);
  1543. }
  1544. @Override
  1545. public void selectAll() {
  1546. if (!isUserSelectionAllowed()) {
  1547. throw new IllegalStateException(
  1548. "Client tried to select all although user selection is disallowed");
  1549. }
  1550. MultiSelectionModel.this.selectAll(false);
  1551. }
  1552. @Override
  1553. public void deselectAll() {
  1554. if (!isUserSelectionAllowed()) {
  1555. throw new IllegalStateException(
  1556. "Client tried to deselect all although user selection is disallowed");
  1557. }
  1558. MultiSelectionModel.this.deselectAll(false);
  1559. }
  1560. });
  1561. }
  1562. @Override
  1563. public boolean select(final Object... itemIds)
  1564. throws IllegalArgumentException {
  1565. if (itemIds != null) {
  1566. // select will fire the event
  1567. return select(Arrays.asList(itemIds));
  1568. } else {
  1569. throw new IllegalArgumentException(
  1570. "Vararg array of itemIds may not be null");
  1571. }
  1572. }
  1573. /**
  1574. * {@inheritDoc}
  1575. * <p>
  1576. * All items might not be selected if the limit set using
  1577. * {@link #setSelectionLimit(int)} is exceeded.
  1578. */
  1579. @Override
  1580. public boolean select(final Collection<?> itemIds)
  1581. throws IllegalArgumentException {
  1582. return select(itemIds, true);
  1583. }
  1584. protected boolean select(final Collection<?> itemIds, boolean refresh) {
  1585. if (itemIds == null) {
  1586. throw new IllegalArgumentException("itemIds may not be null");
  1587. }
  1588. // Sanity check
  1589. checkItemIdsExist(itemIds);
  1590. final boolean selectionWillChange = !selection.containsAll(itemIds)
  1591. && selection.size() < selectionLimit;
  1592. if (selectionWillChange) {
  1593. final HashSet<Object> oldSelection = new HashSet<Object>(
  1594. selection);
  1595. if (selection.size() + itemIds.size() >= selectionLimit) {
  1596. // Add one at a time if there's a risk of overflow
  1597. Iterator<?> iterator = itemIds.iterator();
  1598. while (iterator.hasNext()
  1599. && selection.size() < selectionLimit) {
  1600. selection.add(iterator.next());
  1601. }
  1602. } else {
  1603. selection.addAll(itemIds);
  1604. }
  1605. fireSelectionEvent(oldSelection, selection);
  1606. }
  1607. updateAllSelectedState();
  1608. if (refresh) {
  1609. for (Object itemId : itemIds) {
  1610. refreshRow(itemId);
  1611. }
  1612. }
  1613. return selectionWillChange;
  1614. }
  1615. /**
  1616. * Sets the maximum number of rows that can be selected at once. This is
  1617. * a mechanism to prevent exhausting server memory in situations where
  1618. * users select lots of rows. If the limit is reached, newly selected
  1619. * rows will not become recorded.
  1620. * <p>
  1621. * Old selections are not discarded if the current number of selected
  1622. * row exceeds the new limit.
  1623. * <p>
  1624. * The default limit is {@value #DEFAULT_MAX_SELECTIONS} rows.
  1625. *
  1626. * @param selectionLimit
  1627. * the non-negative selection limit to set
  1628. * @throws IllegalArgumentException
  1629. * if the limit is negative
  1630. */
  1631. public void setSelectionLimit(int selectionLimit) {
  1632. if (selectionLimit < 0) {
  1633. throw new IllegalArgumentException(
  1634. "The selection limit must be non-negative");
  1635. }
  1636. this.selectionLimit = selectionLimit;
  1637. }
  1638. /**
  1639. * Gets the selection limit.
  1640. *
  1641. * @see #setSelectionLimit(int)
  1642. *
  1643. * @return the selection limit
  1644. */
  1645. public int getSelectionLimit() {
  1646. return selectionLimit;
  1647. }
  1648. @Override
  1649. public boolean deselect(final Object... itemIds)
  1650. throws IllegalArgumentException {
  1651. if (itemIds != null) {
  1652. // deselect will fire the event
  1653. return deselect(Arrays.asList(itemIds));
  1654. } else {
  1655. throw new IllegalArgumentException(
  1656. "Vararg array of itemIds may not be null");
  1657. }
  1658. }
  1659. @Override
  1660. public boolean deselect(final Collection<?> itemIds)
  1661. throws IllegalArgumentException {
  1662. return deselect(itemIds, true);
  1663. }
  1664. protected boolean deselect(final Collection<?> itemIds,
  1665. boolean refresh) {
  1666. if (itemIds == null) {
  1667. throw new IllegalArgumentException("itemIds may not be null");
  1668. }
  1669. final boolean hasCommonElements = !Collections.disjoint(itemIds,
  1670. selection);
  1671. if (hasCommonElements) {
  1672. final HashSet<Object> oldSelection = new HashSet<Object>(
  1673. selection);
  1674. selection.removeAll(itemIds);
  1675. fireSelectionEvent(oldSelection, selection);
  1676. }
  1677. updateAllSelectedState();
  1678. if (refresh) {
  1679. for (Object itemId : itemIds) {
  1680. refreshRow(itemId);
  1681. }
  1682. }
  1683. return hasCommonElements;
  1684. }
  1685. @Override
  1686. public boolean selectAll() {
  1687. return selectAll(true);
  1688. }
  1689. protected boolean selectAll(boolean refresh) {
  1690. // select will fire the event
  1691. final Indexed container = getParentGrid().getContainerDataSource();
  1692. if (container != null) {
  1693. return select(container.getItemIds(), refresh);
  1694. } else if (selection.isEmpty()) {
  1695. return false;
  1696. } else {
  1697. /*
  1698. * this should never happen (no container but has a selection),
  1699. * but I guess the only theoretically correct course of
  1700. * action...
  1701. */
  1702. return deselectAll(false);
  1703. }
  1704. }
  1705. @Override
  1706. public boolean deselectAll() {
  1707. return deselectAll(true);
  1708. }
  1709. protected boolean deselectAll(boolean refresh) {
  1710. // deselect will fire the event
  1711. return deselect(getSelectedRows(), refresh);
  1712. }
  1713. /**
  1714. * {@inheritDoc}
  1715. * <p>
  1716. * The returned Collection is in <strong>order of selection</strong>
  1717. * &ndash; the item that was first selected will be first in the
  1718. * collection, and so on. Should an item have been selected twice
  1719. * without being deselected in between, it will have remained in its
  1720. * original position.
  1721. */
  1722. @Override
  1723. public Collection<Object> getSelectedRows() {
  1724. // overridden only for JavaDoc
  1725. return super.getSelectedRows();
  1726. }
  1727. /**
  1728. * Resets the selection model.
  1729. * <p>
  1730. * Equivalent to calling {@link #deselectAll()}
  1731. */
  1732. @Override
  1733. public void reset() {
  1734. deselectAll();
  1735. }
  1736. @Override
  1737. public boolean setSelected(Collection<?> itemIds)
  1738. throws IllegalArgumentException {
  1739. if (itemIds == null) {
  1740. throw new IllegalArgumentException("itemIds may not be null");
  1741. }
  1742. checkItemIdsExist(itemIds);
  1743. boolean changed = false;
  1744. Set<Object> selectedRows = new HashSet<Object>(itemIds);
  1745. final Collection<Object> oldSelection = getSelectedRows();
  1746. Set<Object> added = getDifference(selectedRows, selection);
  1747. if (!added.isEmpty()) {
  1748. changed = true;
  1749. selection.addAll(added);
  1750. for (Object id : added) {
  1751. refreshRow(id);
  1752. }
  1753. }
  1754. Set<Object> removed = getDifference(selection, selectedRows);
  1755. if (!removed.isEmpty()) {
  1756. changed = true;
  1757. selection.removeAll(removed);
  1758. for (Object id : removed) {
  1759. refreshRow(id);
  1760. }
  1761. }
  1762. if (changed) {
  1763. fireSelectionEvent(oldSelection, selection);
  1764. }
  1765. updateAllSelectedState();
  1766. return changed;
  1767. }
  1768. /**
  1769. * Compares two sets and returns a set containing all values that are
  1770. * present in the first, but not in the second.
  1771. *
  1772. * @param set1
  1773. * first item set
  1774. * @param set2
  1775. * second item set
  1776. * @return all values from set1 which are not present in set2
  1777. */
  1778. private static Set<Object> getDifference(Set<Object> set1,
  1779. Set<Object> set2) {
  1780. Set<Object> diff = new HashSet<Object>(set1);
  1781. diff.removeAll(set2);
  1782. return diff;
  1783. }
  1784. @Override
  1785. public boolean setSelected(Object... itemIds)
  1786. throws IllegalArgumentException {
  1787. if (itemIds != null) {
  1788. return setSelected(Arrays.asList(itemIds));
  1789. } else {
  1790. throw new IllegalArgumentException(
  1791. "Vararg array of itemIds may not be null");
  1792. }
  1793. }
  1794. private void updateAllSelectedState() {
  1795. int totalRowCount = getParentGrid().datasource.size();
  1796. int rows = Math.min(totalRowCount, selectionLimit);
  1797. if (totalRowCount == 0) {
  1798. getState().allSelected = false;
  1799. } else {
  1800. getState().allSelected = selection.size() >= rows;
  1801. }
  1802. }
  1803. @Override
  1804. protected MultiSelectionModelState getState() {
  1805. return (MultiSelectionModelState) super.getState();
  1806. }
  1807. @Override
  1808. protected MultiSelectionModelState getState(boolean markAsDirty) {
  1809. return (MultiSelectionModelState) super.getState(markAsDirty);
  1810. }
  1811. @Override
  1812. public boolean isUserSelectionAllowed() {
  1813. return getState(false).userSelectionAllowed;
  1814. }
  1815. @Override
  1816. public void setUserSelectionAllowed(boolean userSelectionAllowed) {
  1817. getState().userSelectionAllowed = userSelectionAllowed;
  1818. }
  1819. }
  1820. /**
  1821. * A data class which contains information which identifies a row in a
  1822. * {@link Grid}.
  1823. * <p>
  1824. * Since this class follows the <code>Flyweight</code>-pattern any instance
  1825. * of this object is subject to change without the user knowing it and so
  1826. * should not be stored anywhere outside of the method providing these
  1827. * instances.
  1828. */
  1829. @Deprecated
  1830. public static class RowReference implements Serializable {
  1831. private final Grid grid;
  1832. private Object itemId;
  1833. /**
  1834. * Creates a new row reference for the given grid.
  1835. *
  1836. * @param grid
  1837. * the grid that the row belongs to
  1838. */
  1839. public RowReference(Grid grid) {
  1840. this.grid = grid;
  1841. }
  1842. /**
  1843. * Sets the identifying information for this row
  1844. *
  1845. * @param itemId
  1846. * the item id of the row
  1847. */
  1848. public void set(Object itemId) {
  1849. this.itemId = itemId;
  1850. }
  1851. /**
  1852. * Gets the grid that contains the referenced row.
  1853. *
  1854. * @return the grid that contains referenced row
  1855. */
  1856. public Grid getGrid() {
  1857. return grid;
  1858. }
  1859. /**
  1860. * Gets the item id of the row.
  1861. *
  1862. * @return the item id of the row
  1863. */
  1864. public Object getItemId() {
  1865. return itemId;
  1866. }
  1867. /**
  1868. * Gets the item for the row.
  1869. *
  1870. * @return the item for the row
  1871. */
  1872. public Item getItem() {
  1873. return grid.getContainerDataSource().getItem(itemId);
  1874. }
  1875. }
  1876. /**
  1877. * A data class which contains information which identifies a cell in a
  1878. * {@link Grid}.
  1879. * <p>
  1880. * Since this class follows the <code>Flyweight</code>-pattern any instance
  1881. * of this object is subject to change without the user knowing it and so
  1882. * should not be stored anywhere outside of the method providing these
  1883. * instances.
  1884. */
  1885. @Deprecated
  1886. public static class CellReference implements Serializable {
  1887. private final RowReference rowReference;
  1888. private Object propertyId;
  1889. public CellReference(RowReference rowReference) {
  1890. this.rowReference = rowReference;
  1891. }
  1892. /**
  1893. * Sets the identifying information for this cell
  1894. *
  1895. * @param propertyId
  1896. * the property id of the column
  1897. */
  1898. public void set(Object propertyId) {
  1899. this.propertyId = propertyId;
  1900. }
  1901. /**
  1902. * Gets the grid that contains the referenced cell.
  1903. *
  1904. * @return the grid that contains referenced cell
  1905. */
  1906. public Grid getGrid() {
  1907. return rowReference.getGrid();
  1908. }
  1909. /**
  1910. * @return the property id of the column
  1911. */
  1912. public Object getPropertyId() {
  1913. return propertyId;
  1914. }
  1915. /**
  1916. * @return the property for the cell
  1917. */
  1918. public Property<?> getProperty() {
  1919. return getItem().getItemProperty(propertyId);
  1920. }
  1921. /**
  1922. * Gets the item id of the row of the cell.
  1923. *
  1924. * @return the item id of the row
  1925. */
  1926. public Object getItemId() {
  1927. return rowReference.getItemId();
  1928. }
  1929. /**
  1930. * Gets the item for the row of the cell.
  1931. *
  1932. * @return the item for the row
  1933. */
  1934. public Item getItem() {
  1935. return rowReference.getItem();
  1936. }
  1937. /**
  1938. * Gets the value of the cell.
  1939. *
  1940. * @return the value of the cell
  1941. */
  1942. public Object getValue() {
  1943. return getProperty().getValue();
  1944. }
  1945. }
  1946. /**
  1947. * A callback interface for generating custom style names for Grid rows.
  1948. *
  1949. * @see Grid#setRowStyleGenerator(RowStyleGenerator)
  1950. */
  1951. @Deprecated
  1952. public interface RowStyleGenerator extends Serializable {
  1953. /**
  1954. * Called by Grid to generate a style name for a row.
  1955. *
  1956. * @param row
  1957. * the row to generate a style for
  1958. * @return the style name to add to this row, or {@code null} to not set
  1959. * any style
  1960. */
  1961. public String getStyle(RowReference row);
  1962. }
  1963. /**
  1964. * A callback interface for generating custom style names for Grid cells.
  1965. *
  1966. * @see Grid#setCellStyleGenerator(CellStyleGenerator)
  1967. */
  1968. @Deprecated
  1969. public interface CellStyleGenerator extends Serializable {
  1970. /**
  1971. * Called by Grid to generate a style name for a column.
  1972. *
  1973. * @param cell
  1974. * the cell to generate a style for
  1975. * @return the style name to add to this cell, or {@code null} to not
  1976. * set any style
  1977. */
  1978. public String getStyle(CellReference cell);
  1979. }
  1980. /**
  1981. * A callback interface for generating optional descriptions (tooltips) for
  1982. * Grid rows. If a description is generated for a row, it is used for all
  1983. * the cells in the row for which a {@link CellDescriptionGenerator cell
  1984. * description} is not generated.
  1985. *
  1986. * @see Grid#setRowDescriptionGenerator
  1987. *
  1988. * @since 7.6
  1989. */
  1990. @Deprecated
  1991. public interface RowDescriptionGenerator extends Serializable {
  1992. /**
  1993. * Called by Grid to generate a description (tooltip) for a row. The
  1994. * description may contain HTML which is rendered directly; if this is
  1995. * not desired the returned string must be escaped by the implementing
  1996. * method.
  1997. *
  1998. * @param row
  1999. * the row to generate a description for
  2000. * @return the row description or {@code null} for no description
  2001. */
  2002. public String getDescription(RowReference row);
  2003. }
  2004. /**
  2005. * A callback interface for generating optional descriptions (tooltips) for
  2006. * Grid cells. If a cell has both a {@link RowDescriptionGenerator row
  2007. * description} and a cell description, the latter has precedence.
  2008. *
  2009. * @see Grid#setCellDescriptionGenerator(CellDescriptionGenerator)
  2010. *
  2011. * @since 7.6
  2012. */
  2013. @Deprecated
  2014. public interface CellDescriptionGenerator extends Serializable {
  2015. /**
  2016. * Called by Grid to generate a description (tooltip) for a cell. The
  2017. * description may contain HTML which is rendered directly; if this is
  2018. * not desired the returned string must be escaped by the implementing
  2019. * method.
  2020. *
  2021. * @param cell
  2022. * the cell to generate a description for
  2023. * @return the cell description or {@code null} for no description
  2024. */
  2025. public String getDescription(CellReference cell);
  2026. }
  2027. /**
  2028. * Class for generating all row and cell related data for the essential
  2029. * parts of Grid.
  2030. */
  2031. private class RowDataGenerator implements DataGenerator {
  2032. private void put(String key, String value, JsonObject object) {
  2033. if (value != null && !value.isEmpty()) {
  2034. object.put(key, value);
  2035. }
  2036. }
  2037. @Override
  2038. public void generateData(Object itemId, Item item, JsonObject rowData) {
  2039. RowReference row = new RowReference(Grid.this);
  2040. row.set(itemId);
  2041. if (rowStyleGenerator != null) {
  2042. String style = rowStyleGenerator.getStyle(row);
  2043. put(GridState.JSONKEY_ROWSTYLE, style, rowData);
  2044. }
  2045. if (rowDescriptionGenerator != null) {
  2046. String description = rowDescriptionGenerator
  2047. .getDescription(row);
  2048. put(GridState.JSONKEY_ROWDESCRIPTION, description, rowData);
  2049. }
  2050. JsonObject cellStyles = Json.createObject();
  2051. JsonObject cellData = Json.createObject();
  2052. JsonObject cellDescriptions = Json.createObject();
  2053. CellReference cell = new CellReference(row);
  2054. for (Column column : getColumns()) {
  2055. cell.set(column.getPropertyId());
  2056. writeData(cell, cellData);
  2057. writeStyles(cell, cellStyles);
  2058. writeDescriptions(cell, cellDescriptions);
  2059. }
  2060. if (cellDescriptionGenerator != null
  2061. && cellDescriptions.keys().length > 0) {
  2062. rowData.put(GridState.JSONKEY_CELLDESCRIPTION,
  2063. cellDescriptions);
  2064. }
  2065. if (cellStyleGenerator != null && cellStyles.keys().length > 0) {
  2066. rowData.put(GridState.JSONKEY_CELLSTYLES, cellStyles);
  2067. }
  2068. rowData.put(GridState.JSONKEY_DATA, cellData);
  2069. }
  2070. private void writeStyles(CellReference cell, JsonObject styles) {
  2071. if (cellStyleGenerator != null) {
  2072. String style = cellStyleGenerator.getStyle(cell);
  2073. put(columnKeys.key(cell.getPropertyId()), style, styles);
  2074. }
  2075. }
  2076. private void writeDescriptions(CellReference cell,
  2077. JsonObject descriptions) {
  2078. if (cellDescriptionGenerator != null) {
  2079. String description = cellDescriptionGenerator
  2080. .getDescription(cell);
  2081. put(columnKeys.key(cell.getPropertyId()), description,
  2082. descriptions);
  2083. }
  2084. }
  2085. private void writeData(CellReference cell, JsonObject data) {
  2086. Column column = getColumn(cell.getPropertyId());
  2087. Converter<?, ?> converter = column.getConverter();
  2088. Renderer<?> renderer = column.getRenderer();
  2089. Item item = cell.getItem();
  2090. Property itemProperty = item.getItemProperty(cell.getPropertyId());
  2091. Object modelValue = itemProperty == null ? null
  2092. : itemProperty.getValue();
  2093. data.put(columnKeys.key(cell.getPropertyId()), AbstractRenderer
  2094. .encodeValue(modelValue, renderer, converter, getLocale()));
  2095. }
  2096. @Override
  2097. public void destroyData(Object itemId) {
  2098. // NO-OP
  2099. }
  2100. }
  2101. /**
  2102. * Abstract base class for Grid header and footer sections.
  2103. *
  2104. * @since 7.6
  2105. * @param <ROWTYPE>
  2106. * the type of the rows in the section
  2107. */
  2108. @Deprecated
  2109. public abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>>
  2110. implements Serializable {
  2111. /**
  2112. * Abstract base class for Grid header and footer rows.
  2113. *
  2114. * @param <CELLTYPE>
  2115. * the type of the cells in the row
  2116. */
  2117. @Deprecated
  2118. public abstract static class StaticRow<CELLTYPE extends StaticCell>
  2119. implements Serializable {
  2120. private RowState rowState = new RowState();
  2121. protected StaticSection<?> section;
  2122. private Map<Object, CELLTYPE> cells = new LinkedHashMap<Object, CELLTYPE>();
  2123. private Map<Set<CELLTYPE>, CELLTYPE> cellGroups = new HashMap<Set<CELLTYPE>, CELLTYPE>();
  2124. protected StaticRow(StaticSection<?> section) {
  2125. this.section = section;
  2126. }
  2127. protected void addCell(Object propertyId) {
  2128. CELLTYPE cell = createCell();
  2129. cell.setColumnId(
  2130. section.grid.getColumn(propertyId).getState().id);
  2131. cells.put(propertyId, cell);
  2132. rowState.cells.add(cell.getCellState());
  2133. }
  2134. protected void removeCell(Object propertyId) {
  2135. CELLTYPE cell = cells.remove(propertyId);
  2136. if (cell != null) {
  2137. Set<CELLTYPE> cellGroupForCell = getCellGroupForCell(cell);
  2138. if (cellGroupForCell != null) {
  2139. removeCellFromGroup(cell, cellGroupForCell);
  2140. }
  2141. rowState.cells.remove(cell.getCellState());
  2142. }
  2143. }
  2144. private void removeCellFromGroup(CELLTYPE cell,
  2145. Set<CELLTYPE> cellGroup) {
  2146. String columnId = cell.getColumnId();
  2147. for (Set<String> group : rowState.cellGroups.keySet()) {
  2148. if (group.contains(columnId)) {
  2149. if (group.size() > 2) {
  2150. // Update map key correctly
  2151. CELLTYPE mergedCell = cellGroups.remove(cellGroup);
  2152. cellGroup.remove(cell);
  2153. cellGroups.put(cellGroup, mergedCell);
  2154. group.remove(columnId);
  2155. } else {
  2156. rowState.cellGroups.remove(group);
  2157. cellGroups.remove(cellGroup);
  2158. }
  2159. return;
  2160. }
  2161. }
  2162. }
  2163. /**
  2164. * Creates and returns a new instance of the cell type.
  2165. *
  2166. * @return the created cell
  2167. */
  2168. protected abstract CELLTYPE createCell();
  2169. protected RowState getRowState() {
  2170. return rowState;
  2171. }
  2172. /**
  2173. * Returns the cell for the given property id on this row. If the
  2174. * column is merged returned cell is the cell for the whole group.
  2175. *
  2176. * @param propertyId
  2177. * the property id of the column
  2178. * @return the cell for the given property, merged cell for merged
  2179. * properties, null if not found
  2180. */
  2181. public CELLTYPE getCell(Object propertyId) {
  2182. CELLTYPE cell = cells.get(propertyId);
  2183. Set<CELLTYPE> cellGroup = getCellGroupForCell(cell);
  2184. if (cellGroup != null) {
  2185. cell = cellGroups.get(cellGroup);
  2186. }
  2187. return cell;
  2188. }
  2189. /**
  2190. * Merges columns cells in a row.
  2191. *
  2192. * @param propertyIds
  2193. * The property ids of columns to merge
  2194. * @return The remaining visible cell after the merge
  2195. */
  2196. public CELLTYPE join(Object... propertyIds) {
  2197. if (propertyIds.length < 2) {
  2198. throw new IllegalArgumentException(
  2199. "You need to merge at least 2 properties");
  2200. }
  2201. Set<CELLTYPE> cells = new HashSet<CELLTYPE>();
  2202. for (int i = 0; i < propertyIds.length; ++i) {
  2203. cells.add(getCell(propertyIds[i]));
  2204. }
  2205. return join(cells);
  2206. }
  2207. /**
  2208. * Merges columns cells in a row.
  2209. *
  2210. * @param cells
  2211. * The cells to merge. Must be from the same row.
  2212. * @return The remaining visible cell after the merge
  2213. */
  2214. public CELLTYPE join(CELLTYPE... cells) {
  2215. if (cells.length < 2) {
  2216. throw new IllegalArgumentException(
  2217. "You need to merge at least 2 cells");
  2218. }
  2219. return join(new HashSet<CELLTYPE>(Arrays.asList(cells)));
  2220. }
  2221. protected CELLTYPE join(Set<CELLTYPE> cells) {
  2222. for (CELLTYPE cell : cells) {
  2223. if (getCellGroupForCell(cell) != null) {
  2224. throw new IllegalArgumentException(
  2225. "Cell already merged");
  2226. } else if (!this.cells.containsValue(cell)) {
  2227. throw new IllegalArgumentException(
  2228. "Cell does not exist on this row");
  2229. }
  2230. }
  2231. // Create new cell data for the group
  2232. CELLTYPE newCell = createCell();
  2233. Set<String> columnGroup = new HashSet<String>();
  2234. for (CELLTYPE cell : cells) {
  2235. columnGroup.add(cell.getColumnId());
  2236. }
  2237. rowState.cellGroups.put(columnGroup, newCell.getCellState());
  2238. cellGroups.put(cells, newCell);
  2239. return newCell;
  2240. }
  2241. private Set<CELLTYPE> getCellGroupForCell(CELLTYPE cell) {
  2242. for (Set<CELLTYPE> group : cellGroups.keySet()) {
  2243. if (group.contains(cell)) {
  2244. return group;
  2245. }
  2246. }
  2247. return null;
  2248. }
  2249. /**
  2250. * Returns the custom style name for this row.
  2251. *
  2252. * @return the style name or null if no style name has been set
  2253. */
  2254. public String getStyleName() {
  2255. return getRowState().styleName;
  2256. }
  2257. /**
  2258. * Sets a custom style name for this row.
  2259. *
  2260. * @param styleName
  2261. * the style name to set or null to not use any style
  2262. * name
  2263. */
  2264. public void setStyleName(String styleName) {
  2265. getRowState().styleName = styleName;
  2266. }
  2267. /**
  2268. * Writes the declarative design to the given table row element.
  2269. *
  2270. * @since 7.5.0
  2271. * @param trElement
  2272. * Element to write design to
  2273. * @param designContext
  2274. * the design context
  2275. */
  2276. protected void writeDesign(Element trElement,
  2277. DesignContext designContext) {
  2278. Set<CELLTYPE> visited = new HashSet<CELLTYPE>();
  2279. for (Grid.Column column : section.grid.getColumns()) {
  2280. CELLTYPE cell = getCell(column.getPropertyId());
  2281. if (visited.contains(cell)) {
  2282. continue;
  2283. }
  2284. visited.add(cell);
  2285. Element cellElement = trElement
  2286. .appendElement(getCellTagName());
  2287. cell.writeDesign(cellElement, designContext);
  2288. for (Entry<Set<CELLTYPE>, CELLTYPE> entry : cellGroups
  2289. .entrySet()) {
  2290. if (entry.getValue() == cell) {
  2291. cellElement.attr("colspan",
  2292. "" + entry.getKey().size());
  2293. break;
  2294. }
  2295. }
  2296. }
  2297. }
  2298. /**
  2299. * Reads the declarative design from the given table row element.
  2300. *
  2301. * @since 7.5.0
  2302. * @param trElement
  2303. * Element to read design from
  2304. * @param designContext
  2305. * the design context
  2306. * @throws DesignException
  2307. * if the given table row contains unexpected children
  2308. */
  2309. protected void readDesign(Element trElement,
  2310. DesignContext designContext) throws DesignException {
  2311. Elements cellElements = trElement.children();
  2312. int totalColSpans = 0;
  2313. for (int i = 0; i < cellElements.size(); ++i) {
  2314. Element element = cellElements.get(i);
  2315. if (!element.tagName().equals(getCellTagName())) {
  2316. throw new DesignException(
  2317. "Unexpected element in tr while expecting "
  2318. + getCellTagName() + ": "
  2319. + element.tagName());
  2320. }
  2321. int columnIndex = i + totalColSpans;
  2322. int colspan = DesignAttributeHandler.readAttribute(
  2323. "colspan", element.attributes(), 1, int.class);
  2324. Set<CELLTYPE> cells = new HashSet<CELLTYPE>();
  2325. for (int c = 0; c < colspan; ++c) {
  2326. cells.add(getCell(section.grid.getColumns()
  2327. .get(columnIndex + c).getPropertyId()));
  2328. }
  2329. if (colspan > 1) {
  2330. totalColSpans += colspan - 1;
  2331. join(cells).readDesign(element, designContext);
  2332. } else {
  2333. cells.iterator().next().readDesign(element,
  2334. designContext);
  2335. }
  2336. }
  2337. }
  2338. protected abstract String getCellTagName();
  2339. void detach() {
  2340. for (CELLTYPE cell : cells.values()) {
  2341. cell.detach();
  2342. }
  2343. for (CELLTYPE cell : cellGroups.values()) {
  2344. cell.detach();
  2345. }
  2346. }
  2347. }
  2348. /**
  2349. * A header or footer cell. Has a simple textual caption.
  2350. */
  2351. @Deprecated
  2352. abstract static class StaticCell implements Serializable {
  2353. private CellState cellState = new CellState();
  2354. private StaticRow<?> row;
  2355. protected StaticCell(StaticRow<?> row) {
  2356. this.row = row;
  2357. }
  2358. void setColumnId(String id) {
  2359. cellState.columnId = id;
  2360. }
  2361. String getColumnId() {
  2362. return cellState.columnId;
  2363. }
  2364. /**
  2365. * Gets the row where this cell is.
  2366. *
  2367. * @return row for this cell
  2368. */
  2369. public StaticRow<?> getRow() {
  2370. return row;
  2371. }
  2372. protected CellState getCellState() {
  2373. return cellState;
  2374. }
  2375. /**
  2376. * Sets the text displayed in this cell.
  2377. *
  2378. * @param text
  2379. * a plain text caption
  2380. */
  2381. public void setText(String text) {
  2382. removeComponentIfPresent();
  2383. cellState.text = text;
  2384. cellState.type = GridStaticCellType.TEXT;
  2385. row.section.markAsDirty();
  2386. }
  2387. /**
  2388. * Returns the text displayed in this cell.
  2389. *
  2390. * @return the plain text caption
  2391. */
  2392. public String getText() {
  2393. if (cellState.type != GridStaticCellType.TEXT) {
  2394. throw new IllegalStateException(
  2395. "Cannot fetch Text from a cell with type "
  2396. + cellState.type);
  2397. }
  2398. return cellState.text;
  2399. }
  2400. /**
  2401. * Returns the HTML content displayed in this cell.
  2402. *
  2403. * @return the html
  2404. *
  2405. */
  2406. public String getHtml() {
  2407. if (cellState.type != GridStaticCellType.HTML) {
  2408. throw new IllegalStateException(
  2409. "Cannot fetch HTML from a cell with type "
  2410. + cellState.type);
  2411. }
  2412. return cellState.html;
  2413. }
  2414. /**
  2415. * Sets the HTML content displayed in this cell.
  2416. *
  2417. * @param html
  2418. * the html to set
  2419. */
  2420. public void setHtml(String html) {
  2421. removeComponentIfPresent();
  2422. cellState.html = html;
  2423. cellState.type = GridStaticCellType.HTML;
  2424. row.section.markAsDirty();
  2425. }
  2426. /**
  2427. * Returns the component displayed in this cell.
  2428. *
  2429. * @return the component
  2430. */
  2431. public Component getComponent() {
  2432. if (cellState.type != GridStaticCellType.WIDGET) {
  2433. throw new IllegalStateException(
  2434. "Cannot fetch Component from a cell with type "
  2435. + cellState.type);
  2436. }
  2437. return (Component) cellState.connector;
  2438. }
  2439. /**
  2440. * Sets the component displayed in this cell.
  2441. *
  2442. * @param component
  2443. * the component to set
  2444. */
  2445. public void setComponent(Component component) {
  2446. removeComponentIfPresent();
  2447. component.setParent(row.section.grid);
  2448. cellState.connector = component;
  2449. cellState.type = GridStaticCellType.WIDGET;
  2450. row.section.markAsDirty();
  2451. }
  2452. /**
  2453. * Returns the type of content stored in this cell.
  2454. *
  2455. * @return cell content type
  2456. */
  2457. public GridStaticCellType getCellType() {
  2458. return cellState.type;
  2459. }
  2460. /**
  2461. * Returns the custom style name for this cell.
  2462. *
  2463. * @return the style name or null if no style name has been set
  2464. */
  2465. public String getStyleName() {
  2466. return cellState.styleName;
  2467. }
  2468. /**
  2469. * Sets a custom style name for this cell.
  2470. *
  2471. * @param styleName
  2472. * the style name to set or null to not use any style
  2473. * name
  2474. */
  2475. public void setStyleName(String styleName) {
  2476. cellState.styleName = styleName;
  2477. row.section.markAsDirty();
  2478. }
  2479. private void removeComponentIfPresent() {
  2480. Component component = (Component) cellState.connector;
  2481. if (component != null) {
  2482. component.setParent(null);
  2483. cellState.connector = null;
  2484. }
  2485. }
  2486. /**
  2487. * Writes the declarative design to the given table cell element.
  2488. *
  2489. * @since 7.5.0
  2490. * @param cellElement
  2491. * Element to write design to
  2492. * @param designContext
  2493. * the design context
  2494. */
  2495. protected void writeDesign(Element cellElement,
  2496. DesignContext designContext) {
  2497. switch (cellState.type) {
  2498. case TEXT:
  2499. cellElement.attr("plain-text", true);
  2500. cellElement.appendText(getText());
  2501. break;
  2502. case HTML:
  2503. cellElement.append(getHtml());
  2504. break;
  2505. case WIDGET:
  2506. cellElement.appendChild(
  2507. designContext.createElement(getComponent()));
  2508. break;
  2509. }
  2510. }
  2511. /**
  2512. * Reads the declarative design from the given table cell element.
  2513. *
  2514. * @since 7.5.0
  2515. * @param cellElement
  2516. * Element to read design from
  2517. * @param designContext
  2518. * the design context
  2519. */
  2520. protected void readDesign(Element cellElement,
  2521. DesignContext designContext) {
  2522. if (!cellElement.hasAttr("plain-text")) {
  2523. if (cellElement.children().size() > 0
  2524. && cellElement.child(0).tagName().contains("-")) {
  2525. setComponent(
  2526. designContext.readDesign(cellElement.child(0)));
  2527. } else {
  2528. setHtml(cellElement.html());
  2529. }
  2530. } else {
  2531. // text – need to unescape HTML entities
  2532. setText(DesignFormatter
  2533. .decodeFromTextNode(cellElement.html()));
  2534. }
  2535. }
  2536. void detach() {
  2537. removeComponentIfPresent();
  2538. }
  2539. }
  2540. protected Grid grid;
  2541. protected List<ROWTYPE> rows = new ArrayList<ROWTYPE>();
  2542. /**
  2543. * Sets the visibility of the whole section.
  2544. *
  2545. * @param visible
  2546. * true to show this section, false to hide
  2547. */
  2548. public void setVisible(boolean visible) {
  2549. if (getSectionState().visible != visible) {
  2550. getSectionState().visible = visible;
  2551. markAsDirty();
  2552. }
  2553. }
  2554. /**
  2555. * Returns the visibility of this section.
  2556. *
  2557. * @return true if visible, false otherwise.
  2558. */
  2559. public boolean isVisible() {
  2560. return getSectionState().visible;
  2561. }
  2562. /**
  2563. * Removes the row at the given position.
  2564. *
  2565. * @param rowIndex
  2566. * the position of the row
  2567. *
  2568. * @throws IllegalArgumentException
  2569. * if no row exists at given index
  2570. * @see #removeRow(StaticRow)
  2571. * @see #addRowAt(int)
  2572. * @see #appendRow()
  2573. * @see #prependRow()
  2574. */
  2575. public ROWTYPE removeRow(int rowIndex) {
  2576. if (rowIndex >= rows.size() || rowIndex < 0) {
  2577. throw new IllegalArgumentException(
  2578. "No row at given index " + rowIndex);
  2579. }
  2580. ROWTYPE row = rows.remove(rowIndex);
  2581. row.detach();
  2582. getSectionState().rows.remove(rowIndex);
  2583. markAsDirty();
  2584. return row;
  2585. }
  2586. /**
  2587. * Removes the given row from the section.
  2588. *
  2589. * @param row
  2590. * the row to be removed
  2591. *
  2592. * @throws IllegalArgumentException
  2593. * if the row does not exist in this section
  2594. * @see #removeRow(int)
  2595. * @see #addRowAt(int)
  2596. * @see #appendRow()
  2597. * @see #prependRow()
  2598. */
  2599. public void removeRow(ROWTYPE row) {
  2600. try {
  2601. removeRow(rows.indexOf(row));
  2602. } catch (IndexOutOfBoundsException e) {
  2603. throw new IllegalArgumentException(
  2604. "Section does not contain the given row");
  2605. }
  2606. }
  2607. /**
  2608. * Gets row at given index.
  2609. *
  2610. * @param rowIndex
  2611. * 0 based index for row. Counted from top to bottom
  2612. * @return row at given index
  2613. */
  2614. public ROWTYPE getRow(int rowIndex) {
  2615. if (rowIndex >= rows.size() || rowIndex < 0) {
  2616. throw new IllegalArgumentException(
  2617. "No row at given index " + rowIndex);
  2618. }
  2619. return rows.get(rowIndex);
  2620. }
  2621. /**
  2622. * Adds a new row at the top of this section.
  2623. *
  2624. * @return the new row
  2625. * @see #appendRow()
  2626. * @see #addRowAt(int)
  2627. * @see #removeRow(StaticRow)
  2628. * @see #removeRow(int)
  2629. */
  2630. public ROWTYPE prependRow() {
  2631. return addRowAt(0);
  2632. }
  2633. /**
  2634. * Adds a new row at the bottom of this section.
  2635. *
  2636. * @return the new row
  2637. * @see #prependRow()
  2638. * @see #addRowAt(int)
  2639. * @see #removeRow(StaticRow)
  2640. * @see #removeRow(int)
  2641. */
  2642. public ROWTYPE appendRow() {
  2643. return addRowAt(rows.size());
  2644. }
  2645. /**
  2646. * Inserts a new row at the given position.
  2647. *
  2648. * @param index
  2649. * the position at which to insert the row
  2650. * @return the new row
  2651. *
  2652. * @throws IndexOutOfBoundsException
  2653. * if the index is out of bounds
  2654. * @see #appendRow()
  2655. * @see #prependRow()
  2656. * @see #removeRow(StaticRow)
  2657. * @see #removeRow(int)
  2658. */
  2659. public ROWTYPE addRowAt(int index) {
  2660. if (index > rows.size() || index < 0) {
  2661. throw new IllegalArgumentException(
  2662. "Unable to add row at index " + index);
  2663. }
  2664. ROWTYPE row = createRow();
  2665. rows.add(index, row);
  2666. getSectionState().rows.add(index, row.getRowState());
  2667. for (Object id : grid.columns.keySet()) {
  2668. row.addCell(id);
  2669. }
  2670. markAsDirty();
  2671. return row;
  2672. }
  2673. /**
  2674. * Gets the amount of rows in this section.
  2675. *
  2676. * @return row count
  2677. */
  2678. public int getRowCount() {
  2679. return rows.size();
  2680. }
  2681. protected abstract GridStaticSectionState getSectionState();
  2682. protected abstract ROWTYPE createRow();
  2683. /**
  2684. * Informs the grid that state has changed and it should be redrawn.
  2685. */
  2686. protected void markAsDirty() {
  2687. grid.markAsDirty();
  2688. }
  2689. /**
  2690. * Removes a column for given property id from the section.
  2691. *
  2692. * @param propertyId
  2693. * property to be removed
  2694. */
  2695. protected void removeColumn(Object propertyId) {
  2696. for (ROWTYPE row : rows) {
  2697. row.removeCell(propertyId);
  2698. }
  2699. }
  2700. /**
  2701. * Adds a column for given property id to the section.
  2702. *
  2703. * @param propertyId
  2704. * property to be added
  2705. */
  2706. protected void addColumn(Object propertyId) {
  2707. for (ROWTYPE row : rows) {
  2708. row.addCell(propertyId);
  2709. }
  2710. }
  2711. /**
  2712. * Performs a sanity check that section is in correct state.
  2713. *
  2714. * @throws IllegalStateException
  2715. * if merged cells are not i n continuous range
  2716. */
  2717. protected void sanityCheck() throws IllegalStateException {
  2718. List<String> columnOrder = grid.getState().columnOrder;
  2719. for (ROWTYPE row : rows) {
  2720. for (Set<String> cellGroup : row.getRowState().cellGroups
  2721. .keySet()) {
  2722. if (!checkCellGroupAndOrder(columnOrder, cellGroup)) {
  2723. throw new IllegalStateException(
  2724. "Not all merged cells were in a continuous range.");
  2725. }
  2726. }
  2727. }
  2728. }
  2729. private boolean checkCellGroupAndOrder(List<String> columnOrder,
  2730. Set<String> cellGroup) {
  2731. if (!columnOrder.containsAll(cellGroup)) {
  2732. return false;
  2733. }
  2734. for (int i = 0; i < columnOrder.size(); ++i) {
  2735. if (!cellGroup.contains(columnOrder.get(i))) {
  2736. continue;
  2737. }
  2738. for (int j = 1; j < cellGroup.size(); ++j) {
  2739. if (!cellGroup.contains(columnOrder.get(i + j))) {
  2740. return false;
  2741. }
  2742. }
  2743. return true;
  2744. }
  2745. return false;
  2746. }
  2747. /**
  2748. * Writes the declarative design to the given table section element.
  2749. *
  2750. * @since 7.5.0
  2751. * @param tableSectionElement
  2752. * Element to write design to
  2753. * @param designContext
  2754. * the design context
  2755. */
  2756. protected void writeDesign(Element tableSectionElement,
  2757. DesignContext designContext) {
  2758. for (ROWTYPE row : rows) {
  2759. row.writeDesign(tableSectionElement.appendElement("tr"),
  2760. designContext);
  2761. }
  2762. }
  2763. /**
  2764. * Writes the declarative design from the given table section element.
  2765. *
  2766. * @since 7.5.0
  2767. * @param tableSectionElement
  2768. * Element to read design from
  2769. * @param designContext
  2770. * the design context
  2771. * @throws DesignException
  2772. * if the table section contains unexpected children
  2773. */
  2774. protected void readDesign(Element tableSectionElement,
  2775. DesignContext designContext) throws DesignException {
  2776. while (rows.size() > 0) {
  2777. removeRow(0);
  2778. }
  2779. for (Element row : tableSectionElement.children()) {
  2780. if (!row.tagName().equals("tr")) {
  2781. throw new DesignException("Unexpected element in "
  2782. + tableSectionElement.tagName() + ": "
  2783. + row.tagName());
  2784. }
  2785. appendRow().readDesign(row, designContext);
  2786. }
  2787. }
  2788. }
  2789. /**
  2790. * Represents the header section of a Grid.
  2791. */
  2792. @Deprecated
  2793. protected static class Header extends StaticSection<HeaderRow> {
  2794. private HeaderRow defaultRow = null;
  2795. private final GridStaticSectionState headerState = new GridStaticSectionState();
  2796. protected Header(Grid grid) {
  2797. this.grid = grid;
  2798. grid.getState(true).header = headerState;
  2799. HeaderRow row = createRow();
  2800. rows.add(row);
  2801. setDefaultRow(row);
  2802. getSectionState().rows.add(row.getRowState());
  2803. }
  2804. /**
  2805. * Sets the default row of this header. The default row is a special
  2806. * header row providing a user interface for sorting columns.
  2807. *
  2808. * @param row
  2809. * the new default row, or null for no default row
  2810. *
  2811. * @throws IllegalArgumentException
  2812. * this header does not contain the row
  2813. */
  2814. public void setDefaultRow(HeaderRow row) {
  2815. if (row == defaultRow) {
  2816. return;
  2817. }
  2818. if (row != null && !rows.contains(row)) {
  2819. throw new IllegalArgumentException(
  2820. "Cannot set a default row that does not exist in the section");
  2821. }
  2822. if (defaultRow != null) {
  2823. defaultRow.setDefaultRow(false);
  2824. }
  2825. if (row != null) {
  2826. row.setDefaultRow(true);
  2827. }
  2828. defaultRow = row;
  2829. markAsDirty();
  2830. }
  2831. /**
  2832. * Returns the current default row of this header. The default row is a
  2833. * special header row providing a user interface for sorting columns.
  2834. *
  2835. * @return the default row or null if no default row set
  2836. */
  2837. public HeaderRow getDefaultRow() {
  2838. return defaultRow;
  2839. }
  2840. @Override
  2841. protected GridStaticSectionState getSectionState() {
  2842. return headerState;
  2843. }
  2844. @Override
  2845. protected HeaderRow createRow() {
  2846. return new HeaderRow(this);
  2847. }
  2848. @Override
  2849. public HeaderRow removeRow(int rowIndex) {
  2850. HeaderRow row = super.removeRow(rowIndex);
  2851. if (row == defaultRow) {
  2852. // Default Header Row was just removed.
  2853. setDefaultRow(null);
  2854. }
  2855. return row;
  2856. }
  2857. @Override
  2858. protected void sanityCheck() throws IllegalStateException {
  2859. super.sanityCheck();
  2860. boolean hasDefaultRow = false;
  2861. for (HeaderRow row : rows) {
  2862. if (row.getRowState().defaultRow) {
  2863. if (!hasDefaultRow) {
  2864. hasDefaultRow = true;
  2865. } else {
  2866. throw new IllegalStateException(
  2867. "Multiple default rows in header");
  2868. }
  2869. }
  2870. }
  2871. }
  2872. @Override
  2873. protected void readDesign(Element tableSectionElement,
  2874. DesignContext designContext) {
  2875. super.readDesign(tableSectionElement, designContext);
  2876. if (defaultRow == null && !rows.isEmpty()) {
  2877. grid.setDefaultHeaderRow(rows.get(0));
  2878. }
  2879. }
  2880. }
  2881. /**
  2882. * Represents a header row in Grid.
  2883. */
  2884. @Deprecated
  2885. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  2886. protected HeaderRow(StaticSection<?> section) {
  2887. super(section);
  2888. }
  2889. private void setDefaultRow(boolean value) {
  2890. getRowState().defaultRow = value;
  2891. }
  2892. @Override
  2893. protected HeaderCell createCell() {
  2894. return new HeaderCell(this);
  2895. }
  2896. @Override
  2897. protected String getCellTagName() {
  2898. return "th";
  2899. }
  2900. @Override
  2901. protected void writeDesign(Element trElement,
  2902. DesignContext designContext) {
  2903. super.writeDesign(trElement, designContext);
  2904. if (section.grid.getDefaultHeaderRow() == this) {
  2905. DesignAttributeHandler.writeAttribute("default",
  2906. trElement.attributes(), true, null, boolean.class,
  2907. designContext);
  2908. }
  2909. }
  2910. @Override
  2911. protected void readDesign(Element trElement,
  2912. DesignContext designContext) {
  2913. super.readDesign(trElement, designContext);
  2914. boolean defaultRow = DesignAttributeHandler.readAttribute("default",
  2915. trElement.attributes(), false, boolean.class);
  2916. if (defaultRow) {
  2917. section.grid.setDefaultHeaderRow(this);
  2918. }
  2919. }
  2920. }
  2921. /**
  2922. * Represents a header cell in Grid. Can be a merged cell for multiple
  2923. * columns.
  2924. */
  2925. @Deprecated
  2926. public static class HeaderCell extends StaticSection.StaticCell {
  2927. protected HeaderCell(HeaderRow row) {
  2928. super(row);
  2929. }
  2930. }
  2931. /**
  2932. * Represents the footer section of a Grid. By default Footer is not
  2933. * visible.
  2934. */
  2935. @Deprecated
  2936. protected static class Footer extends StaticSection<FooterRow> {
  2937. private final GridStaticSectionState footerState = new GridStaticSectionState();
  2938. protected Footer(Grid grid) {
  2939. this.grid = grid;
  2940. grid.getState(true).footer = footerState;
  2941. }
  2942. @Override
  2943. protected GridStaticSectionState getSectionState() {
  2944. return footerState;
  2945. }
  2946. @Override
  2947. protected FooterRow createRow() {
  2948. return new FooterRow(this);
  2949. }
  2950. @Override
  2951. protected void sanityCheck() throws IllegalStateException {
  2952. super.sanityCheck();
  2953. }
  2954. }
  2955. /**
  2956. * Represents a footer row in Grid.
  2957. */
  2958. @Deprecated
  2959. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  2960. protected FooterRow(StaticSection<?> section) {
  2961. super(section);
  2962. }
  2963. @Override
  2964. protected FooterCell createCell() {
  2965. return new FooterCell(this);
  2966. }
  2967. @Override
  2968. protected String getCellTagName() {
  2969. return "td";
  2970. }
  2971. }
  2972. /**
  2973. * Represents a footer cell in Grid.
  2974. */
  2975. @Deprecated
  2976. public static class FooterCell extends StaticSection.StaticCell {
  2977. protected FooterCell(FooterRow row) {
  2978. super(row);
  2979. }
  2980. }
  2981. /**
  2982. * A column in the grid. Can be obtained by calling
  2983. * {@link Grid#getColumn(Object propertyId)}.
  2984. */
  2985. @Deprecated
  2986. public static class Column implements Serializable {
  2987. /**
  2988. * The state of the column shared to the client
  2989. */
  2990. private final GridColumnState state;
  2991. /**
  2992. * The grid this column is associated with
  2993. */
  2994. private final Grid grid;
  2995. /**
  2996. * Backing property for column
  2997. */
  2998. private final Object propertyId;
  2999. private Converter<?, Object> converter;
  3000. /**
  3001. * A check for allowing the
  3002. * {@link #Column(Grid, GridColumnState, Object) constructor} to call
  3003. * {@link #setConverter(Converter)} with a <code>null</code>, even if
  3004. * model and renderer aren't compatible.
  3005. */
  3006. private boolean isFirstConverterAssignment = true;
  3007. /**
  3008. * Internally used constructor.
  3009. *
  3010. * @param grid
  3011. * The grid this column belongs to. Should not be null.
  3012. * @param state
  3013. * the shared state of this column
  3014. * @param propertyId
  3015. * the backing property id for this column
  3016. */
  3017. Column(Grid grid, GridColumnState state, Object propertyId) {
  3018. this.grid = grid;
  3019. this.state = state;
  3020. this.propertyId = propertyId;
  3021. internalSetRenderer(new TextRenderer());
  3022. }
  3023. /**
  3024. * Returns the serializable state of this column that is sent to the
  3025. * client side connector.
  3026. *
  3027. * @return the internal state of the column
  3028. */
  3029. GridColumnState getState() {
  3030. return state;
  3031. }
  3032. /**
  3033. * Returns the property id for the backing property of this Column
  3034. *
  3035. * @return property id
  3036. */
  3037. public Object getPropertyId() {
  3038. return propertyId;
  3039. }
  3040. /**
  3041. * Returns the caption of the header. By default the header caption is
  3042. * the property id of the column.
  3043. *
  3044. * @return the text in the default row of header.
  3045. *
  3046. * @throws IllegalStateException
  3047. * if the column no longer is attached to the grid
  3048. */
  3049. public String getHeaderCaption() throws IllegalStateException {
  3050. checkColumnIsAttached();
  3051. return state.headerCaption;
  3052. }
  3053. /**
  3054. * Sets the caption of the header. This caption is also used as the
  3055. * hiding toggle caption, unless it is explicitly set via
  3056. * {@link #setHidingToggleCaption(String)}.
  3057. *
  3058. * @param caption
  3059. * the text to show in the caption
  3060. * @return the column itself
  3061. *
  3062. * @throws IllegalStateException
  3063. * if the column is no longer attached to any grid
  3064. */
  3065. public Column setHeaderCaption(String caption)
  3066. throws IllegalStateException {
  3067. checkColumnIsAttached();
  3068. if (caption == null) {
  3069. caption = ""; // Render null as empty
  3070. }
  3071. state.headerCaption = caption;
  3072. HeaderRow row = grid.getHeader().getDefaultRow();
  3073. if (row != null) {
  3074. row.getCell(grid.getPropertyIdByColumnId(state.id))
  3075. .setText(caption);
  3076. }
  3077. return this;
  3078. }
  3079. /**
  3080. * Gets the caption of the hiding toggle for this column.
  3081. *
  3082. * @since 7.5.0
  3083. * @see #setHidingToggleCaption(String)
  3084. * @return the caption for the hiding toggle for this column
  3085. * @throws IllegalStateException
  3086. * if the column is no longer attached to any grid
  3087. */
  3088. public String getHidingToggleCaption() throws IllegalStateException {
  3089. checkColumnIsAttached();
  3090. return state.hidingToggleCaption;
  3091. }
  3092. /**
  3093. * Sets the caption of the hiding toggle for this column. Shown in the
  3094. * toggle for this column in the grid's sidebar when the column is
  3095. * {@link #isHidable() hidable}.
  3096. * <p>
  3097. * The default value is <code>null</code>, and in that case the column's
  3098. * {@link #getHeaderCaption() header caption} is used.
  3099. * <p>
  3100. * <em>NOTE:</em> setting this to empty string might cause the hiding
  3101. * toggle to not render correctly.
  3102. *
  3103. * @since 7.5.0
  3104. * @param hidingToggleCaption
  3105. * the text to show in the column hiding toggle
  3106. * @return the column itself
  3107. * @throws IllegalStateException
  3108. * if the column is no longer attached to any grid
  3109. */
  3110. public Column setHidingToggleCaption(String hidingToggleCaption)
  3111. throws IllegalStateException {
  3112. checkColumnIsAttached();
  3113. state.hidingToggleCaption = hidingToggleCaption;
  3114. grid.markAsDirty();
  3115. return this;
  3116. }
  3117. /**
  3118. * Returns the width (in pixels). By default a column is 100px wide.
  3119. *
  3120. * @return the width in pixels of the column
  3121. * @throws IllegalStateException
  3122. * if the column is no longer attached to any grid
  3123. */
  3124. public double getWidth() throws IllegalStateException {
  3125. checkColumnIsAttached();
  3126. return state.width;
  3127. }
  3128. /**
  3129. * Sets the width (in pixels).
  3130. * <p>
  3131. * This overrides any configuration set by any of
  3132. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  3133. * {@link #setMaximumWidth(double)}.
  3134. *
  3135. * @param pixelWidth
  3136. * the new pixel width of the column
  3137. * @return the column itself
  3138. *
  3139. * @throws IllegalStateException
  3140. * if the column is no longer attached to any grid
  3141. * @throws IllegalArgumentException
  3142. * thrown if pixel width is less than zero
  3143. */
  3144. public Column setWidth(double pixelWidth)
  3145. throws IllegalStateException, IllegalArgumentException {
  3146. checkColumnIsAttached();
  3147. if (pixelWidth < 0) {
  3148. throw new IllegalArgumentException(
  3149. "Pixel width should be greated than 0 (in " + toString()
  3150. + ")");
  3151. }
  3152. if (state.width != pixelWidth) {
  3153. state.width = pixelWidth;
  3154. grid.markAsDirty();
  3155. grid.fireColumnResizeEvent(this, false);
  3156. }
  3157. return this;
  3158. }
  3159. /**
  3160. * Returns whether this column has an undefined width.
  3161. *
  3162. * @since 7.6
  3163. * @return whether the width is undefined
  3164. * @throws IllegalStateException
  3165. * if the column is no longer attached to any grid
  3166. */
  3167. public boolean isWidthUndefined() {
  3168. checkColumnIsAttached();
  3169. return state.width < 0;
  3170. }
  3171. /**
  3172. * Marks the column width as undefined. An undefined width means the
  3173. * grid is free to resize the column based on the cell contents and
  3174. * available space in the grid.
  3175. *
  3176. * @return the column itself
  3177. */
  3178. public Column setWidthUndefined() {
  3179. checkColumnIsAttached();
  3180. if (!isWidthUndefined()) {
  3181. state.width = -1;
  3182. grid.markAsDirty();
  3183. grid.fireColumnResizeEvent(this, false);
  3184. }
  3185. return this;
  3186. }
  3187. /**
  3188. * Checks if column is attached and throws an
  3189. * {@link IllegalStateException} if it is not
  3190. *
  3191. * @throws IllegalStateException
  3192. * if the column is no longer attached to any grid
  3193. */
  3194. protected void checkColumnIsAttached() throws IllegalStateException {
  3195. if (grid.getColumnByColumnId(state.id) == null) {
  3196. throw new IllegalStateException("Column no longer exists.");
  3197. }
  3198. }
  3199. /**
  3200. * Sets this column as the last frozen column in its grid.
  3201. *
  3202. * @return the column itself
  3203. *
  3204. * @throws IllegalArgumentException
  3205. * if the column is no longer attached to any grid
  3206. * @see Grid#setFrozenColumnCount(int)
  3207. */
  3208. public Column setLastFrozenColumn() {
  3209. checkColumnIsAttached();
  3210. grid.setFrozenColumnCount(
  3211. grid.getState(false).columnOrder.indexOf(getState().id)
  3212. + 1);
  3213. return this;
  3214. }
  3215. /**
  3216. * Sets the renderer for this column.
  3217. * <p>
  3218. * If a suitable converter isn't defined explicitly, the session
  3219. * converter factory is used to find a compatible converter.
  3220. *
  3221. * @param renderer
  3222. * the renderer to use
  3223. * @return the column itself
  3224. *
  3225. * @throws IllegalArgumentException
  3226. * if no compatible converter could be found
  3227. *
  3228. * @see VaadinSession#getConverterFactory()
  3229. * @see ConverterUtil#getConverter(Class, Class, VaadinSession)
  3230. * @see #setConverter(Converter)
  3231. */
  3232. public Column setRenderer(Renderer<?> renderer) {
  3233. if (!internalSetRenderer(renderer)) {
  3234. throw new IllegalArgumentException(
  3235. "Could not find a converter for converting from the model type "
  3236. + getModelType()
  3237. + " to the renderer presentation type "
  3238. + renderer.getPresentationType() + " (in "
  3239. + toString() + ")");
  3240. }
  3241. return this;
  3242. }
  3243. /**
  3244. * Sets the renderer for this column and the converter used to convert
  3245. * from the property value type to the renderer presentation type.
  3246. *
  3247. * @param renderer
  3248. * the renderer to use, cannot be null
  3249. * @param converter
  3250. * the converter to use
  3251. * @return the column itself
  3252. *
  3253. * @throws IllegalArgumentException
  3254. * if the renderer is already associated with a grid column
  3255. */
  3256. public <T> Column setRenderer(Renderer<T> renderer,
  3257. Converter<? extends T, ?> converter) {
  3258. if (renderer.getParent() != null) {
  3259. throw new IllegalArgumentException(
  3260. "Cannot set a renderer that is already connected to a grid column (in "
  3261. + toString() + ")");
  3262. }
  3263. if (getRenderer() != null) {
  3264. grid.removeExtension(getRenderer());
  3265. }
  3266. grid.addRenderer(renderer);
  3267. state.rendererConnector = renderer;
  3268. setConverter(converter);
  3269. return this;
  3270. }
  3271. /**
  3272. * Sets the converter used to convert from the property value type to
  3273. * the renderer presentation type.
  3274. *
  3275. * @param converter
  3276. * the converter to use, or {@code null} to not use any
  3277. * converters
  3278. * @return the column itself
  3279. *
  3280. * @throws IllegalArgumentException
  3281. * if the types are not compatible
  3282. */
  3283. public Column setConverter(Converter<?, ?> converter)
  3284. throws IllegalArgumentException {
  3285. Class<?> modelType = getModelType();
  3286. if (converter != null) {
  3287. if (!converter.getModelType().isAssignableFrom(modelType)) {
  3288. throw new IllegalArgumentException(
  3289. "The converter model type "
  3290. + converter.getModelType()
  3291. + " is not compatible with the property type "
  3292. + modelType + " (in " + toString() + ")");
  3293. } else if (!getRenderer().getPresentationType()
  3294. .isAssignableFrom(converter.getPresentationType())) {
  3295. throw new IllegalArgumentException(
  3296. "The converter presentation type "
  3297. + converter.getPresentationType()
  3298. + " is not compatible with the renderer presentation type "
  3299. + getRenderer().getPresentationType()
  3300. + " (in " + toString() + ")");
  3301. }
  3302. }
  3303. else {
  3304. /*
  3305. * Since the converter is null (i.e. will be removed), we need
  3306. * to know that the renderer and model are compatible. If not,
  3307. * we can't allow for this to happen.
  3308. *
  3309. * The constructor is allowed to call this method with null
  3310. * without any compatibility checks, therefore we have a special
  3311. * case for it.
  3312. */
  3313. Class<?> rendererPresentationType = getRenderer()
  3314. .getPresentationType();
  3315. if (!isFirstConverterAssignment && !rendererPresentationType
  3316. .isAssignableFrom(modelType)) {
  3317. throw new IllegalArgumentException(
  3318. "Cannot remove converter, "
  3319. + "as renderer's presentation type "
  3320. + rendererPresentationType.getName()
  3321. + " and column's " + "model "
  3322. + modelType.getName() + " type aren't "
  3323. + "directly compatible with each other (in "
  3324. + toString() + ")");
  3325. }
  3326. }
  3327. isFirstConverterAssignment = false;
  3328. @SuppressWarnings("unchecked")
  3329. Converter<?, Object> castConverter = (Converter<?, Object>) converter;
  3330. this.converter = castConverter;
  3331. return this;
  3332. }
  3333. /**
  3334. * Returns the renderer instance used by this column.
  3335. *
  3336. * @return the renderer
  3337. */
  3338. public Renderer<?> getRenderer() {
  3339. return (Renderer<?>) getState().rendererConnector;
  3340. }
  3341. /**
  3342. * Returns the converter instance used by this column.
  3343. *
  3344. * @return the converter
  3345. */
  3346. public Converter<?, ?> getConverter() {
  3347. return converter;
  3348. }
  3349. private <T> boolean internalSetRenderer(Renderer<T> renderer) {
  3350. Converter<? extends T, ?> converter;
  3351. if (isCompatibleWithProperty(renderer, getConverter())) {
  3352. // Use the existing converter (possibly none) if types
  3353. // compatible
  3354. converter = (Converter<? extends T, ?>) getConverter();
  3355. } else {
  3356. converter = ConverterUtil.getConverter(
  3357. renderer.getPresentationType(), getModelType(),
  3358. getSession());
  3359. }
  3360. setRenderer(renderer, converter);
  3361. return isCompatibleWithProperty(renderer, converter);
  3362. }
  3363. private VaadinSession getSession() {
  3364. UI ui = grid.getUI();
  3365. return ui != null ? ui.getSession() : null;
  3366. }
  3367. private boolean isCompatibleWithProperty(Renderer<?> renderer,
  3368. Converter<?, ?> converter) {
  3369. Class<?> type;
  3370. if (converter == null) {
  3371. type = getModelType();
  3372. } else {
  3373. type = converter.getPresentationType();
  3374. }
  3375. return renderer.getPresentationType().isAssignableFrom(type);
  3376. }
  3377. private Class<?> getModelType() {
  3378. return grid.getContainerDataSource()
  3379. .getType(grid.getPropertyIdByColumnId(state.id));
  3380. }
  3381. /**
  3382. * Sets whether this column is sortable by the user. The grid can be
  3383. * sorted by a sortable column by clicking or tapping the column's
  3384. * default header. Programmatic sorting using the Grid#sort methods is
  3385. * not affected by this setting.
  3386. *
  3387. * @param sortable
  3388. * {@code true} if the user should be able to sort the
  3389. * column, {@code false} otherwise
  3390. * @return the column itself
  3391. *
  3392. * @throws IllegalStateException
  3393. * if the data source of the Grid does not implement
  3394. * {@link Sortable}
  3395. * @throws IllegalStateException
  3396. * if the data source does not support sorting by the
  3397. * property associated with this column
  3398. */
  3399. public Column setSortable(boolean sortable) {
  3400. checkColumnIsAttached();
  3401. if (sortable) {
  3402. if (!(grid.datasource instanceof Sortable)) {
  3403. throw new IllegalStateException("Can't set column "
  3404. + toString()
  3405. + " sortable. The Container of Grid does not implement Sortable");
  3406. } else if (!((Sortable) grid.datasource)
  3407. .getSortableContainerPropertyIds()
  3408. .contains(propertyId)) {
  3409. throw new IllegalStateException(
  3410. "Can't set column " + toString()
  3411. + " sortable. Container doesn't support sorting by property "
  3412. + propertyId);
  3413. }
  3414. }
  3415. state.sortable = sortable;
  3416. grid.markAsDirty();
  3417. return this;
  3418. }
  3419. /**
  3420. * Returns whether the user can sort the grid by this column.
  3421. * <p>
  3422. * <em>Note:</em> it is possible to sort by this column programmatically
  3423. * using the Grid#sort methods regardless of the returned value.
  3424. *
  3425. * @return {@code true} if the column is sortable by the user,
  3426. * {@code false} otherwise
  3427. */
  3428. public boolean isSortable() {
  3429. return state.sortable;
  3430. }
  3431. @Override
  3432. public String toString() {
  3433. return getClass().getSimpleName() + "[propertyId:"
  3434. + grid.getPropertyIdByColumnId(state.id) + "]";
  3435. }
  3436. /**
  3437. * Sets the ratio with which the column expands.
  3438. * <p>
  3439. * By default, all columns expand equally (treated as if all of them had
  3440. * an expand ratio of 1). Once at least one column gets a defined expand
  3441. * ratio, the implicit expand ratio is removed, and only the defined
  3442. * expand ratios are taken into account.
  3443. * <p>
  3444. * If a column has a defined width ({@link #setWidth(double)}), it
  3445. * overrides this method's effects.
  3446. * <p>
  3447. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  3448. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  3449. * as wide as its contents requires</strong>. The column with a ratio of
  3450. * 1 is as wide as it needs, <strong>plus a third of any excess
  3451. * space</strong>, because we have 3 parts total, and this column
  3452. * reserves only one of those. The column with a ratio of 2, is as wide
  3453. * as it needs to be, <strong>plus two thirds</strong> of the excess
  3454. * width.
  3455. *
  3456. * @param expandRatio
  3457. * the expand ratio of this column. {@code 0} to not have it
  3458. * expand at all. A negative number to clear the expand
  3459. * value.
  3460. * @throws IllegalStateException
  3461. * if the column is no longer attached to any grid
  3462. * @see #setWidth(double)
  3463. */
  3464. public Column setExpandRatio(int expandRatio)
  3465. throws IllegalStateException {
  3466. checkColumnIsAttached();
  3467. getState().expandRatio = expandRatio;
  3468. grid.markAsDirty();
  3469. return this;
  3470. }
  3471. /**
  3472. * Returns the column's expand ratio.
  3473. *
  3474. * @return the column's expand ratio
  3475. * @see #setExpandRatio(int)
  3476. */
  3477. public int getExpandRatio() {
  3478. return getState().expandRatio;
  3479. }
  3480. /**
  3481. * Clears the expand ratio for this column.
  3482. * <p>
  3483. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  3484. *
  3485. * @throws IllegalStateException
  3486. * if the column is no longer attached to any grid
  3487. */
  3488. public Column clearExpandRatio() throws IllegalStateException {
  3489. return setExpandRatio(-1);
  3490. }
  3491. /**
  3492. * Sets the minimum width for this column.
  3493. * <p>
  3494. * This defines the minimum guaranteed pixel width of the column
  3495. * <em>when it is set to expand</em>.
  3496. *
  3497. * @throws IllegalStateException
  3498. * if the column is no longer attached to any grid
  3499. * @see #setExpandRatio(int)
  3500. */
  3501. public Column setMinimumWidth(double pixels)
  3502. throws IllegalStateException {
  3503. checkColumnIsAttached();
  3504. final double maxwidth = getMaximumWidth();
  3505. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  3506. throw new IllegalArgumentException("New minimum width ("
  3507. + pixels + ") was greater than maximum width ("
  3508. + maxwidth + ")");
  3509. }
  3510. getState().minWidth = pixels;
  3511. grid.markAsDirty();
  3512. return this;
  3513. }
  3514. /**
  3515. * Return the minimum width for this column.
  3516. *
  3517. * @return the minimum width for this column
  3518. * @see #setMinimumWidth(double)
  3519. */
  3520. public double getMinimumWidth() {
  3521. return getState().minWidth;
  3522. }
  3523. /**
  3524. * Sets the maximum width for this column.
  3525. * <p>
  3526. * This defines the maximum allowed pixel width of the column <em>when
  3527. * it is set to expand</em>.
  3528. *
  3529. * @param pixels
  3530. * the maximum width
  3531. * @throws IllegalStateException
  3532. * if the column is no longer attached to any grid
  3533. * @see #setExpandRatio(int)
  3534. */
  3535. public Column setMaximumWidth(double pixels) {
  3536. checkColumnIsAttached();
  3537. final double minwidth = getMinimumWidth();
  3538. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  3539. throw new IllegalArgumentException("New maximum width ("
  3540. + pixels + ") was less than minimum width (" + minwidth
  3541. + ")");
  3542. }
  3543. getState().maxWidth = pixels;
  3544. grid.markAsDirty();
  3545. return this;
  3546. }
  3547. /**
  3548. * Returns the maximum width for this column.
  3549. *
  3550. * @return the maximum width for this column
  3551. * @see #setMaximumWidth(double)
  3552. */
  3553. public double getMaximumWidth() {
  3554. return getState().maxWidth;
  3555. }
  3556. /**
  3557. * Sets whether the properties corresponding to this column should be
  3558. * editable when the item editor is active. By default columns are
  3559. * editable.
  3560. * <p>
  3561. * Values in non-editable columns are currently not displayed when the
  3562. * editor is active, but this will probably change in the future. They
  3563. * are not automatically assigned an editor field and, if one is
  3564. * manually assigned, it is not used. Columns that cannot (or should
  3565. * not) be edited even in principle should be set non-editable.
  3566. *
  3567. * @param editable
  3568. * {@code true} if this column should be editable,
  3569. * {@code false} otherwise
  3570. * @return this column
  3571. *
  3572. * @throws IllegalStateException
  3573. * if the editor is currently active
  3574. *
  3575. * @see Grid#editItem(Object)
  3576. * @see Grid#isEditorActive()
  3577. */
  3578. public Column setEditable(boolean editable) {
  3579. checkColumnIsAttached();
  3580. if (grid.isEditorActive()) {
  3581. throw new IllegalStateException(
  3582. "Cannot change column editable status while the editor is active");
  3583. }
  3584. getState().editable = editable;
  3585. grid.markAsDirty();
  3586. return this;
  3587. }
  3588. /**
  3589. * Returns whether the properties corresponding to this column should be
  3590. * editable when the item editor is active.
  3591. *
  3592. * @return {@code true} if this column is editable, {@code false}
  3593. * otherwise
  3594. *
  3595. * @see Grid#editItem(Object)
  3596. * @see #setEditable(boolean)
  3597. */
  3598. public boolean isEditable() {
  3599. return getState().editable;
  3600. }
  3601. /**
  3602. * Sets the field component used to edit the properties in this column
  3603. * when the item editor is active. If an item has not been set, then the
  3604. * binding is postponed until the item is set using
  3605. * {@link #editItem(Object)}.
  3606. * <p>
  3607. * Setting the field to <code>null</code> clears any previously set
  3608. * field, causing a new field to be created the next time the item
  3609. * editor is opened.
  3610. *
  3611. * @param editor
  3612. * the editor field
  3613. * @return this column
  3614. */
  3615. public Column setEditorField(Field<?> editor) {
  3616. grid.setEditorField(getPropertyId(), editor);
  3617. return this;
  3618. }
  3619. /**
  3620. * Returns the editor field used to edit the properties in this column
  3621. * when the item editor is active. Returns null if the column is not
  3622. * {@link Column#isEditable() editable}.
  3623. * <p>
  3624. * When {@link #editItem(Object) editItem} is called, fields are
  3625. * automatically created and bound for any unbound properties.
  3626. * <p>
  3627. * Getting a field before the editor has been opened depends on special
  3628. * support from the {@link FieldGroup} in use. Using this method with a
  3629. * user-provided <code>FieldGroup</code> might cause
  3630. * {@link FieldGroup.BindException BindException} to be thrown.
  3631. *
  3632. * @return the bound field; or <code>null</code> if the respective
  3633. * column is not editable
  3634. *
  3635. * @throws IllegalArgumentException
  3636. * if there is no column for the provided property id
  3637. * @throws FieldGroup.BindException
  3638. * if no field has been configured and there is a problem
  3639. * building or binding
  3640. */
  3641. public Field<?> getEditorField() {
  3642. return grid.getEditorField(getPropertyId());
  3643. }
  3644. /**
  3645. * Hides or shows the column. By default columns are visible before
  3646. * explicitly hiding them.
  3647. *
  3648. * @since 7.5.0
  3649. * @param hidden
  3650. * <code>true</code> to hide the column, <code>false</code>
  3651. * to show
  3652. * @return this column
  3653. */
  3654. public Column setHidden(boolean hidden) {
  3655. if (hidden != getState().hidden) {
  3656. getState().hidden = hidden;
  3657. grid.markAsDirty();
  3658. grid.fireColumnVisibilityChangeEvent(this, hidden, false);
  3659. }
  3660. return this;
  3661. }
  3662. /**
  3663. * Returns whether this column is hidden. Default is {@code false}.
  3664. *
  3665. * @since 7.5.0
  3666. * @return <code>true</code> if the column is currently hidden,
  3667. * <code>false</code> otherwise
  3668. */
  3669. public boolean isHidden() {
  3670. return getState().hidden;
  3671. }
  3672. /**
  3673. * Sets whether this column can be hidden by the user. Hidable columns
  3674. * can be hidden and shown via the sidebar menu.
  3675. *
  3676. * @since 7.5.0
  3677. * @param hidable
  3678. * <code>true</code> iff the column may be hidable by the
  3679. * user via UI interaction
  3680. * @return this column
  3681. */
  3682. public Column setHidable(boolean hidable) {
  3683. if (hidable != getState().hidable) {
  3684. getState().hidable = hidable;
  3685. grid.markAsDirty();
  3686. }
  3687. return this;
  3688. }
  3689. /**
  3690. * Returns whether this column can be hidden by the user. Default is
  3691. * {@code false}.
  3692. * <p>
  3693. * <em>Note:</em> the column can be programmatically hidden using
  3694. * {@link #setHidden(boolean)} regardless of the returned value.
  3695. *
  3696. * @since 7.5.0
  3697. * @return <code>true</code> if the user can hide the column,
  3698. * <code>false</code> if not
  3699. */
  3700. public boolean isHidable() {
  3701. return getState().hidable;
  3702. }
  3703. /**
  3704. * Sets whether this column can be resized by the user.
  3705. *
  3706. * @since 7.6
  3707. * @param resizable
  3708. * {@code true} if this column should be resizable,
  3709. * {@code false} otherwise
  3710. */
  3711. public Column setResizable(boolean resizable) {
  3712. if (resizable != getState().resizable) {
  3713. getState().resizable = resizable;
  3714. grid.markAsDirty();
  3715. }
  3716. return this;
  3717. }
  3718. /**
  3719. * Returns whether this column can be resized by the user. Default is
  3720. * {@code true}.
  3721. * <p>
  3722. * <em>Note:</em> the column can be programmatically resized using
  3723. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  3724. * of the returned value.
  3725. *
  3726. * @since 7.6
  3727. * @return {@code true} if this column is resizable, {@code false}
  3728. * otherwise
  3729. */
  3730. public boolean isResizable() {
  3731. return getState().resizable;
  3732. }
  3733. /**
  3734. * Writes the design attributes for this column into given element.
  3735. *
  3736. * @since 7.5.0
  3737. *
  3738. * @param design
  3739. * Element to write attributes into
  3740. *
  3741. * @param designContext
  3742. * the design context
  3743. */
  3744. protected void writeDesign(Element design,
  3745. DesignContext designContext) {
  3746. Attributes attributes = design.attributes();
  3747. GridColumnState def = new GridColumnState();
  3748. DesignAttributeHandler.writeAttribute("property-id", attributes,
  3749. getPropertyId(), null, Object.class, designContext);
  3750. // Sortable is a special attribute that depends on the container.
  3751. DesignAttributeHandler.writeAttribute("sortable", attributes,
  3752. isSortable(), null, boolean.class, designContext);
  3753. DesignAttributeHandler.writeAttribute("editable", attributes,
  3754. isEditable(), def.editable, boolean.class, designContext);
  3755. DesignAttributeHandler.writeAttribute("resizable", attributes,
  3756. isResizable(), def.resizable, boolean.class, designContext);
  3757. DesignAttributeHandler.writeAttribute("hidable", attributes,
  3758. isHidable(), def.hidable, boolean.class, designContext);
  3759. DesignAttributeHandler.writeAttribute("hidden", attributes,
  3760. isHidden(), def.hidden, boolean.class, designContext);
  3761. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  3762. attributes, getHidingToggleCaption(), null, String.class,
  3763. designContext);
  3764. DesignAttributeHandler.writeAttribute("width", attributes,
  3765. getWidth(), def.width, Double.class, designContext);
  3766. DesignAttributeHandler.writeAttribute("min-width", attributes,
  3767. getMinimumWidth(), def.minWidth, Double.class,
  3768. designContext);
  3769. DesignAttributeHandler.writeAttribute("max-width", attributes,
  3770. getMaximumWidth(), def.maxWidth, Double.class,
  3771. designContext);
  3772. DesignAttributeHandler.writeAttribute("expand", attributes,
  3773. getExpandRatio(), def.expandRatio, Integer.class,
  3774. designContext);
  3775. }
  3776. /**
  3777. * Reads the design attributes for this column from given element.
  3778. *
  3779. * @since 7.5.0
  3780. * @param design
  3781. * Element to read attributes from
  3782. * @param designContext
  3783. * the design context
  3784. */
  3785. protected void readDesign(Element design, DesignContext designContext) {
  3786. Attributes attributes = design.attributes();
  3787. if (design.hasAttr("sortable")) {
  3788. setSortable(DesignAttributeHandler.readAttribute("sortable",
  3789. attributes, boolean.class));
  3790. }
  3791. if (design.hasAttr("editable")) {
  3792. setEditable(DesignAttributeHandler.readAttribute("editable",
  3793. attributes, boolean.class));
  3794. }
  3795. if (design.hasAttr("resizable")) {
  3796. setResizable(DesignAttributeHandler.readAttribute("resizable",
  3797. attributes, boolean.class));
  3798. }
  3799. if (design.hasAttr("hidable")) {
  3800. setHidable(DesignAttributeHandler.readAttribute("hidable",
  3801. attributes, boolean.class));
  3802. }
  3803. if (design.hasAttr("hidden")) {
  3804. setHidden(DesignAttributeHandler.readAttribute("hidden",
  3805. attributes, boolean.class));
  3806. }
  3807. if (design.hasAttr("hiding-toggle-caption")) {
  3808. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  3809. "hiding-toggle-caption", attributes, String.class));
  3810. }
  3811. // Read size info where necessary.
  3812. if (design.hasAttr("width")) {
  3813. setWidth(DesignAttributeHandler.readAttribute("width",
  3814. attributes, Double.class));
  3815. }
  3816. if (design.hasAttr("min-width")) {
  3817. setMinimumWidth(DesignAttributeHandler
  3818. .readAttribute("min-width", attributes, Double.class));
  3819. }
  3820. if (design.hasAttr("max-width")) {
  3821. setMaximumWidth(DesignAttributeHandler
  3822. .readAttribute("max-width", attributes, Double.class));
  3823. }
  3824. if (design.hasAttr("expand")) {
  3825. if (design.attr("expand").isEmpty()) {
  3826. setExpandRatio(1);
  3827. } else {
  3828. setExpandRatio(DesignAttributeHandler.readAttribute(
  3829. "expand", attributes, Integer.class));
  3830. }
  3831. }
  3832. }
  3833. }
  3834. /**
  3835. * An abstract base class for server-side {@link Renderer Grid renderers}.
  3836. * This class currently extends the AbstractExtension superclass, but this
  3837. * fact should be regarded as an implementation detail and subject to change
  3838. * in a future major or minor Vaadin revision.
  3839. *
  3840. * @param <T>
  3841. * the type this renderer knows how to present
  3842. */
  3843. @Deprecated
  3844. public abstract static class AbstractRenderer<T>
  3845. extends AbstractGridExtension implements Renderer<T> {
  3846. private final Class<T> presentationType;
  3847. private final String nullRepresentation;
  3848. protected AbstractRenderer(Class<T> presentationType,
  3849. String nullRepresentation) {
  3850. this.presentationType = presentationType;
  3851. this.nullRepresentation = nullRepresentation;
  3852. }
  3853. protected AbstractRenderer(Class<T> presentationType) {
  3854. this(presentationType, null);
  3855. }
  3856. /**
  3857. * This method is inherited from AbstractExtension but should never be
  3858. * called directly with an AbstractRenderer.
  3859. */
  3860. @Deprecated
  3861. @Override
  3862. protected Class<Grid> getSupportedParentType() {
  3863. return Grid.class;
  3864. }
  3865. /**
  3866. * This method is inherited from AbstractExtension but should never be
  3867. * called directly with an AbstractRenderer.
  3868. */
  3869. @Deprecated
  3870. @Override
  3871. protected void extend(AbstractClientConnector target) {
  3872. super.extend(target);
  3873. }
  3874. @Override
  3875. public Class<T> getPresentationType() {
  3876. return presentationType;
  3877. }
  3878. @Override
  3879. public JsonValue encode(T value) {
  3880. if (value == null) {
  3881. return encode(getNullRepresentation(), String.class);
  3882. } else {
  3883. return encode(value, getPresentationType());
  3884. }
  3885. }
  3886. /**
  3887. * Null representation for the renderer
  3888. *
  3889. * @return a textual representation of {@code null}
  3890. */
  3891. protected String getNullRepresentation() {
  3892. return nullRepresentation;
  3893. }
  3894. /**
  3895. * Encodes the given value to JSON.
  3896. * <p>
  3897. * This is a helper method that can be invoked by an
  3898. * {@link #encode(Object) encode(T)} override if serializing a value of
  3899. * type other than {@link #getPresentationType() the presentation type}
  3900. * is desired. For instance, a {@code Renderer<Date>} could first turn a
  3901. * date value into a formatted string and return
  3902. * {@code encode(dateString, String.class)}.
  3903. *
  3904. * @param value
  3905. * the value to be encoded
  3906. * @param type
  3907. * the type of the value
  3908. * @return a JSON representation of the given value
  3909. */
  3910. protected <U> JsonValue encode(U value, Class<U> type) {
  3911. return JsonCodec
  3912. .encode(value, null, type, getUI().getConnectorTracker())
  3913. .getEncodedValue();
  3914. }
  3915. /**
  3916. * Converts and encodes the given data model property value using the
  3917. * given converter and renderer. This method is public only for testing
  3918. * purposes.
  3919. *
  3920. * @since 7.6
  3921. * @param renderer
  3922. * the renderer to use
  3923. * @param converter
  3924. * the converter to use
  3925. * @param modelValue
  3926. * the value to convert and encode
  3927. * @param locale
  3928. * the locale to use in conversion
  3929. * @return an encoded value ready to be sent to the client
  3930. */
  3931. public static <T> JsonValue encodeValue(Object modelValue,
  3932. Renderer<T> renderer, Converter<?, ?> converter,
  3933. Locale locale) {
  3934. Class<T> presentationType = renderer.getPresentationType();
  3935. T presentationValue;
  3936. if (converter == null) {
  3937. try {
  3938. presentationValue = presentationType.cast(modelValue);
  3939. } catch (ClassCastException e) {
  3940. if (presentationType == String.class) {
  3941. // If there is no converter, just fallback to using
  3942. // toString(). modelValue can't be null as
  3943. // Class.cast(null) will always succeed
  3944. presentationValue = (T) modelValue.toString();
  3945. } else {
  3946. throw new Converter.ConversionException(
  3947. "Unable to convert value of type "
  3948. + modelValue.getClass().getName()
  3949. + " to presentation type "
  3950. + presentationType.getName()
  3951. + ". No converter is set and the types are not compatible.");
  3952. }
  3953. }
  3954. } else {
  3955. assert presentationType
  3956. .isAssignableFrom(converter.getPresentationType());
  3957. @SuppressWarnings("unchecked")
  3958. Converter<T, Object> safeConverter = (Converter<T, Object>) converter;
  3959. presentationValue = safeConverter.convertToPresentation(
  3960. modelValue, safeConverter.getPresentationType(),
  3961. locale);
  3962. }
  3963. JsonValue encodedValue;
  3964. try {
  3965. encodedValue = renderer.encode(presentationValue);
  3966. } catch (Exception e) {
  3967. getLogger().log(Level.SEVERE, "Unable to encode data", e);
  3968. encodedValue = renderer.encode(null);
  3969. }
  3970. return encodedValue;
  3971. }
  3972. private static Logger getLogger() {
  3973. return Logger.getLogger(AbstractRenderer.class.getName());
  3974. }
  3975. }
  3976. /**
  3977. * An abstract base class for server-side Grid extensions.
  3978. * <p>
  3979. * Note: If the extension is an instance of {@link DataGenerator} it will
  3980. * automatically register itself to {@link RpcDataProviderExtension} of
  3981. * extended Grid. On remove this registration is automatically removed.
  3982. *
  3983. * @since 7.5
  3984. */
  3985. @Deprecated
  3986. public abstract static class AbstractGridExtension
  3987. extends AbstractExtension {
  3988. /**
  3989. * Constructs a new Grid extension.
  3990. */
  3991. public AbstractGridExtension() {
  3992. super();
  3993. }
  3994. /**
  3995. * Constructs a new Grid extension and extends given Grid.
  3996. *
  3997. * @param grid
  3998. * a grid instance
  3999. */
  4000. public AbstractGridExtension(Grid grid) {
  4001. super();
  4002. extend(grid);
  4003. }
  4004. @Override
  4005. protected void extend(AbstractClientConnector target) {
  4006. super.extend(target);
  4007. if (this instanceof DataGenerator) {
  4008. getParentGrid().datasourceExtension
  4009. .addDataGenerator((DataGenerator) this);
  4010. }
  4011. }
  4012. @Override
  4013. public void remove() {
  4014. if (this instanceof DataGenerator) {
  4015. getParentGrid().datasourceExtension
  4016. .removeDataGenerator((DataGenerator) this);
  4017. }
  4018. super.remove();
  4019. }
  4020. /**
  4021. * Gets the item id for a row key.
  4022. * <p>
  4023. * A key is used to identify a particular row on both a server and a
  4024. * client. This method can be used to get the item id for the row key
  4025. * that the client has sent.
  4026. *
  4027. * @param rowKey
  4028. * the row key for which to retrieve an item id
  4029. * @return the item id corresponding to {@code key}
  4030. */
  4031. protected Object getItemId(String rowKey) {
  4032. return getParentGrid().getKeyMapper().get(rowKey);
  4033. }
  4034. /**
  4035. * Gets the column for a column id.
  4036. * <p>
  4037. * An id is used to identify a particular column on both a server and a
  4038. * client. This method can be used to get the column for the column id
  4039. * that the client has sent.
  4040. *
  4041. * @param columnId
  4042. * the column id for which to retrieve a column
  4043. * @return the column corresponding to {@code columnId}
  4044. */
  4045. protected Column getColumn(String columnId) {
  4046. return getParentGrid().getColumnByColumnId(columnId);
  4047. }
  4048. /**
  4049. * Gets the parent Grid of the renderer.
  4050. *
  4051. * @return parent grid
  4052. * @throws IllegalStateException
  4053. * if parent is not Grid
  4054. */
  4055. protected Grid getParentGrid() {
  4056. if (getParent() instanceof Grid) {
  4057. Grid grid = (Grid) getParent();
  4058. return grid;
  4059. } else if (getParent() == null) {
  4060. throw new IllegalStateException(
  4061. "Renderer is not attached to any parent");
  4062. } else {
  4063. throw new IllegalStateException(
  4064. "Renderers can be used only with Grid. Extended "
  4065. + getParent().getClass().getSimpleName()
  4066. + " instead");
  4067. }
  4068. }
  4069. /**
  4070. * Resends the row data for given item id to the client.
  4071. *
  4072. * @since 7.6
  4073. * @param itemId
  4074. * row to refresh
  4075. */
  4076. protected void refreshRow(Object itemId) {
  4077. getParentGrid().datasourceExtension.updateRowData(itemId);
  4078. }
  4079. /**
  4080. * Informs the parent Grid that this Extension wants to add a child
  4081. * component to it.
  4082. *
  4083. * @since 7.6
  4084. * @param c
  4085. * component
  4086. */
  4087. protected void addComponentToGrid(Component c) {
  4088. getParentGrid().addComponent(c);
  4089. }
  4090. /**
  4091. * Informs the parent Grid that this Extension wants to remove a child
  4092. * component from it.
  4093. *
  4094. * @since 7.6
  4095. * @param c
  4096. * component
  4097. */
  4098. protected void removeComponentFromGrid(Component c) {
  4099. getParentGrid().removeComponent(c);
  4100. }
  4101. }
  4102. /**
  4103. * The data source attached to the grid
  4104. */
  4105. private Container.Indexed datasource;
  4106. /**
  4107. * Property id to column instance mapping
  4108. */
  4109. private final Map<Object, Column> columns = new HashMap<Object, Column>();
  4110. /**
  4111. * Key generator for column server-to-client communication
  4112. */
  4113. private final KeyMapper<Object> columnKeys = new KeyMapper<Object>();
  4114. /**
  4115. * The current sort order
  4116. */
  4117. private final List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  4118. /**
  4119. * Property listener for listening to changes in data source properties.
  4120. */
  4121. private final PropertySetChangeListener propertyListener = new PropertySetChangeListener() {
  4122. @Override
  4123. public void containerPropertySetChange(PropertySetChangeEvent event) {
  4124. Collection<?> properties = new HashSet<Object>(
  4125. event.getContainer().getContainerPropertyIds());
  4126. // Find columns that need to be removed.
  4127. List<Column> removedColumns = new LinkedList<Column>();
  4128. for (Object propertyId : columns.keySet()) {
  4129. if (!properties.contains(propertyId)) {
  4130. removedColumns.add(getColumn(propertyId));
  4131. }
  4132. }
  4133. // Actually remove columns.
  4134. for (Column column : removedColumns) {
  4135. Object propertyId = column.getPropertyId();
  4136. internalRemoveColumn(propertyId);
  4137. columnKeys.remove(propertyId);
  4138. }
  4139. datasourceExtension.columnsRemoved(removedColumns);
  4140. // Add new columns
  4141. List<Column> addedColumns = new LinkedList<Column>();
  4142. for (Object propertyId : properties) {
  4143. if (!columns.containsKey(propertyId)) {
  4144. addedColumns.add(appendColumn(propertyId));
  4145. }
  4146. }
  4147. datasourceExtension.columnsAdded(addedColumns);
  4148. if (getFrozenColumnCount() > columns.size()) {
  4149. setFrozenColumnCount(columns.size());
  4150. }
  4151. // Unset sortable for non-sortable columns.
  4152. if (datasource instanceof Sortable) {
  4153. Collection<?> sortables = ((Sortable) datasource)
  4154. .getSortableContainerPropertyIds();
  4155. for (Object propertyId : columns.keySet()) {
  4156. Column column = columns.get(propertyId);
  4157. if (!sortables.contains(propertyId)
  4158. && column.isSortable()) {
  4159. column.setSortable(false);
  4160. }
  4161. }
  4162. }
  4163. }
  4164. };
  4165. private final ItemSetChangeListener editorClosingItemSetListener = new ItemSetChangeListener() {
  4166. @Override
  4167. public void containerItemSetChange(ItemSetChangeEvent event) {
  4168. cancelEditor();
  4169. }
  4170. };
  4171. private RpcDataProviderExtension datasourceExtension;
  4172. /**
  4173. * The selection model that is currently in use. Never <code>null</code>
  4174. * after the constructor has been run.
  4175. */
  4176. private SelectionModel selectionModel;
  4177. /**
  4178. * Used to know whether selection change events originate from the server or
  4179. * the client so the selection change handler knows whether the changes
  4180. * should be sent to the client.
  4181. */
  4182. private boolean applyingSelectionFromClient;
  4183. private final Header header = new Header(this);
  4184. private final Footer footer = new Footer(this);
  4185. private Object editedItemId = null;
  4186. private boolean editorActive = false;
  4187. /**
  4188. * True while the editor is storing the field values, i.e. commiting the
  4189. * field group.
  4190. */
  4191. private boolean editorSaving = false;
  4192. private FieldGroup editorFieldGroup = new CustomFieldGroup();
  4193. /**
  4194. * Poperty ID to Field mapping that stores editor fields set by
  4195. * {@link #setEditorField(Object, Field)}.
  4196. */
  4197. private Map<Object, Field<?>> editorFields = new HashMap<Object, Field<?>>();
  4198. private CellStyleGenerator cellStyleGenerator;
  4199. private RowStyleGenerator rowStyleGenerator;
  4200. private CellDescriptionGenerator cellDescriptionGenerator;
  4201. private RowDescriptionGenerator rowDescriptionGenerator;
  4202. /**
  4203. * <code>true</code> if Grid is using the internal IndexedContainer created
  4204. * in Grid() constructor, or <code>false</code> if the user has set their
  4205. * own Container.
  4206. *
  4207. * @see #setContainerDataSource(Indexed)
  4208. * @see #Grid()
  4209. */
  4210. private boolean defaultContainer = true;
  4211. private EditorErrorHandler editorErrorHandler = new DefaultEditorErrorHandler();
  4212. private DetailComponentManager detailComponentManager = null;
  4213. private Set<Component> extensionComponents = new HashSet<Component>();
  4214. private static final Method SELECTION_CHANGE_METHOD = ReflectTools
  4215. .findMethod(SelectionListener.class, "select",
  4216. SelectionEvent.class);
  4217. private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
  4218. .findMethod(SortListener.class, "sort", SortEvent.class);
  4219. private static final Method COLUMN_REORDER_METHOD = ReflectTools.findMethod(
  4220. ColumnReorderListener.class, "columnReorder",
  4221. ColumnReorderEvent.class);
  4222. private static final Method COLUMN_RESIZE_METHOD = ReflectTools.findMethod(
  4223. ColumnResizeListener.class, "columnResize",
  4224. ColumnResizeEvent.class);
  4225. private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
  4226. .findMethod(ColumnVisibilityChangeListener.class,
  4227. "columnVisibilityChanged",
  4228. ColumnVisibilityChangeEvent.class);
  4229. /**
  4230. * Creates a new Grid with a new {@link IndexedContainer} as the data
  4231. * source.
  4232. */
  4233. public Grid() {
  4234. this(null, null);
  4235. }
  4236. /**
  4237. * Creates a new Grid using the given data source.
  4238. *
  4239. * @param dataSource
  4240. * the indexed container to use as a data source
  4241. */
  4242. public Grid(final Container.Indexed dataSource) {
  4243. this(null, dataSource);
  4244. }
  4245. /**
  4246. * Creates a new Grid with the given caption and a new
  4247. * {@link IndexedContainer} data source.
  4248. *
  4249. * @param caption
  4250. * the caption of the grid
  4251. */
  4252. public Grid(String caption) {
  4253. this(caption, null);
  4254. }
  4255. /**
  4256. * Creates a new Grid with the given caption and data source. If the data
  4257. * source is null, a new {@link IndexedContainer} will be used.
  4258. *
  4259. * @param caption
  4260. * the caption of the grid
  4261. * @param dataSource
  4262. * the indexed container to use as a data source
  4263. */
  4264. public Grid(String caption, Container.Indexed dataSource) {
  4265. if (dataSource == null) {
  4266. internalSetContainerDataSource(new IndexedContainer());
  4267. } else {
  4268. setContainerDataSource(dataSource);
  4269. }
  4270. setCaption(caption);
  4271. initGrid();
  4272. }
  4273. /**
  4274. * Grid initial setup
  4275. */
  4276. private void initGrid() {
  4277. setSelectionMode(getDefaultSelectionMode());
  4278. registerRpc(new GridServerRpc() {
  4279. @Override
  4280. public void sort(String[] columnIds, SortDirection[] directions,
  4281. boolean userOriginated) {
  4282. assert columnIds.length == directions.length;
  4283. List<SortOrder> order = new ArrayList<SortOrder>(
  4284. columnIds.length);
  4285. for (int i = 0; i < columnIds.length; i++) {
  4286. Object propertyId = getPropertyIdByColumnId(columnIds[i]);
  4287. order.add(new SortOrder(propertyId, directions[i]));
  4288. }
  4289. setSortOrder(order, userOriginated);
  4290. if (!order.equals(getSortOrder())) {
  4291. /*
  4292. * Actual sort order is not what the client expects. Make
  4293. * sure the client gets a state change event by clearing the
  4294. * diffstate and marking as dirty
  4295. */
  4296. ConnectorTracker connectorTracker = getUI()
  4297. .getConnectorTracker();
  4298. JsonObject diffState = connectorTracker
  4299. .getDiffState(Grid.this);
  4300. diffState.remove("sortColumns");
  4301. diffState.remove("sortDirs");
  4302. markAsDirty();
  4303. }
  4304. }
  4305. @Override
  4306. public void itemClick(String rowKey, String columnId,
  4307. MouseEventDetails details) {
  4308. Object itemId = getKeyMapper().get(rowKey);
  4309. Item item = datasource.getItem(itemId);
  4310. Object propertyId = getPropertyIdByColumnId(columnId);
  4311. fireEvent(new ItemClickEvent(Grid.this, item, itemId,
  4312. propertyId, details));
  4313. }
  4314. @Override
  4315. public void columnsReordered(List<String> newColumnOrder,
  4316. List<String> oldColumnOrder) {
  4317. final String diffStateKey = "columnOrder";
  4318. ConnectorTracker connectorTracker = getUI()
  4319. .getConnectorTracker();
  4320. JsonObject diffState = connectorTracker.getDiffState(Grid.this);
  4321. // discard the change if the columns have been reordered from
  4322. // the server side, as the server side is always right
  4323. if (getState(false).columnOrder.equals(oldColumnOrder)) {
  4324. // Don't mark as dirty since client has the state already
  4325. getState(false).columnOrder = newColumnOrder;
  4326. // write changes to diffState so that possible reverting the
  4327. // column order is sent to client
  4328. assert diffState
  4329. .hasKey(diffStateKey) : "Field name has changed";
  4330. Type type = null;
  4331. try {
  4332. type = (getState(false).getClass()
  4333. .getDeclaredField(diffStateKey)
  4334. .getGenericType());
  4335. } catch (NoSuchFieldException e) {
  4336. e.printStackTrace();
  4337. } catch (SecurityException e) {
  4338. e.printStackTrace();
  4339. }
  4340. EncodeResult encodeResult = JsonCodec.encode(
  4341. getState(false).columnOrder, diffState, type,
  4342. connectorTracker);
  4343. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  4344. fireColumnReorderEvent(true);
  4345. } else {
  4346. // make sure the client is reverted to the order that the
  4347. // server thinks it is
  4348. diffState.remove(diffStateKey);
  4349. markAsDirty();
  4350. }
  4351. }
  4352. @Override
  4353. public void columnVisibilityChanged(String id, boolean hidden,
  4354. boolean userOriginated) {
  4355. final Column column = getColumnByColumnId(id);
  4356. final GridColumnState columnState = column.getState();
  4357. if (columnState.hidden != hidden) {
  4358. columnState.hidden = hidden;
  4359. final String diffStateKey = "columns";
  4360. ConnectorTracker connectorTracker = getUI()
  4361. .getConnectorTracker();
  4362. JsonObject diffState = connectorTracker
  4363. .getDiffState(Grid.this);
  4364. assert diffState
  4365. .hasKey(diffStateKey) : "Field name has changed";
  4366. Type type = null;
  4367. try {
  4368. type = (getState(false).getClass()
  4369. .getDeclaredField(diffStateKey)
  4370. .getGenericType());
  4371. } catch (NoSuchFieldException e) {
  4372. e.printStackTrace();
  4373. } catch (SecurityException e) {
  4374. e.printStackTrace();
  4375. }
  4376. EncodeResult encodeResult = JsonCodec.encode(
  4377. getState(false).columns, diffState, type,
  4378. connectorTracker);
  4379. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  4380. fireColumnVisibilityChangeEvent(column, hidden,
  4381. userOriginated);
  4382. }
  4383. }
  4384. @Override
  4385. public void contextClick(int rowIndex, String rowKey,
  4386. String columnId, Section section,
  4387. MouseEventDetails details) {
  4388. Object itemId = null;
  4389. if (rowKey != null) {
  4390. itemId = getKeyMapper().get(rowKey);
  4391. }
  4392. fireEvent(new GridContextClickEvent(Grid.this, details, section,
  4393. rowIndex, itemId, getPropertyIdByColumnId(columnId)));
  4394. }
  4395. @Override
  4396. public void columnResized(String id, double pixels) {
  4397. final Column column = getColumnByColumnId(id);
  4398. if (column != null && column.isResizable()) {
  4399. column.getState().width = pixels;
  4400. fireColumnResizeEvent(column, true);
  4401. markAsDirty();
  4402. }
  4403. }
  4404. });
  4405. registerRpc(new EditorServerRpc() {
  4406. @Override
  4407. public void bind(int rowIndex) {
  4408. try {
  4409. Object id = getContainerDataSource().getIdByIndex(rowIndex);
  4410. final boolean opening = editedItemId == null;
  4411. final boolean moving = !opening && !editedItemId.equals(id);
  4412. final boolean allowMove = !isEditorBuffered()
  4413. && getEditorFieldGroup().isValid();
  4414. if (opening || !moving || allowMove) {
  4415. doBind(id);
  4416. } else {
  4417. failBind(null);
  4418. }
  4419. } catch (Exception e) {
  4420. failBind(e);
  4421. }
  4422. }
  4423. private void doBind(Object id) {
  4424. editedItemId = id;
  4425. doEditItem();
  4426. getEditorRpc().confirmBind(true);
  4427. }
  4428. private void failBind(Exception e) {
  4429. if (e != null) {
  4430. handleError(e);
  4431. }
  4432. getEditorRpc().confirmBind(false);
  4433. }
  4434. @Override
  4435. public void cancel(int rowIndex) {
  4436. try {
  4437. // For future proofing even though cannot currently fail
  4438. doCancelEditor();
  4439. } catch (Exception e) {
  4440. handleError(e);
  4441. }
  4442. }
  4443. @Override
  4444. public void save(int rowIndex) {
  4445. List<String> errorColumnIds = null;
  4446. String errorMessage = null;
  4447. boolean success = false;
  4448. try {
  4449. saveEditor();
  4450. success = true;
  4451. } catch (CommitException e) {
  4452. try {
  4453. CommitErrorEvent event = new CommitErrorEvent(Grid.this,
  4454. e);
  4455. getEditorErrorHandler().commitError(event);
  4456. errorMessage = event.getUserErrorMessage();
  4457. errorColumnIds = new ArrayList<String>();
  4458. for (Column column : event.getErrorColumns()) {
  4459. errorColumnIds.add(column.state.id);
  4460. }
  4461. } catch (Exception ee) {
  4462. // A badly written error handler can throw an exception,
  4463. // which would lock up the Grid
  4464. handleError(ee);
  4465. }
  4466. } catch (Exception e) {
  4467. handleError(e);
  4468. }
  4469. getEditorRpc().confirmSave(success, errorMessage,
  4470. errorColumnIds);
  4471. }
  4472. private void handleError(Exception e) {
  4473. com.vaadin.server.ErrorEvent.findErrorHandler(Grid.this)
  4474. .error(new ConnectorErrorEvent(Grid.this, e));
  4475. }
  4476. });
  4477. }
  4478. @Override
  4479. public void beforeClientResponse(boolean initial) {
  4480. try {
  4481. header.sanityCheck();
  4482. footer.sanityCheck();
  4483. } catch (Exception e) {
  4484. e.printStackTrace();
  4485. setComponentError(new ErrorMessage() {
  4486. @Override
  4487. public ErrorLevel getErrorLevel() {
  4488. return ErrorLevel.CRITICAL;
  4489. }
  4490. @Override
  4491. public String getFormattedHtmlMessage() {
  4492. return "Incorrectly merged cells";
  4493. }
  4494. });
  4495. }
  4496. super.beforeClientResponse(initial);
  4497. }
  4498. /**
  4499. * Sets the grid data source.
  4500. * <p>
  4501. *
  4502. * <strong>Note</strong> Grid columns are based on properties and try to
  4503. * detect a correct converter for the data type. The columns are not
  4504. * reinitialized automatically if the container is changed, and if the same
  4505. * properties are present after container change, the columns are reused.
  4506. * Properties with same names, but different data types will lead to
  4507. * unpredictable behaviour.
  4508. *
  4509. * @param container
  4510. * The container data source. Cannot be null.
  4511. * @throws IllegalArgumentException
  4512. * if the data source is null
  4513. */
  4514. public void setContainerDataSource(Container.Indexed container) {
  4515. defaultContainer = false;
  4516. internalSetContainerDataSource(container);
  4517. }
  4518. private void internalSetContainerDataSource(Container.Indexed container) {
  4519. if (container == null) {
  4520. throw new IllegalArgumentException(
  4521. "Cannot set the datasource to null");
  4522. }
  4523. if (datasource == container) {
  4524. return;
  4525. }
  4526. // Remove old listeners
  4527. if (datasource instanceof PropertySetChangeNotifier) {
  4528. ((PropertySetChangeNotifier) datasource)
  4529. .removePropertySetChangeListener(propertyListener);
  4530. }
  4531. if (datasourceExtension != null) {
  4532. removeExtension(datasourceExtension);
  4533. }
  4534. // Remove old DetailComponentManager
  4535. if (detailComponentManager != null) {
  4536. detailComponentManager.remove();
  4537. }
  4538. resetEditor();
  4539. datasource = container;
  4540. //
  4541. // Adjust sort order
  4542. //
  4543. if (container instanceof Container.Sortable) {
  4544. // If the container is sortable, go through the current sort order
  4545. // and match each item to the sortable properties of the new
  4546. // container. If the new container does not support an item in the
  4547. // current sort order, that item is removed from the current sort
  4548. // order list.
  4549. Collection<?> sortableProps = ((Container.Sortable) getContainerDataSource())
  4550. .getSortableContainerPropertyIds();
  4551. Iterator<SortOrder> i = sortOrder.iterator();
  4552. while (i.hasNext()) {
  4553. if (!sortableProps.contains(i.next().getPropertyId())) {
  4554. i.remove();
  4555. }
  4556. }
  4557. sort(false);
  4558. } else {
  4559. // Clear sorting order. Don't sort.
  4560. sortOrder.clear();
  4561. }
  4562. datasourceExtension = new RpcDataProviderExtension(container);
  4563. datasourceExtension.extend(this);
  4564. datasourceExtension.addDataGenerator(new RowDataGenerator());
  4565. for (Extension e : getExtensions()) {
  4566. if (e instanceof DataGenerator) {
  4567. datasourceExtension.addDataGenerator((DataGenerator) e);
  4568. }
  4569. }
  4570. if (detailComponentManager != null) {
  4571. detailComponentManager = new DetailComponentManager(this,
  4572. detailComponentManager.getDetailsGenerator());
  4573. } else {
  4574. detailComponentManager = new DetailComponentManager(this);
  4575. }
  4576. /*
  4577. * selectionModel == null when the invocation comes from the
  4578. * constructor.
  4579. */
  4580. if (selectionModel != null) {
  4581. selectionModel.reset();
  4582. }
  4583. // Listen to changes in properties and remove columns if needed
  4584. if (datasource instanceof PropertySetChangeNotifier) {
  4585. ((PropertySetChangeNotifier) datasource)
  4586. .addPropertySetChangeListener(propertyListener);
  4587. }
  4588. /*
  4589. * activeRowHandler will be updated by the client-side request that
  4590. * occurs on container change - no need to actively re-insert any
  4591. * ValueChangeListeners at this point.
  4592. */
  4593. setFrozenColumnCount(0);
  4594. if (columns.isEmpty()) {
  4595. // Add columns
  4596. for (Object propertyId : datasource.getContainerPropertyIds()) {
  4597. Column column = appendColumn(propertyId);
  4598. // Initial sorting is defined by container
  4599. if (datasource instanceof Sortable) {
  4600. column.setSortable(((Sortable) datasource)
  4601. .getSortableContainerPropertyIds()
  4602. .contains(propertyId));
  4603. } else {
  4604. column.setSortable(false);
  4605. }
  4606. }
  4607. } else {
  4608. Collection<?> properties = datasource.getContainerPropertyIds();
  4609. for (Object property : columns.keySet()) {
  4610. if (!properties.contains(property)) {
  4611. throw new IllegalStateException(
  4612. "Found at least one column in Grid that does not exist in the given container: "
  4613. + property + " with the header \""
  4614. + getColumn(property).getHeaderCaption()
  4615. + "\". "
  4616. + "Call removeAllColumns() before setContainerDataSource() if you want to reconfigure the columns based on the new container.");
  4617. }
  4618. if (!(datasource instanceof Sortable)
  4619. || !((Sortable) datasource)
  4620. .getSortableContainerPropertyIds()
  4621. .contains(property)) {
  4622. columns.get(property).setSortable(false);
  4623. }
  4624. }
  4625. }
  4626. }
  4627. /**
  4628. * Returns the grid data source.
  4629. *
  4630. * @return the container data source of the grid
  4631. */
  4632. public Container.Indexed getContainerDataSource() {
  4633. return datasource;
  4634. }
  4635. /**
  4636. * Returns a column based on the property id
  4637. *
  4638. * @param propertyId
  4639. * the property id of the column
  4640. * @return the column or <code>null</code> if not found
  4641. */
  4642. public Column getColumn(Object propertyId) {
  4643. return columns.get(propertyId);
  4644. }
  4645. /**
  4646. * Returns a copy of currently configures columns in their current visual
  4647. * order in this Grid.
  4648. *
  4649. * @return unmodifiable copy of current columns in visual order
  4650. */
  4651. public List<Column> getColumns() {
  4652. List<Column> columns = new ArrayList<Grid.Column>();
  4653. for (String columnId : getState(false).columnOrder) {
  4654. columns.add(getColumnByColumnId(columnId));
  4655. }
  4656. return Collections.unmodifiableList(columns);
  4657. }
  4658. /**
  4659. * Adds a new Column to Grid. Also adds the property to container with data
  4660. * type String, if property for column does not exist in it. Default value
  4661. * for the new property is an empty String.
  4662. * <p>
  4663. * Note that adding a new property is only done for the default container
  4664. * that Grid sets up with the default constructor.
  4665. *
  4666. * @param propertyId
  4667. * the property id of the new column
  4668. * @return the new column
  4669. *
  4670. * @throws IllegalStateException
  4671. * if column for given property already exists in this grid
  4672. */
  4673. public Column addColumn(Object propertyId) throws IllegalStateException {
  4674. if (datasource.getContainerPropertyIds().contains(propertyId)
  4675. && !columns.containsKey(propertyId)) {
  4676. appendColumn(propertyId);
  4677. } else if (defaultContainer) {
  4678. addColumnProperty(propertyId, String.class, "");
  4679. } else {
  4680. if (columns.containsKey(propertyId)) {
  4681. throw new IllegalStateException(
  4682. "A column for property id '" + propertyId.toString()
  4683. + "' already exists in this grid");
  4684. } else {
  4685. throw new IllegalStateException(
  4686. "Property id '" + propertyId.toString()
  4687. + "' does not exist in the container");
  4688. }
  4689. }
  4690. // Inform the data provider of this new column.
  4691. Column column = getColumn(propertyId);
  4692. List<Column> addedColumns = new ArrayList<Column>();
  4693. addedColumns.add(column);
  4694. datasourceExtension.columnsAdded(addedColumns);
  4695. return column;
  4696. }
  4697. /**
  4698. * Adds a new Column to Grid. This function makes sure that the property
  4699. * with the given id and data type exists in the container. If property does
  4700. * not exists, it will be created.
  4701. * <p>
  4702. * Default value for the new property is 0 if type is Integer, Double and
  4703. * Float. If type is String, default value is an empty string. For all other
  4704. * types the default value is null.
  4705. * <p>
  4706. * Note that adding a new property is only done for the default container
  4707. * that Grid sets up with the default constructor.
  4708. *
  4709. * @param propertyId
  4710. * the property id of the new column
  4711. * @param type
  4712. * the data type for the new property
  4713. * @return the new column
  4714. *
  4715. * @throws IllegalStateException
  4716. * if column for given property already exists in this grid or
  4717. * property already exists in the container with wrong type
  4718. */
  4719. public Column addColumn(Object propertyId, Class<?> type) {
  4720. addColumnProperty(propertyId, type, null);
  4721. return getColumn(propertyId);
  4722. }
  4723. protected void addColumnProperty(Object propertyId, Class<?> type,
  4724. Object defaultValue) throws IllegalStateException {
  4725. if (!defaultContainer) {
  4726. throw new IllegalStateException(
  4727. "Container for this Grid is not a default container from Grid() constructor");
  4728. }
  4729. if (!columns.containsKey(propertyId)) {
  4730. if (!datasource.getContainerPropertyIds().contains(propertyId)) {
  4731. datasource.addContainerProperty(propertyId, type, defaultValue);
  4732. } else {
  4733. Property<?> containerProperty = datasource.getContainerProperty(
  4734. datasource.firstItemId(), propertyId);
  4735. if (containerProperty.getType() == type) {
  4736. appendColumn(propertyId);
  4737. } else {
  4738. throw new IllegalStateException(
  4739. "DataSource already has the given property "
  4740. + propertyId + " with a different type");
  4741. }
  4742. }
  4743. } else {
  4744. throw new IllegalStateException(
  4745. "Grid already has a column for property " + propertyId);
  4746. }
  4747. }
  4748. /**
  4749. * Removes all columns from this Grid.
  4750. */
  4751. public void removeAllColumns() {
  4752. List<Column> removed = new ArrayList<Column>(columns.values());
  4753. Set<Object> properties = new HashSet<Object>(columns.keySet());
  4754. for (Object propertyId : properties) {
  4755. removeColumn(propertyId);
  4756. }
  4757. datasourceExtension.columnsRemoved(removed);
  4758. }
  4759. /**
  4760. * Used internally by the {@link Grid} to get a {@link Column} by
  4761. * referencing its generated state id. Also used by {@link Column} to verify
  4762. * if it has been detached from the {@link Grid}.
  4763. *
  4764. * @param columnId
  4765. * the client id generated for the column when the column is
  4766. * added to the grid
  4767. * @return the column with the id or <code>null</code> if not found
  4768. */
  4769. Column getColumnByColumnId(String columnId) {
  4770. Object propertyId = getPropertyIdByColumnId(columnId);
  4771. return getColumn(propertyId);
  4772. }
  4773. /**
  4774. * Used internally by the {@link Grid} to get a property id by referencing
  4775. * the columns generated state id.
  4776. *
  4777. * @param columnId
  4778. * The state id of the column
  4779. * @return The column instance or null if not found
  4780. */
  4781. Object getPropertyIdByColumnId(String columnId) {
  4782. return columnKeys.get(columnId);
  4783. }
  4784. /**
  4785. * Returns whether column reordering is allowed. Default value is
  4786. * <code>false</code>.
  4787. *
  4788. * @since 7.5.0
  4789. * @return true if reordering is allowed
  4790. */
  4791. public boolean isColumnReorderingAllowed() {
  4792. return getState(false).columnReorderingAllowed;
  4793. }
  4794. /**
  4795. * Sets whether or not column reordering is allowed. Default value is
  4796. * <code>false</code>.
  4797. *
  4798. * @since 7.5.0
  4799. * @param columnReorderingAllowed
  4800. * specifies whether column reordering is allowed
  4801. */
  4802. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  4803. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  4804. getState().columnReorderingAllowed = columnReorderingAllowed;
  4805. }
  4806. }
  4807. @Override
  4808. protected GridState getState() {
  4809. return (GridState) super.getState();
  4810. }
  4811. @Override
  4812. protected GridState getState(boolean markAsDirty) {
  4813. return (GridState) super.getState(markAsDirty);
  4814. }
  4815. /**
  4816. * Sets the column resize mode to use. The default mode is
  4817. * {@link ColumnResizeMode#ANIMATED}.
  4818. *
  4819. * @param mode
  4820. * a ColumnResizeMode value
  4821. * @since 7.7.5
  4822. */
  4823. public void setColumnResizeMode(ColumnResizeMode mode) {
  4824. getState().columnResizeMode = mode;
  4825. }
  4826. /**
  4827. * Returns the current column resize mode. The default mode is
  4828. * {@link ColumnResizeMode#ANIMATED}.
  4829. *
  4830. * @return a ColumnResizeMode value
  4831. * @since 7.7.5
  4832. */
  4833. public ColumnResizeMode getColumnResizeMode() {
  4834. return getState(false).columnResizeMode;
  4835. }
  4836. /**
  4837. * Creates a new column based on a property id and appends it as the last
  4838. * column.
  4839. *
  4840. * @param datasourcePropertyId
  4841. * The property id of a property in the datasource
  4842. */
  4843. private Column appendColumn(Object datasourcePropertyId) {
  4844. if (datasourcePropertyId == null) {
  4845. throw new IllegalArgumentException("Property id cannot be null");
  4846. }
  4847. assert datasource.getContainerPropertyIds().contains(
  4848. datasourcePropertyId) : "Datasource should contain the property id";
  4849. GridColumnState columnState = new GridColumnState();
  4850. columnState.id = columnKeys.key(datasourcePropertyId);
  4851. Column column = new Column(this, columnState, datasourcePropertyId);
  4852. columns.put(datasourcePropertyId, column);
  4853. getState().columns.add(columnState);
  4854. getState().columnOrder.add(columnState.id);
  4855. header.addColumn(datasourcePropertyId);
  4856. footer.addColumn(datasourcePropertyId);
  4857. String humanFriendlyPropertyId = SharedUtil.propertyIdToHumanFriendly(
  4858. String.valueOf(datasourcePropertyId));
  4859. column.setHeaderCaption(humanFriendlyPropertyId);
  4860. if (datasource instanceof Sortable
  4861. && ((Sortable) datasource).getSortableContainerPropertyIds()
  4862. .contains(datasourcePropertyId)) {
  4863. column.setSortable(true);
  4864. }
  4865. return column;
  4866. }
  4867. /**
  4868. * Removes a column from Grid based on a property id.
  4869. *
  4870. * @param propertyId
  4871. * The property id of column to be removed
  4872. *
  4873. * @throws IllegalArgumentException
  4874. * if there is no column for given property id in this grid
  4875. */
  4876. public void removeColumn(Object propertyId)
  4877. throws IllegalArgumentException {
  4878. if (!columns.keySet().contains(propertyId)) {
  4879. throw new IllegalArgumentException(
  4880. "There is no column for given property id " + propertyId);
  4881. }
  4882. List<Column> removed = new ArrayList<Column>();
  4883. removed.add(getColumn(propertyId));
  4884. internalRemoveColumn(propertyId);
  4885. datasourceExtension.columnsRemoved(removed);
  4886. }
  4887. private void internalRemoveColumn(Object propertyId) {
  4888. setEditorField(propertyId, null);
  4889. header.removeColumn(propertyId);
  4890. footer.removeColumn(propertyId);
  4891. Column column = columns.remove(propertyId);
  4892. getState().columnOrder.remove(columnKeys.key(propertyId));
  4893. getState().columns.remove(column.getState());
  4894. removeExtension(column.getRenderer());
  4895. }
  4896. /**
  4897. * Sets the columns and their order for the grid. Current columns whose
  4898. * property id is not in propertyIds are removed. Similarly, a column is
  4899. * added for any property id in propertyIds that has no corresponding column
  4900. * in this Grid.
  4901. *
  4902. * @since 7.5.0
  4903. *
  4904. * @param propertyIds
  4905. * properties in the desired column order
  4906. */
  4907. public void setColumns(Object... propertyIds) {
  4908. if (SharedUtil.containsDuplicates(propertyIds)) {
  4909. throw new IllegalArgumentException(
  4910. "The propertyIds array contains duplicates: "
  4911. + SharedUtil.getDuplicates(propertyIds));
  4912. }
  4913. Set<?> removePids = new HashSet<Object>(columns.keySet());
  4914. removePids.removeAll(Arrays.asList(propertyIds));
  4915. for (Object removePid : removePids) {
  4916. removeColumn(removePid);
  4917. }
  4918. Set<?> addPids = new HashSet<Object>(Arrays.asList(propertyIds));
  4919. addPids.removeAll(columns.keySet());
  4920. for (Object propertyId : addPids) {
  4921. addColumn(propertyId);
  4922. }
  4923. setColumnOrder(propertyIds);
  4924. }
  4925. /**
  4926. * Sets a new column order for the grid. All columns which are not ordered
  4927. * here will remain in the order they were before as the last columns of
  4928. * grid.
  4929. *
  4930. * @param propertyIds
  4931. * properties in the order columns should be
  4932. */
  4933. public void setColumnOrder(Object... propertyIds) {
  4934. if (SharedUtil.containsDuplicates(propertyIds)) {
  4935. throw new IllegalArgumentException(
  4936. "The propertyIds array contains duplicates: "
  4937. + SharedUtil.getDuplicates(propertyIds));
  4938. }
  4939. List<String> columnOrder = new ArrayList<String>();
  4940. for (Object propertyId : propertyIds) {
  4941. if (columns.containsKey(propertyId)) {
  4942. columnOrder.add(columnKeys.key(propertyId));
  4943. } else {
  4944. throw new IllegalArgumentException(
  4945. "Grid does not contain column for property "
  4946. + String.valueOf(propertyId));
  4947. }
  4948. }
  4949. List<String> stateColumnOrder = getState().columnOrder;
  4950. if (stateColumnOrder.size() != columnOrder.size()) {
  4951. stateColumnOrder.removeAll(columnOrder);
  4952. columnOrder.addAll(stateColumnOrder);
  4953. }
  4954. getState().columnOrder = columnOrder;
  4955. fireColumnReorderEvent(false);
  4956. }
  4957. /**
  4958. * Sets the number of frozen columns in this grid. Setting the count to 0
  4959. * means that no data columns will be frozen, but the built-in selection
  4960. * checkbox column will still be frozen if it's in use. Setting the count to
  4961. * -1 will also disable the selection column.
  4962. * <p>
  4963. * The default value is 0.
  4964. *
  4965. * @param numberOfColumns
  4966. * the number of columns that should be frozen
  4967. *
  4968. * @throws IllegalArgumentException
  4969. * if the column count is < 0 or > the number of visible columns
  4970. */
  4971. public void setFrozenColumnCount(int numberOfColumns) {
  4972. if (numberOfColumns < -1 || numberOfColumns > columns.size()) {
  4973. throw new IllegalArgumentException(
  4974. "count must be between -1 and the current number of columns ("
  4975. + columns.size() + "): " + numberOfColumns);
  4976. }
  4977. getState().frozenColumnCount = numberOfColumns;
  4978. }
  4979. /**
  4980. * Gets the number of frozen columns in this grid. 0 means that no data
  4981. * columns will be frozen, but the built-in selection checkbox column will
  4982. * still be frozen if it's in use. -1 means that not even the selection
  4983. * column is frozen.
  4984. * <p>
  4985. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  4986. * columns} in the count.
  4987. *
  4988. * @see #setFrozenColumnCount(int)
  4989. *
  4990. * @return the number of frozen columns
  4991. */
  4992. public int getFrozenColumnCount() {
  4993. return getState(false).frozenColumnCount;
  4994. }
  4995. /**
  4996. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  4997. * <p>
  4998. * If the item has visible details, its size will also be taken into
  4999. * account.
  5000. *
  5001. * @param itemId
  5002. * id of item to scroll to.
  5003. * @throws IllegalArgumentException
  5004. * if the provided id is not recognized by the data source.
  5005. */
  5006. public void scrollTo(Object itemId) throws IllegalArgumentException {
  5007. scrollTo(itemId, ScrollDestination.ANY);
  5008. }
  5009. /**
  5010. * Scrolls to a certain item, using user-specified scroll destination.
  5011. * <p>
  5012. * If the item has visible details, its size will also be taken into
  5013. * account.
  5014. *
  5015. * @param itemId
  5016. * id of item to scroll to.
  5017. * @param destination
  5018. * value specifying desired position of scrolled-to row.
  5019. * @throws IllegalArgumentException
  5020. * if the provided id is not recognized by the data source.
  5021. */
  5022. public void scrollTo(Object itemId, ScrollDestination destination)
  5023. throws IllegalArgumentException {
  5024. int row = datasource.indexOfId(itemId);
  5025. if (row == -1) {
  5026. throw new IllegalArgumentException(
  5027. "Item with specified ID does not exist in data source");
  5028. }
  5029. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  5030. clientRPC.scrollToRow(row, destination);
  5031. }
  5032. /**
  5033. * Scrolls to the beginning of the first data row.
  5034. */
  5035. public void scrollToStart() {
  5036. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  5037. clientRPC.scrollToStart();
  5038. }
  5039. /**
  5040. * Scrolls to the end of the last data row.
  5041. */
  5042. public void scrollToEnd() {
  5043. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  5044. clientRPC.scrollToEnd();
  5045. }
  5046. /**
  5047. * Sets the number of rows that should be visible in Grid's body, while
  5048. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  5049. * <p>
  5050. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  5051. * remembered, and applied once the mode is applied.
  5052. *
  5053. * @param rows
  5054. * The height in terms of number of rows displayed in Grid's
  5055. * body. If Grid doesn't contain enough rows, white space is
  5056. * displayed instead. If <code>null</code> is given, then Grid's
  5057. * height is undefined
  5058. * @throws IllegalArgumentException
  5059. * if {@code rows} is zero or less
  5060. * @throws IllegalArgumentException
  5061. * if {@code rows} is {@link Double#isInfinite(double) infinite}
  5062. * @throws IllegalArgumentException
  5063. * if {@code rows} is {@link Double#isNaN(double) NaN}
  5064. */
  5065. public void setHeightByRows(double rows) {
  5066. if (rows <= 0.0d) {
  5067. throw new IllegalArgumentException(
  5068. "More than zero rows must be shown.");
  5069. } else if (Double.isInfinite(rows)) {
  5070. throw new IllegalArgumentException(
  5071. "Grid doesn't support infinite heights");
  5072. } else if (Double.isNaN(rows)) {
  5073. throw new IllegalArgumentException("NaN is not a valid row count");
  5074. }
  5075. getState().heightByRows = rows;
  5076. }
  5077. /**
  5078. * Gets the amount of rows in Grid's body that are shown, while
  5079. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  5080. *
  5081. * @return the amount of rows that are being shown in Grid's body
  5082. * @see #setHeightByRows(double)
  5083. */
  5084. public double getHeightByRows() {
  5085. return getState(false).heightByRows;
  5086. }
  5087. /**
  5088. * {@inheritDoc}
  5089. * <p>
  5090. * <em>Note:</em> This method will change the widget's size in the browser
  5091. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  5092. *
  5093. * @see #setHeightMode(HeightMode)
  5094. */
  5095. @Override
  5096. public void setHeight(float height, Unit unit) {
  5097. super.setHeight(height, unit);
  5098. }
  5099. /**
  5100. * Defines the mode in which the Grid widget's height is calculated.
  5101. * <p>
  5102. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  5103. * via a {@code setHeight}-method, and behave as a traditional Component.
  5104. * <p>
  5105. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  5106. * will display as many rows as {@link #getHeightByRows()} defines.
  5107. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  5108. * will resize itself to still display the required amount of rows in its
  5109. * body. It also takes the horizontal scrollbar into account.
  5110. *
  5111. * @param heightMode
  5112. * the mode in to which Grid should be set
  5113. */
  5114. public void setHeightMode(HeightMode heightMode) {
  5115. /*
  5116. * This method is a workaround for the fact that Vaadin re-applies
  5117. * widget dimensions (height/width) on each state change event. The
  5118. * original design was to have setHeight and setHeightByRow be equals,
  5119. * and whichever was called the latest was considered in effect.
  5120. *
  5121. * But, because of Vaadin always calling setHeight on the widget, this
  5122. * approach doesn't work.
  5123. */
  5124. getState().heightMode = heightMode;
  5125. }
  5126. /**
  5127. * Returns the current {@link HeightMode} the Grid is in.
  5128. * <p>
  5129. * Defaults to {@link HeightMode#CSS}.
  5130. *
  5131. * @return the current HeightMode
  5132. */
  5133. public HeightMode getHeightMode() {
  5134. return getState(false).heightMode;
  5135. }
  5136. /* Selection related methods: */
  5137. /**
  5138. * Takes a new {@link SelectionModel} into use.
  5139. * <p>
  5140. * The SelectionModel that is previously in use will have all its items
  5141. * deselected. If any items were selected, this will fire a
  5142. * {@link SelectionEvent}.
  5143. * <p>
  5144. * If the given SelectionModel is already in use, this method does nothing.
  5145. *
  5146. * @param selectionModel
  5147. * the new SelectionModel to use
  5148. * @throws IllegalArgumentException
  5149. * if {@code selectionModel} is <code>null</code>
  5150. */
  5151. public void setSelectionModel(SelectionModel selectionModel)
  5152. throws IllegalArgumentException {
  5153. if (selectionModel == null) {
  5154. throw new IllegalArgumentException(
  5155. "Selection model may not be null");
  5156. }
  5157. if (this.selectionModel != selectionModel) {
  5158. Collection<Object> oldSelection;
  5159. // this.selectionModel is null on init
  5160. if (this.selectionModel != null) {
  5161. oldSelection = this.selectionModel.getSelectedRows();
  5162. this.selectionModel.remove();
  5163. } else {
  5164. oldSelection = Collections.emptyList();
  5165. }
  5166. this.selectionModel = selectionModel;
  5167. selectionModel.setGrid(this);
  5168. Collection<Object> newSelection = this.selectionModel
  5169. .getSelectedRows();
  5170. if (!SharedUtil.equals(oldSelection, newSelection)) {
  5171. fireSelectionEvent(oldSelection, newSelection);
  5172. }
  5173. // selection is included in the row data, so the client needs to be
  5174. // updated
  5175. datasourceExtension.refreshCache();
  5176. }
  5177. }
  5178. /**
  5179. * Returns the currently used {@link SelectionModel}.
  5180. *
  5181. * @return the currently used SelectionModel
  5182. */
  5183. public SelectionModel getSelectionModel() {
  5184. return selectionModel;
  5185. }
  5186. /**
  5187. * Sets the Grid's selection mode.
  5188. * <p>
  5189. * Grid supports three selection modes: multiselect, single select and no
  5190. * selection, and this is a convenience method for choosing between one of
  5191. * them.
  5192. * <p>
  5193. * Technically, this method is a shortcut that can be used instead of
  5194. * calling {@code setSelectionModel} with a specific SelectionModel
  5195. * instance. Grid comes with three built-in SelectionModel classes, and the
  5196. * {@link SelectionMode} enum represents each of them.
  5197. * <p>
  5198. * Essentially, the two following method calls are equivalent:
  5199. * <p>
  5200. * <code><pre>
  5201. * grid.setSelectionMode(SelectionMode.MULTI);
  5202. * grid.setSelectionModel(new MultiSelectionMode());
  5203. * </pre></code>
  5204. *
  5205. *
  5206. * @param selectionMode
  5207. * the selection mode to switch to
  5208. * @return The {@link SelectionModel} instance that was taken into use
  5209. * @throws IllegalArgumentException
  5210. * if {@code selectionMode} is <code>null</code>
  5211. * @see SelectionModel
  5212. */
  5213. public SelectionModel setSelectionMode(final SelectionMode selectionMode)
  5214. throws IllegalArgumentException {
  5215. if (selectionMode == null) {
  5216. throw new IllegalArgumentException(
  5217. "selection mode may not be null");
  5218. }
  5219. final SelectionModel newSelectionModel = selectionMode.createModel();
  5220. setSelectionModel(newSelectionModel);
  5221. return newSelectionModel;
  5222. }
  5223. /**
  5224. * Checks whether an item is selected or not.
  5225. *
  5226. * @param itemId
  5227. * the item id to check for
  5228. * @return <code>true</code> iff the item is selected
  5229. */
  5230. // keep this javadoc in sync with SelectionModel.isSelected
  5231. public boolean isSelected(Object itemId) {
  5232. return selectionModel.isSelected(itemId);
  5233. }
  5234. /**
  5235. * Returns a collection of all the currently selected itemIds.
  5236. * <p>
  5237. * This method is a shorthand that delegates to the
  5238. * {@link #getSelectionModel() selection model}.
  5239. *
  5240. * @return a collection of all the currently selected itemIds
  5241. */
  5242. // keep this javadoc in sync with SelectionModel.getSelectedRows
  5243. public Collection<Object> getSelectedRows() {
  5244. return getSelectionModel().getSelectedRows();
  5245. }
  5246. /**
  5247. * Gets the item id of the currently selected item.
  5248. * <p>
  5249. * This method is a shorthand that delegates to the
  5250. * {@link #getSelectionModel() selection model}. Only
  5251. * {@link SelectionModel.Single} is supported.
  5252. *
  5253. * @return the item id of the currently selected item, or <code>null</code>
  5254. * if nothing is selected
  5255. * @throws IllegalStateException
  5256. * if the selection model does not implement
  5257. * {@code SelectionModel.Single}
  5258. */
  5259. // keep this javadoc in sync with SelectionModel.Single.getSelectedRow
  5260. public Object getSelectedRow() throws IllegalStateException {
  5261. if (selectionModel instanceof SelectionModel.Single) {
  5262. return ((SelectionModel.Single) selectionModel).getSelectedRow();
  5263. } else if (selectionModel instanceof SelectionModel.Multi) {
  5264. throw new IllegalStateException("Cannot get unique selected row: "
  5265. + "Grid is in multiselect mode "
  5266. + "(the current selection model is "
  5267. + selectionModel.getClass().getName() + ").");
  5268. } else if (selectionModel instanceof SelectionModel.None) {
  5269. throw new IllegalStateException(
  5270. "Cannot get selected row: " + "Grid selection is disabled "
  5271. + "(the current selection model is "
  5272. + selectionModel.getClass().getName() + ").");
  5273. } else {
  5274. throw new IllegalStateException("Cannot get selected row: "
  5275. + "Grid selection model does not implement "
  5276. + SelectionModel.Single.class.getName() + " or "
  5277. + SelectionModel.Multi.class.getName()
  5278. + "(the current model is "
  5279. + selectionModel.getClass().getName() + ").");
  5280. }
  5281. }
  5282. /**
  5283. * Marks an item as selected.
  5284. * <p>
  5285. * This method is a shorthand that delegates to the
  5286. * {@link #getSelectionModel() selection model}. Only
  5287. * {@link SelectionModel.Single} and {@link SelectionModel.Multi} are
  5288. * supported.
  5289. *
  5290. * @param itemId
  5291. * the itemId to mark as selected
  5292. * @return <code>true</code> if the selection state changed,
  5293. * <code>false</code> if the itemId already was selected
  5294. * @throws IllegalArgumentException
  5295. * if the {@code itemId} doesn't exist in the currently active
  5296. * Container
  5297. * @throws IllegalStateException
  5298. * if the selection was illegal. One such reason might be that
  5299. * the implementation already had an item selected, and that
  5300. * needs to be explicitly deselected before re-selecting
  5301. * something.
  5302. * @throws IllegalStateException
  5303. * if the selection model does not implement
  5304. * {@code SelectionModel.Single} or {@code SelectionModel.Multi}
  5305. */
  5306. // keep this javadoc in sync with SelectionModel.Single.select
  5307. public boolean select(Object itemId)
  5308. throws IllegalArgumentException, IllegalStateException {
  5309. if (selectionModel instanceof SelectionModel.Single) {
  5310. return ((SelectionModel.Single) selectionModel).select(itemId);
  5311. } else if (selectionModel instanceof SelectionModel.Multi) {
  5312. return ((SelectionModel.Multi) selectionModel).select(itemId);
  5313. } else if (selectionModel instanceof SelectionModel.None) {
  5314. throw new IllegalStateException("Cannot select row '" + itemId
  5315. + "': Grid selection is disabled "
  5316. + "(the current selection model is "
  5317. + selectionModel.getClass().getName() + ").");
  5318. } else {
  5319. throw new IllegalStateException("Cannot select row '" + itemId
  5320. + "': Grid selection model does not implement "
  5321. + SelectionModel.Single.class.getName() + " or "
  5322. + SelectionModel.Multi.class.getName()
  5323. + "(the current model is "
  5324. + selectionModel.getClass().getName() + ").");
  5325. }
  5326. }
  5327. /**
  5328. * Marks an item as unselected.
  5329. * <p>
  5330. * This method is a shorthand that delegates to the
  5331. * {@link #getSelectionModel() selection model}. Only
  5332. * {@link SelectionModel.Single} and {@link SelectionModel.Multi} are
  5333. * supported.
  5334. *
  5335. * @param itemId
  5336. * the itemId to remove from being selected
  5337. * @return <code>true</code> if the selection state changed,
  5338. * <code>false</code> if the itemId was already selected
  5339. * @throws IllegalArgumentException
  5340. * if the {@code itemId} doesn't exist in the currently active
  5341. * Container
  5342. * @throws IllegalStateException
  5343. * if the deselection was illegal. One such reason might be that
  5344. * the implementation requires one or more items to be selected
  5345. * at all times.
  5346. * @throws IllegalStateException
  5347. * if the selection model does not implement
  5348. * {@code SelectionModel.Single} or {code SelectionModel.Multi}
  5349. */
  5350. // keep this javadoc in sync with SelectionModel.Single.deselect
  5351. public boolean deselect(Object itemId) throws IllegalStateException {
  5352. if (selectionModel instanceof SelectionModel.Single) {
  5353. if (isSelected(itemId)) {
  5354. return ((SelectionModel.Single) selectionModel).select(null);
  5355. }
  5356. return false;
  5357. } else if (selectionModel instanceof SelectionModel.Multi) {
  5358. return ((SelectionModel.Multi) selectionModel).deselect(itemId);
  5359. } else if (selectionModel instanceof SelectionModel.None) {
  5360. throw new IllegalStateException("Cannot deselect row '" + itemId
  5361. + "': Grid selection is disabled "
  5362. + "(the current selection model is "
  5363. + selectionModel.getClass().getName() + ").");
  5364. } else {
  5365. throw new IllegalStateException("Cannot deselect row '" + itemId
  5366. + "': Grid selection model does not implement "
  5367. + SelectionModel.Single.class.getName() + " or "
  5368. + SelectionModel.Multi.class.getName()
  5369. + "(the current model is "
  5370. + selectionModel.getClass().getName() + ").");
  5371. }
  5372. }
  5373. /**
  5374. * Marks all items as unselected.
  5375. * <p>
  5376. * This method is a shorthand that delegates to the
  5377. * {@link #getSelectionModel() selection model}. Only
  5378. * {@link SelectionModel.Single} and {@link SelectionModel.Multi} are
  5379. * supported.
  5380. *
  5381. * @return <code>true</code> if the selection state changed,
  5382. * <code>false</code> if the itemId was already selected
  5383. * @throws IllegalStateException
  5384. * if the deselection was illegal. One such reason might be that
  5385. * the implementation requires one or more items to be selected
  5386. * at all times.
  5387. * @throws IllegalStateException
  5388. * if the selection model does not implement
  5389. * {@code SelectionModel.Single} or {code SelectionModel.Multi}
  5390. */
  5391. public boolean deselectAll() throws IllegalStateException {
  5392. if (selectionModel instanceof SelectionModel.Single) {
  5393. if (getSelectedRow() != null) {
  5394. return deselect(getSelectedRow());
  5395. }
  5396. return false;
  5397. } else if (selectionModel instanceof SelectionModel.Multi) {
  5398. return ((SelectionModel.Multi) selectionModel).deselectAll();
  5399. } else if (selectionModel instanceof SelectionModel.None) {
  5400. throw new IllegalStateException(
  5401. "Cannot deselect all rows" + ": Grid selection is disabled "
  5402. + "(the current selection model is "
  5403. + selectionModel.getClass().getName() + ").");
  5404. } else {
  5405. throw new IllegalStateException("Cannot deselect all rows:"
  5406. + " Grid selection model does not implement "
  5407. + SelectionModel.Single.class.getName() + " or "
  5408. + SelectionModel.Multi.class.getName()
  5409. + "(the current model is "
  5410. + selectionModel.getClass().getName() + ").");
  5411. }
  5412. }
  5413. /**
  5414. * Fires a selection change event.
  5415. * <p>
  5416. * <strong>Note:</strong> This is not a method that should be called by
  5417. * application logic. This method is publicly accessible only so that
  5418. * {@link SelectionModel SelectionModels} would be able to inform Grid of
  5419. * these events.
  5420. *
  5421. * @param newSelection
  5422. * the selection that was added by this event
  5423. * @param oldSelection
  5424. * the selection that was removed by this event
  5425. */
  5426. public void fireSelectionEvent(Collection<Object> oldSelection,
  5427. Collection<Object> newSelection) {
  5428. fireEvent(new SelectionEvent(this, oldSelection, newSelection));
  5429. }
  5430. @Override
  5431. public void addSelectionListener(SelectionListener listener) {
  5432. addListener(SelectionEvent.class, listener, SELECTION_CHANGE_METHOD);
  5433. }
  5434. @Override
  5435. public void removeSelectionListener(SelectionListener listener) {
  5436. removeListener(SelectionEvent.class, listener, SELECTION_CHANGE_METHOD);
  5437. }
  5438. private void fireColumnReorderEvent(boolean userOriginated) {
  5439. fireEvent(new ColumnReorderEvent(this, userOriginated));
  5440. }
  5441. /**
  5442. * Registers a new column reorder listener.
  5443. *
  5444. * @since 7.5.0
  5445. * @param listener
  5446. * the listener to register
  5447. */
  5448. public void addColumnReorderListener(ColumnReorderListener listener) {
  5449. addListener(ColumnReorderEvent.class, listener, COLUMN_REORDER_METHOD);
  5450. }
  5451. /**
  5452. * Removes a previously registered column reorder listener.
  5453. *
  5454. * @since 7.5.0
  5455. * @param listener
  5456. * the listener to remove
  5457. */
  5458. public void removeColumnReorderListener(ColumnReorderListener listener) {
  5459. removeListener(ColumnReorderEvent.class, listener,
  5460. COLUMN_REORDER_METHOD);
  5461. }
  5462. private void fireColumnResizeEvent(Column column, boolean userOriginated) {
  5463. fireEvent(new ColumnResizeEvent(this, column, userOriginated));
  5464. }
  5465. /**
  5466. * Registers a new column resize listener.
  5467. *
  5468. * @param listener
  5469. * the listener to register
  5470. */
  5471. public void addColumnResizeListener(ColumnResizeListener listener) {
  5472. addListener(ColumnResizeEvent.class, listener, COLUMN_RESIZE_METHOD);
  5473. }
  5474. /**
  5475. * Removes a previously registered column resize listener.
  5476. *
  5477. * @param listener
  5478. * the listener to remove
  5479. */
  5480. public void removeColumnResizeListener(ColumnResizeListener listener) {
  5481. removeListener(ColumnResizeEvent.class, listener, COLUMN_RESIZE_METHOD);
  5482. }
  5483. /**
  5484. * Gets the {@link KeyMapper } being used by the data source.
  5485. *
  5486. * @return the key mapper being used by the data source
  5487. */
  5488. KeyMapper<Object> getKeyMapper() {
  5489. return datasourceExtension.getKeyMapper();
  5490. }
  5491. /**
  5492. * Adds a renderer to this grid's connector hierarchy.
  5493. *
  5494. * @param renderer
  5495. * the renderer to add
  5496. */
  5497. void addRenderer(Renderer<?> renderer) {
  5498. addExtension(renderer);
  5499. }
  5500. /**
  5501. * Sets the current sort order using the fluid Sort API. Read the
  5502. * documentation for {@link Sort} for more information.
  5503. * <p>
  5504. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  5505. * all possible sorting indicators.
  5506. *
  5507. * @param s
  5508. * a sort instance
  5509. *
  5510. * @throws IllegalStateException
  5511. * if container is not sortable (does not implement
  5512. * Container.Sortable)
  5513. * @throws IllegalArgumentException
  5514. * if trying to sort by non-existing property
  5515. */
  5516. public void sort(Sort s) {
  5517. setSortOrder(s.build());
  5518. }
  5519. /**
  5520. * Sort this Grid in ascending order by a specified property.
  5521. * <p>
  5522. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  5523. * all possible sorting indicators.
  5524. *
  5525. * @param propertyId
  5526. * a property ID
  5527. *
  5528. * @throws IllegalStateException
  5529. * if container is not sortable (does not implement
  5530. * Container.Sortable)
  5531. * @throws IllegalArgumentException
  5532. * if trying to sort by non-existing property
  5533. */
  5534. public void sort(Object propertyId) {
  5535. sort(propertyId, SortDirection.ASCENDING);
  5536. }
  5537. /**
  5538. * Sort this Grid in user-specified {@link SortOrder} by a property.
  5539. * <p>
  5540. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  5541. * all possible sorting indicators.
  5542. *
  5543. * @param propertyId
  5544. * a property ID
  5545. * @param direction
  5546. * a sort order value (ascending/descending)
  5547. *
  5548. * @throws IllegalStateException
  5549. * if container is not sortable (does not implement
  5550. * Container.Sortable)
  5551. * @throws IllegalArgumentException
  5552. * if trying to sort by non-existing property
  5553. */
  5554. public void sort(Object propertyId, SortDirection direction) {
  5555. sort(Sort.by(propertyId, direction));
  5556. }
  5557. /**
  5558. * Clear the current sort order, and re-sort the grid.
  5559. */
  5560. public void clearSortOrder() {
  5561. sortOrder.clear();
  5562. sort(false);
  5563. }
  5564. /**
  5565. * Sets the sort order to use.
  5566. * <p>
  5567. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  5568. * all possible sorting indicators.
  5569. *
  5570. * @param order
  5571. * a sort order list.
  5572. *
  5573. * @throws IllegalStateException
  5574. * if container is not sortable (does not implement
  5575. * Container.Sortable)
  5576. * @throws IllegalArgumentException
  5577. * if order is null or trying to sort by non-existing property
  5578. */
  5579. public void setSortOrder(List<SortOrder> order) {
  5580. setSortOrder(order, false);
  5581. }
  5582. private void setSortOrder(List<SortOrder> order, boolean userOriginated)
  5583. throws IllegalStateException, IllegalArgumentException {
  5584. if (!(getContainerDataSource() instanceof Container.Sortable)) {
  5585. throw new IllegalStateException(
  5586. "Attached container is not sortable (does not implement Container.Sortable)");
  5587. }
  5588. if (order == null) {
  5589. throw new IllegalArgumentException("Order list may not be null!");
  5590. }
  5591. sortOrder.clear();
  5592. Collection<?> sortableProps = ((Container.Sortable) getContainerDataSource())
  5593. .getSortableContainerPropertyIds();
  5594. for (SortOrder o : order) {
  5595. if (!sortableProps.contains(o.getPropertyId())) {
  5596. throw new IllegalArgumentException("Property "
  5597. + o.getPropertyId()
  5598. + " does not exist or is not sortable in the current container");
  5599. }
  5600. }
  5601. sortOrder.addAll(order);
  5602. sort(userOriginated);
  5603. }
  5604. /**
  5605. * Get the current sort order list.
  5606. *
  5607. * @return a sort order list
  5608. */
  5609. public List<SortOrder> getSortOrder() {
  5610. return Collections.unmodifiableList(sortOrder);
  5611. }
  5612. /**
  5613. * Apply sorting to data source.
  5614. */
  5615. private void sort(boolean userOriginated) {
  5616. Container c = getContainerDataSource();
  5617. if (c instanceof Container.Sortable) {
  5618. Container.Sortable cs = (Container.Sortable) c;
  5619. final int items = sortOrder.size();
  5620. Object[] propertyIds = new Object[items];
  5621. boolean[] directions = new boolean[items];
  5622. SortDirection[] stateDirs = new SortDirection[items];
  5623. for (int i = 0; i < items; ++i) {
  5624. SortOrder order = sortOrder.get(i);
  5625. stateDirs[i] = order.getDirection();
  5626. propertyIds[i] = order.getPropertyId();
  5627. switch (order.getDirection()) {
  5628. case ASCENDING:
  5629. directions[i] = true;
  5630. break;
  5631. case DESCENDING:
  5632. directions[i] = false;
  5633. break;
  5634. default:
  5635. throw new IllegalArgumentException("getDirection() of "
  5636. + order + " returned an unexpected value");
  5637. }
  5638. }
  5639. cs.sort(propertyIds, directions);
  5640. if (columns.keySet().containsAll(Arrays.asList(propertyIds))) {
  5641. String[] columnKeys = new String[items];
  5642. for (int i = 0; i < items; ++i) {
  5643. columnKeys[i] = this.columnKeys.key(propertyIds[i]);
  5644. }
  5645. getState().sortColumns = columnKeys;
  5646. getState(false).sortDirs = stateDirs;
  5647. } else {
  5648. // Not all sorted properties are in Grid. Remove any indicators.
  5649. getState().sortColumns = new String[] {};
  5650. getState(false).sortDirs = new SortDirection[] {};
  5651. }
  5652. fireEvent(new SortEvent(this, new ArrayList<SortOrder>(sortOrder),
  5653. userOriginated));
  5654. } else {
  5655. throw new IllegalStateException(
  5656. "Container is not sortable (does not implement Container.Sortable)");
  5657. }
  5658. }
  5659. /**
  5660. * Adds a sort order change listener that gets notified when the sort order
  5661. * changes.
  5662. *
  5663. * @param listener
  5664. * the sort order change listener to add
  5665. */
  5666. @Override
  5667. public Registration addSortListener(SortListener listener) {
  5668. addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  5669. return () -> removeListener(SortEvent.class, listener,
  5670. SORT_ORDER_CHANGE_METHOD);
  5671. }
  5672. /**
  5673. * Removes a sort order change listener previously added using
  5674. * {@link #addSortListener(SortListener)}.
  5675. *
  5676. * @param listener
  5677. * the sort order change listener to remove
  5678. */
  5679. @Override
  5680. public void removeSortListener(SortListener listener) {
  5681. removeListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  5682. }
  5683. /* Grid Headers */
  5684. /**
  5685. * Returns the header section of this grid. The default header contains a
  5686. * single row displaying the column captions.
  5687. *
  5688. * @return the header
  5689. */
  5690. protected Header getHeader() {
  5691. return header;
  5692. }
  5693. /**
  5694. * Gets the header row at given index.
  5695. *
  5696. * @param rowIndex
  5697. * 0 based index for row. Counted from top to bottom
  5698. * @return header row at given index
  5699. * @throws IllegalArgumentException
  5700. * if no row exists at given index
  5701. */
  5702. public HeaderRow getHeaderRow(int rowIndex) {
  5703. return header.getRow(rowIndex);
  5704. }
  5705. /**
  5706. * Inserts a new row at the given position to the header section. Shifts the
  5707. * row currently at that position and any subsequent rows down (adds one to
  5708. * their indices).
  5709. *
  5710. * @param index
  5711. * the position at which to insert the row
  5712. * @return the new row
  5713. *
  5714. * @throws IllegalArgumentException
  5715. * if the index is less than 0 or greater than row count
  5716. * @see #appendHeaderRow()
  5717. * @see #prependHeaderRow()
  5718. * @see #removeHeaderRow(HeaderRow)
  5719. * @see #removeHeaderRow(int)
  5720. */
  5721. public HeaderRow addHeaderRowAt(int index) {
  5722. return header.addRowAt(index);
  5723. }
  5724. /**
  5725. * Adds a new row at the bottom of the header section.
  5726. *
  5727. * @return the new row
  5728. * @see #prependHeaderRow()
  5729. * @see #addHeaderRowAt(int)
  5730. * @see #removeHeaderRow(HeaderRow)
  5731. * @see #removeHeaderRow(int)
  5732. */
  5733. public HeaderRow appendHeaderRow() {
  5734. return header.appendRow();
  5735. }
  5736. /**
  5737. * Returns the current default row of the header section. The default row is
  5738. * a special header row providing a user interface for sorting columns.
  5739. * Setting a header text for column updates cells in the default header.
  5740. *
  5741. * @return the default row or null if no default row set
  5742. */
  5743. public HeaderRow getDefaultHeaderRow() {
  5744. return header.getDefaultRow();
  5745. }
  5746. /**
  5747. * Gets the row count for the header section.
  5748. *
  5749. * @return row count
  5750. */
  5751. public int getHeaderRowCount() {
  5752. return header.getRowCount();
  5753. }
  5754. /**
  5755. * Adds a new row at the top of the header section.
  5756. *
  5757. * @return the new row
  5758. * @see #appendHeaderRow()
  5759. * @see #addHeaderRowAt(int)
  5760. * @see #removeHeaderRow(HeaderRow)
  5761. * @see #removeHeaderRow(int)
  5762. */
  5763. public HeaderRow prependHeaderRow() {
  5764. return header.prependRow();
  5765. }
  5766. /**
  5767. * Removes the given row from the header section.
  5768. *
  5769. * @param row
  5770. * the row to be removed
  5771. *
  5772. * @throws IllegalArgumentException
  5773. * if the row does not exist in this section
  5774. * @see #removeHeaderRow(int)
  5775. * @see #addHeaderRowAt(int)
  5776. * @see #appendHeaderRow()
  5777. * @see #prependHeaderRow()
  5778. */
  5779. public void removeHeaderRow(HeaderRow row) {
  5780. header.removeRow(row);
  5781. }
  5782. /**
  5783. * Removes the row at the given position from the header section.
  5784. *
  5785. * @param rowIndex
  5786. * the position of the row
  5787. *
  5788. * @throws IllegalArgumentException
  5789. * if no row exists at given index
  5790. * @see #removeHeaderRow(HeaderRow)
  5791. * @see #addHeaderRowAt(int)
  5792. * @see #appendHeaderRow()
  5793. * @see #prependHeaderRow()
  5794. */
  5795. public void removeHeaderRow(int rowIndex) {
  5796. header.removeRow(rowIndex);
  5797. }
  5798. /**
  5799. * Sets the default row of the header. The default row is a special header
  5800. * row providing a user interface for sorting columns.
  5801. *
  5802. * @param row
  5803. * the new default row, or null for no default row
  5804. *
  5805. * @throws IllegalArgumentException
  5806. * header does not contain the row
  5807. */
  5808. public void setDefaultHeaderRow(HeaderRow row) {
  5809. header.setDefaultRow(row);
  5810. }
  5811. /**
  5812. * Sets the visibility of the header section.
  5813. *
  5814. * @param visible
  5815. * true to show header section, false to hide
  5816. */
  5817. public void setHeaderVisible(boolean visible) {
  5818. header.setVisible(visible);
  5819. }
  5820. /**
  5821. * Returns the visibility of the header section.
  5822. *
  5823. * @return true if visible, false otherwise.
  5824. */
  5825. public boolean isHeaderVisible() {
  5826. return header.isVisible();
  5827. }
  5828. /* Grid Footers */
  5829. /**
  5830. * Returns the footer section of this grid. The default header contains a
  5831. * single row displaying the column captions.
  5832. *
  5833. * @return the footer
  5834. */
  5835. protected Footer getFooter() {
  5836. return footer;
  5837. }
  5838. /**
  5839. * Gets the footer row at given index.
  5840. *
  5841. * @param rowIndex
  5842. * 0 based index for row. Counted from top to bottom
  5843. * @return footer row at given index
  5844. * @throws IllegalArgumentException
  5845. * if no row exists at given index
  5846. */
  5847. public FooterRow getFooterRow(int rowIndex) {
  5848. return footer.getRow(rowIndex);
  5849. }
  5850. /**
  5851. * Inserts a new row at the given position to the footer section. Shifts the
  5852. * row currently at that position and any subsequent rows down (adds one to
  5853. * their indices).
  5854. *
  5855. * @param index
  5856. * the position at which to insert the row
  5857. * @return the new row
  5858. *
  5859. * @throws IllegalArgumentException
  5860. * if the index is less than 0 or greater than row count
  5861. * @see #appendFooterRow()
  5862. * @see #prependFooterRow()
  5863. * @see #removeFooterRow(FooterRow)
  5864. * @see #removeFooterRow(int)
  5865. */
  5866. public FooterRow addFooterRowAt(int index) {
  5867. return footer.addRowAt(index);
  5868. }
  5869. /**
  5870. * Adds a new row at the bottom of the footer section.
  5871. *
  5872. * @return the new row
  5873. * @see #prependFooterRow()
  5874. * @see #addFooterRowAt(int)
  5875. * @see #removeFooterRow(FooterRow)
  5876. * @see #removeFooterRow(int)
  5877. */
  5878. public FooterRow appendFooterRow() {
  5879. return footer.appendRow();
  5880. }
  5881. /**
  5882. * Gets the row count for the footer.
  5883. *
  5884. * @return row count
  5885. */
  5886. public int getFooterRowCount() {
  5887. return footer.getRowCount();
  5888. }
  5889. /**
  5890. * Adds a new row at the top of the footer section.
  5891. *
  5892. * @return the new row
  5893. * @see #appendFooterRow()
  5894. * @see #addFooterRowAt(int)
  5895. * @see #removeFooterRow(FooterRow)
  5896. * @see #removeFooterRow(int)
  5897. */
  5898. public FooterRow prependFooterRow() {
  5899. return footer.prependRow();
  5900. }
  5901. /**
  5902. * Removes the given row from the footer section.
  5903. *
  5904. * @param row
  5905. * the row to be removed
  5906. *
  5907. * @throws IllegalArgumentException
  5908. * if the row does not exist in this section
  5909. * @see #removeFooterRow(int)
  5910. * @see #addFooterRowAt(int)
  5911. * @see #appendFooterRow()
  5912. * @see #prependFooterRow()
  5913. */
  5914. public void removeFooterRow(FooterRow row) {
  5915. footer.removeRow(row);
  5916. }
  5917. /**
  5918. * Removes the row at the given position from the footer section.
  5919. *
  5920. * @param rowIndex
  5921. * the position of the row
  5922. *
  5923. * @throws IllegalArgumentException
  5924. * if no row exists at given index
  5925. * @see #removeFooterRow(FooterRow)
  5926. * @see #addFooterRowAt(int)
  5927. * @see #appendFooterRow()
  5928. * @see #prependFooterRow()
  5929. */
  5930. public void removeFooterRow(int rowIndex) {
  5931. footer.removeRow(rowIndex);
  5932. }
  5933. /**
  5934. * Sets the visibility of the footer section.
  5935. *
  5936. * @param visible
  5937. * true to show footer section, false to hide
  5938. */
  5939. public void setFooterVisible(boolean visible) {
  5940. footer.setVisible(visible);
  5941. }
  5942. /**
  5943. * Returns the visibility of the footer section.
  5944. *
  5945. * @return true if visible, false otherwise.
  5946. */
  5947. public boolean isFooterVisible() {
  5948. return footer.isVisible();
  5949. }
  5950. private void addComponent(Component c) {
  5951. extensionComponents.add(c);
  5952. c.setParent(this);
  5953. markAsDirty();
  5954. }
  5955. private void removeComponent(Component c) {
  5956. extensionComponents.remove(c);
  5957. c.setParent(null);
  5958. markAsDirty();
  5959. }
  5960. @Override
  5961. public Iterator<Component> iterator() {
  5962. // This is a hash set to avoid adding header/footer components inside
  5963. // merged cells multiple times
  5964. LinkedHashSet<Component> componentList = new LinkedHashSet<Component>();
  5965. Header header = getHeader();
  5966. for (int i = 0; i < header.getRowCount(); ++i) {
  5967. HeaderRow row = header.getRow(i);
  5968. for (Object propId : columns.keySet()) {
  5969. HeaderCell cell = row.getCell(propId);
  5970. if (cell.getCellState().type == GridStaticCellType.WIDGET) {
  5971. componentList.add(cell.getComponent());
  5972. }
  5973. }
  5974. }
  5975. Footer footer = getFooter();
  5976. for (int i = 0; i < footer.getRowCount(); ++i) {
  5977. FooterRow row = footer.getRow(i);
  5978. for (Object propId : columns.keySet()) {
  5979. FooterCell cell = row.getCell(propId);
  5980. if (cell.getCellState().type == GridStaticCellType.WIDGET) {
  5981. componentList.add(cell.getComponent());
  5982. }
  5983. }
  5984. }
  5985. componentList.addAll(getEditorFields());
  5986. componentList.addAll(extensionComponents);
  5987. return componentList.iterator();
  5988. }
  5989. @Override
  5990. public boolean isRendered(Component childComponent) {
  5991. if (getEditorFields().contains(childComponent)) {
  5992. // Only render editor fields if the editor is open
  5993. return isEditorActive();
  5994. } else {
  5995. // TODO Header and footer components should also only be rendered if
  5996. // the header/footer is visible
  5997. return true;
  5998. }
  5999. }
  6000. EditorClientRpc getEditorRpc() {
  6001. return getRpcProxy(EditorClientRpc.class);
  6002. }
  6003. /**
  6004. * Sets the {@code CellDescriptionGenerator} instance for generating
  6005. * optional descriptions (tooltips) for individual Grid cells. If a
  6006. * {@link RowDescriptionGenerator} is also set, the row description it
  6007. * generates is displayed for cells for which {@code generator} returns
  6008. * null.
  6009. *
  6010. * @param generator
  6011. * the description generator to use or {@code null} to remove a
  6012. * previously set generator if any
  6013. *
  6014. * @see #setRowDescriptionGenerator(RowDescriptionGenerator)
  6015. *
  6016. * @since 7.6
  6017. */
  6018. public void setCellDescriptionGenerator(
  6019. CellDescriptionGenerator generator) {
  6020. cellDescriptionGenerator = generator;
  6021. getState().hasDescriptions = (generator != null
  6022. || rowDescriptionGenerator != null);
  6023. datasourceExtension.refreshCache();
  6024. }
  6025. /**
  6026. * Returns the {@code CellDescriptionGenerator} instance used to generate
  6027. * descriptions (tooltips) for Grid cells.
  6028. *
  6029. * @return the description generator or {@code null} if no generator is set
  6030. *
  6031. * @since 7.6
  6032. */
  6033. public CellDescriptionGenerator getCellDescriptionGenerator() {
  6034. return cellDescriptionGenerator;
  6035. }
  6036. /**
  6037. * Sets the {@code RowDescriptionGenerator} instance for generating optional
  6038. * descriptions (tooltips) for Grid rows. If a
  6039. * {@link CellDescriptionGenerator} is also set, the row description
  6040. * generated by {@code generator} is used for cells for which the cell
  6041. * description generator returns null.
  6042. *
  6043. *
  6044. * @param generator
  6045. * the description generator to use or {@code null} to remove a
  6046. * previously set generator if any
  6047. *
  6048. * @see #setCellDescriptionGenerator(CellDescriptionGenerator)
  6049. *
  6050. * @since 7.6
  6051. */
  6052. public void setRowDescriptionGenerator(RowDescriptionGenerator generator) {
  6053. rowDescriptionGenerator = generator;
  6054. getState().hasDescriptions = (generator != null
  6055. || cellDescriptionGenerator != null);
  6056. datasourceExtension.refreshCache();
  6057. }
  6058. /**
  6059. * Returns the {@code RowDescriptionGenerator} instance used to generate
  6060. * descriptions (tooltips) for Grid rows
  6061. *
  6062. * @return the description generator or {@code} null if no generator is set
  6063. *
  6064. * @since 7.6
  6065. */
  6066. public RowDescriptionGenerator getRowDescriptionGenerator() {
  6067. return rowDescriptionGenerator;
  6068. }
  6069. /**
  6070. * Sets the style generator that is used for generating styles for cells
  6071. *
  6072. * @param cellStyleGenerator
  6073. * the cell style generator to set, or <code>null</code> to
  6074. * remove a previously set generator
  6075. */
  6076. public void setCellStyleGenerator(CellStyleGenerator cellStyleGenerator) {
  6077. this.cellStyleGenerator = cellStyleGenerator;
  6078. datasourceExtension.refreshCache();
  6079. }
  6080. /**
  6081. * Gets the style generator that is used for generating styles for cells
  6082. *
  6083. * @return the cell style generator, or <code>null</code> if no generator is
  6084. * set
  6085. */
  6086. public CellStyleGenerator getCellStyleGenerator() {
  6087. return cellStyleGenerator;
  6088. }
  6089. /**
  6090. * Sets the style generator that is used for generating styles for rows
  6091. *
  6092. * @param rowStyleGenerator
  6093. * the row style generator to set, or <code>null</code> to remove
  6094. * a previously set generator
  6095. */
  6096. public void setRowStyleGenerator(RowStyleGenerator rowStyleGenerator) {
  6097. this.rowStyleGenerator = rowStyleGenerator;
  6098. datasourceExtension.refreshCache();
  6099. }
  6100. /**
  6101. * Gets the style generator that is used for generating styles for rows
  6102. *
  6103. * @return the row style generator, or <code>null</code> if no generator is
  6104. * set
  6105. */
  6106. public RowStyleGenerator getRowStyleGenerator() {
  6107. return rowStyleGenerator;
  6108. }
  6109. /**
  6110. * Adds a row to the underlying container. The order of the parameters
  6111. * should match the current visible column order.
  6112. * <p>
  6113. * Please note that it's generally only safe to use this method during
  6114. * initialization. After Grid has been initialized and the visible column
  6115. * order might have been changed, it's better to instead add items directly
  6116. * to the underlying container and use {@link Item#getItemProperty(Object)}
  6117. * to make sure each value is assigned to the intended property.
  6118. *
  6119. * @param values
  6120. * the cell values of the new row, in the same order as the
  6121. * visible column order, not <code>null</code>.
  6122. * @return the item id of the new row
  6123. * @throws IllegalArgumentException
  6124. * if values is null
  6125. * @throws IllegalArgumentException
  6126. * if its length does not match the number of visible columns
  6127. * @throws IllegalArgumentException
  6128. * if a parameter value is not an instance of the corresponding
  6129. * property type
  6130. * @throws UnsupportedOperationException
  6131. * if the container does not support adding new items
  6132. */
  6133. public Object addRow(Object... values) {
  6134. if (values == null) {
  6135. throw new IllegalArgumentException("Values cannot be null");
  6136. }
  6137. Indexed dataSource = getContainerDataSource();
  6138. List<String> columnOrder = getState(false).columnOrder;
  6139. if (values.length != columnOrder.size()) {
  6140. throw new IllegalArgumentException(
  6141. "There are " + columnOrder.size() + " visible columns, but "
  6142. + values.length + " cell values were provided.");
  6143. }
  6144. // First verify all parameter types
  6145. for (int i = 0; i < columnOrder.size(); i++) {
  6146. Object propertyId = getPropertyIdByColumnId(columnOrder.get(i));
  6147. Class<?> propertyType = dataSource.getType(propertyId);
  6148. if (values[i] != null && !propertyType.isInstance(values[i])) {
  6149. throw new IllegalArgumentException("Parameter " + i + "("
  6150. + values[i] + ") is not an instance of "
  6151. + propertyType.getCanonicalName());
  6152. }
  6153. }
  6154. Object itemId = dataSource.addItem();
  6155. try {
  6156. Item item = dataSource.getItem(itemId);
  6157. for (int i = 0; i < columnOrder.size(); i++) {
  6158. Object propertyId = getPropertyIdByColumnId(columnOrder.get(i));
  6159. Property<Object> property = item.getItemProperty(propertyId);
  6160. property.setValue(values[i]);
  6161. }
  6162. } catch (RuntimeException e) {
  6163. try {
  6164. dataSource.removeItem(itemId);
  6165. } catch (Exception e2) {
  6166. getLogger().log(Level.SEVERE,
  6167. "Error recovering from exception in addRow", e);
  6168. }
  6169. throw e;
  6170. }
  6171. return itemId;
  6172. }
  6173. /**
  6174. * Refreshes, i.e. causes the client side to re-render the rows with the
  6175. * given item ids.
  6176. * <p>
  6177. * Calling this for a row which is not currently rendered on the client side
  6178. * has no effect.
  6179. *
  6180. * @param itemIds
  6181. * the item id(s) of the row to refresh.
  6182. */
  6183. public void refreshRows(Object... itemIds) {
  6184. for (Object itemId : itemIds) {
  6185. datasourceExtension.updateRowData(itemId);
  6186. }
  6187. }
  6188. /**
  6189. * Refreshes, i.e. causes the client side to re-render all rows.
  6190. *
  6191. * @since 7.7.7
  6192. */
  6193. public void refreshAllRows() {
  6194. datasourceExtension.refreshCache();
  6195. }
  6196. private static Logger getLogger() {
  6197. return Logger.getLogger(Grid.class.getName());
  6198. }
  6199. /**
  6200. * Sets whether or not the item editor UI is enabled for this grid. When the
  6201. * editor is enabled, the user can open it by double-clicking a row or
  6202. * hitting enter when a row is focused. The editor can also be opened
  6203. * programmatically using the {@link #editItem(Object)} method.
  6204. *
  6205. * @param isEnabled
  6206. * <code>true</code> to enable the feature, <code>false</code>
  6207. * otherwise
  6208. * @throws IllegalStateException
  6209. * if an item is currently being edited
  6210. *
  6211. * @see #getEditedItemId()
  6212. */
  6213. public void setEditorEnabled(boolean isEnabled)
  6214. throws IllegalStateException {
  6215. if (isEditorActive()) {
  6216. throw new IllegalStateException(
  6217. "Cannot disable the editor while an item ("
  6218. + getEditedItemId() + ") is being edited");
  6219. }
  6220. if (isEditorEnabled() != isEnabled) {
  6221. getState().editorEnabled = isEnabled;
  6222. }
  6223. }
  6224. /**
  6225. * Checks whether the item editor UI is enabled for this grid.
  6226. *
  6227. * @return <code>true</code> iff the editor is enabled for this grid
  6228. *
  6229. * @see #setEditorEnabled(boolean)
  6230. * @see #getEditedItemId()
  6231. */
  6232. public boolean isEditorEnabled() {
  6233. return getState(false).editorEnabled;
  6234. }
  6235. /**
  6236. * Gets the id of the item that is currently being edited.
  6237. *
  6238. * @return the id of the item that is currently being edited, or
  6239. * <code>null</code> if no item is being edited at the moment
  6240. */
  6241. public Object getEditedItemId() {
  6242. return editedItemId;
  6243. }
  6244. /**
  6245. * Gets the field group that is backing the item editor of this grid.
  6246. *
  6247. * @return the backing field group
  6248. */
  6249. public FieldGroup getEditorFieldGroup() {
  6250. return editorFieldGroup;
  6251. }
  6252. /**
  6253. * Sets the field group that is backing the item editor of this grid.
  6254. *
  6255. * @param fieldGroup
  6256. * the backing field group
  6257. *
  6258. * @throws IllegalStateException
  6259. * if the editor is currently active
  6260. */
  6261. public void setEditorFieldGroup(FieldGroup fieldGroup) {
  6262. if (isEditorActive()) {
  6263. throw new IllegalStateException(
  6264. "Cannot change field group while an item ("
  6265. + getEditedItemId() + ") is being edited");
  6266. }
  6267. editorFieldGroup = fieldGroup;
  6268. }
  6269. /**
  6270. * Returns whether an item is currently being edited in the editor.
  6271. *
  6272. * @return true iff the editor is open
  6273. */
  6274. public boolean isEditorActive() {
  6275. return editorActive;
  6276. }
  6277. private void checkColumnExists(Object propertyId) {
  6278. if (getColumn(propertyId) == null) {
  6279. throw new IllegalArgumentException(
  6280. "There is no column with the property id " + propertyId);
  6281. }
  6282. }
  6283. private Field<?> getEditorField(Object propertyId) {
  6284. checkColumnExists(propertyId);
  6285. if (!getColumn(propertyId).isEditable()) {
  6286. return null;
  6287. }
  6288. Field<?> editor = editorFieldGroup.getField(propertyId);
  6289. // If field group has no field for this property, see if we have it
  6290. // stored
  6291. if (editor == null) {
  6292. editor = editorFields.get(propertyId);
  6293. if (editor != null) {
  6294. editorFieldGroup.bind(editor, propertyId);
  6295. }
  6296. }
  6297. // Otherwise try to build one
  6298. try {
  6299. if (editor == null) {
  6300. editor = editorFieldGroup.buildAndBind(propertyId);
  6301. }
  6302. } finally {
  6303. if (editor == null) {
  6304. editor = editorFieldGroup.getField(propertyId);
  6305. }
  6306. if (editor != null && editor.getParent() != Grid.this) {
  6307. assert editor.getParent() == null;
  6308. editor.setParent(this);
  6309. }
  6310. }
  6311. return editor;
  6312. }
  6313. /**
  6314. * Opens the editor interface for the provided item. Scrolls the Grid to
  6315. * bring the item to view if it is not already visible.
  6316. *
  6317. * Note that any cell content rendered by a WidgetRenderer will not be
  6318. * visible in the editor row.
  6319. *
  6320. * @param itemId
  6321. * the id of the item to edit
  6322. * @throws IllegalStateException
  6323. * if the editor is not enabled or already editing an item in
  6324. * buffered mode
  6325. * @throws IllegalArgumentException
  6326. * if the {@code itemId} is not in the backing container
  6327. * @see #setEditorEnabled(boolean)
  6328. */
  6329. public void editItem(Object itemId)
  6330. throws IllegalStateException, IllegalArgumentException {
  6331. if (!isEditorEnabled()) {
  6332. throw new IllegalStateException("Item editor is not enabled");
  6333. } else if (isEditorBuffered() && editedItemId != null) {
  6334. throw new IllegalStateException("Editing item " + itemId
  6335. + " failed. Item editor is already editing item "
  6336. + editedItemId);
  6337. } else if (!getContainerDataSource().containsId(itemId)) {
  6338. throw new IllegalArgumentException("Item with id " + itemId
  6339. + " not found in current container");
  6340. }
  6341. editedItemId = itemId;
  6342. getEditorRpc().bind(getContainerDataSource().indexOfId(itemId));
  6343. }
  6344. protected void doEditItem() {
  6345. Item item = getContainerDataSource().getItem(editedItemId);
  6346. editorFieldGroup.setItemDataSource(item);
  6347. for (Column column : getColumns()) {
  6348. column.getState().editorConnector = item
  6349. .getItemProperty(column.getPropertyId()) == null ? null
  6350. : getEditorField(column.getPropertyId());
  6351. }
  6352. editorActive = true;
  6353. // Must ensure that all fields, recursively, are sent to the client
  6354. // This is needed because the fields are hidden using isRendered
  6355. for (Field<?> f : getEditorFields()) {
  6356. f.markAsDirtyRecursive();
  6357. }
  6358. if (datasource instanceof ItemSetChangeNotifier) {
  6359. ((ItemSetChangeNotifier) datasource)
  6360. .addItemSetChangeListener(editorClosingItemSetListener);
  6361. }
  6362. }
  6363. private void setEditorField(Object propertyId, Field<?> field) {
  6364. checkColumnExists(propertyId);
  6365. Field<?> oldField = editorFieldGroup.getField(propertyId);
  6366. if (oldField != null) {
  6367. editorFieldGroup.unbind(oldField);
  6368. oldField.setParent(null);
  6369. }
  6370. if (field != null) {
  6371. field.setParent(this);
  6372. editorFieldGroup.bind(field, propertyId);
  6373. }
  6374. // Store field for this property for future reference
  6375. editorFields.put(propertyId, field);
  6376. }
  6377. /**
  6378. * Saves all changes done to the bound fields.
  6379. * <p>
  6380. * <em>Note:</em> This is a pass-through call to the backing field group.
  6381. *
  6382. * @throws CommitException
  6383. * If the commit was aborted
  6384. *
  6385. * @see FieldGroup#commit()
  6386. */
  6387. public void saveEditor() throws CommitException {
  6388. try {
  6389. editorSaving = true;
  6390. editorFieldGroup.commit();
  6391. } finally {
  6392. editorSaving = false;
  6393. }
  6394. }
  6395. /**
  6396. * Cancels the currently active edit if any. Hides the editor and discards
  6397. * possible unsaved changes in the editor fields.
  6398. */
  6399. public void cancelEditor() {
  6400. if (editorSaving) {
  6401. // If the editor is already saving the values, it's too late to
  6402. // cancel it. This prevents item set changes from propagating during
  6403. // save, causing discard to be run during commit.
  6404. return;
  6405. }
  6406. if (isEditorActive()) {
  6407. getEditorRpc()
  6408. .cancel(getContainerDataSource().indexOfId(editedItemId));
  6409. doCancelEditor();
  6410. }
  6411. }
  6412. protected void doCancelEditor() {
  6413. editedItemId = null;
  6414. editorActive = false;
  6415. editorFieldGroup.discard();
  6416. editorFieldGroup.setItemDataSource(null);
  6417. if (datasource instanceof ItemSetChangeNotifier) {
  6418. ((ItemSetChangeNotifier) datasource)
  6419. .removeItemSetChangeListener(editorClosingItemSetListener);
  6420. }
  6421. // Mark Grid as dirty so the client side gets to know that the editors
  6422. // are no longer attached
  6423. markAsDirty();
  6424. }
  6425. void resetEditor() {
  6426. if (isEditorActive()) {
  6427. /*
  6428. * Simply force cancel the editing; throwing here would just make
  6429. * Grid.setContainerDataSource semantics more complicated.
  6430. */
  6431. cancelEditor();
  6432. }
  6433. for (Field<?> editor : getEditorFields()) {
  6434. editor.setParent(null);
  6435. }
  6436. editedItemId = null;
  6437. editorActive = false;
  6438. editorFieldGroup = new CustomFieldGroup();
  6439. }
  6440. /**
  6441. * Gets a collection of all fields bound to the item editor of this grid.
  6442. * <p>
  6443. * When {@link #editItem(Object) editItem} is called, fields are
  6444. * automatically created and bound to any unbound properties.
  6445. *
  6446. * @return a collection of all the fields bound to the item editor
  6447. */
  6448. Collection<Field<?>> getEditorFields() {
  6449. Collection<Field<?>> fields = editorFieldGroup.getFields();
  6450. assert allAttached(fields);
  6451. return fields;
  6452. }
  6453. private boolean allAttached(Collection<? extends Component> components) {
  6454. for (Component component : components) {
  6455. if (component.getParent() != this) {
  6456. return false;
  6457. }
  6458. }
  6459. return true;
  6460. }
  6461. /**
  6462. * Sets the field factory for the {@link FieldGroup}. The field factory is
  6463. * only used when {@link FieldGroup} creates a new field.
  6464. * <p>
  6465. * <em>Note:</em> This is a pass-through call to the backing field group.
  6466. *
  6467. * @param fieldFactory
  6468. * The field factory to use
  6469. */
  6470. public void setEditorFieldFactory(FieldGroupFieldFactory fieldFactory) {
  6471. editorFieldGroup.setFieldFactory(fieldFactory);
  6472. }
  6473. /**
  6474. * Sets the error handler for the editor.
  6475. *
  6476. * The error handler is called whenever there is an exception in the editor.
  6477. *
  6478. * @param editorErrorHandler
  6479. * The editor error handler to use
  6480. * @throws IllegalArgumentException
  6481. * if the error handler is null
  6482. */
  6483. public void setEditorErrorHandler(EditorErrorHandler editorErrorHandler)
  6484. throws IllegalArgumentException {
  6485. if (editorErrorHandler == null) {
  6486. throw new IllegalArgumentException(
  6487. "The error handler cannot be null");
  6488. }
  6489. this.editorErrorHandler = editorErrorHandler;
  6490. }
  6491. /**
  6492. * Gets the error handler used for the editor
  6493. *
  6494. * @see #setErrorHandler(com.vaadin.server.ErrorHandler)
  6495. * @return the editor error handler, never null
  6496. */
  6497. public EditorErrorHandler getEditorErrorHandler() {
  6498. return editorErrorHandler;
  6499. }
  6500. /**
  6501. * Gets the field factory for the {@link FieldGroup}. The field factory is
  6502. * only used when {@link FieldGroup} creates a new field.
  6503. * <p>
  6504. * <em>Note:</em> This is a pass-through call to the backing field group.
  6505. *
  6506. * @return The field factory in use
  6507. */
  6508. public FieldGroupFieldFactory getEditorFieldFactory() {
  6509. return editorFieldGroup.getFieldFactory();
  6510. }
  6511. /**
  6512. * Sets the caption on the save button in the Grid editor.
  6513. *
  6514. * @param saveCaption
  6515. * the caption to set
  6516. * @throws IllegalArgumentException
  6517. * if {@code saveCaption} is {@code null}
  6518. */
  6519. public void setEditorSaveCaption(String saveCaption)
  6520. throws IllegalArgumentException {
  6521. if (saveCaption == null) {
  6522. throw new IllegalArgumentException("Save caption cannot be null");
  6523. }
  6524. getState().editorSaveCaption = saveCaption;
  6525. }
  6526. /**
  6527. * Gets the current caption of the save button in the Grid editor.
  6528. *
  6529. * @return the current caption of the save button
  6530. */
  6531. public String getEditorSaveCaption() {
  6532. return getState(false).editorSaveCaption;
  6533. }
  6534. /**
  6535. * Sets the caption on the cancel button in the Grid editor.
  6536. *
  6537. * @param cancelCaption
  6538. * the caption to set
  6539. * @throws IllegalArgumentException
  6540. * if {@code cancelCaption} is {@code null}
  6541. */
  6542. public void setEditorCancelCaption(String cancelCaption)
  6543. throws IllegalArgumentException {
  6544. if (cancelCaption == null) {
  6545. throw new IllegalArgumentException("Cancel caption cannot be null");
  6546. }
  6547. getState().editorCancelCaption = cancelCaption;
  6548. }
  6549. /**
  6550. * Gets the current caption of the cancel button in the Grid editor.
  6551. *
  6552. * @return the current caption of the cancel button
  6553. */
  6554. public String getEditorCancelCaption() {
  6555. return getState(false).editorCancelCaption;
  6556. }
  6557. /**
  6558. * Sets the buffered editor mode. The default mode is buffered (
  6559. * <code>true</code>).
  6560. *
  6561. * @since 7.6
  6562. * @param editorBuffered
  6563. * <code>true</code> to enable buffered editor,
  6564. * <code>false</code> to disable it
  6565. * @throws IllegalStateException
  6566. * If editor is active while attempting to change the buffered
  6567. * mode.
  6568. */
  6569. public void setEditorBuffered(boolean editorBuffered)
  6570. throws IllegalStateException {
  6571. if (isEditorActive()) {
  6572. throw new IllegalStateException(
  6573. "Can't change editor unbuffered mode while editor is active.");
  6574. }
  6575. getState().editorBuffered = editorBuffered;
  6576. editorFieldGroup.setBuffered(editorBuffered);
  6577. }
  6578. /**
  6579. * Gets the buffered editor mode.
  6580. *
  6581. * @since 7.6
  6582. * @return <code>true</code> if buffered editor is enabled,
  6583. * <code>false</code> otherwise
  6584. */
  6585. public boolean isEditorBuffered() {
  6586. return getState(false).editorBuffered;
  6587. }
  6588. @Override
  6589. public void addItemClickListener(ItemClickListener listener) {
  6590. addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  6591. listener, ItemClickEvent.ITEM_CLICK_METHOD);
  6592. }
  6593. @Override
  6594. @Deprecated
  6595. public void addListener(ItemClickListener listener) {
  6596. addItemClickListener(listener);
  6597. }
  6598. @Override
  6599. public void removeItemClickListener(ItemClickListener listener) {
  6600. removeListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  6601. listener);
  6602. }
  6603. @Override
  6604. @Deprecated
  6605. public void removeListener(ItemClickListener listener) {
  6606. removeItemClickListener(listener);
  6607. }
  6608. /**
  6609. * Requests that the column widths should be recalculated.
  6610. * <p>
  6611. * In most cases Grid will know when column widths need to be recalculated
  6612. * but this method can be used to force recalculation in situations when
  6613. * grid does not recalculate automatically.
  6614. *
  6615. * @since 7.4.1
  6616. */
  6617. public void recalculateColumnWidths() {
  6618. getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
  6619. }
  6620. /**
  6621. * Registers a new column visibility change listener
  6622. *
  6623. * @since 7.5.0
  6624. * @param listener
  6625. * the listener to register
  6626. */
  6627. public void addColumnVisibilityChangeListener(
  6628. ColumnVisibilityChangeListener listener) {
  6629. addListener(ColumnVisibilityChangeEvent.class, listener,
  6630. COLUMN_VISIBILITY_METHOD);
  6631. }
  6632. /**
  6633. * Removes a previously registered column visibility change listener
  6634. *
  6635. * @since 7.5.0
  6636. * @param listener
  6637. * the listener to remove
  6638. */
  6639. public void removeColumnVisibilityChangeListener(
  6640. ColumnVisibilityChangeListener listener) {
  6641. removeListener(ColumnVisibilityChangeEvent.class, listener,
  6642. COLUMN_VISIBILITY_METHOD);
  6643. }
  6644. private void fireColumnVisibilityChangeEvent(Column column, boolean hidden,
  6645. boolean isUserOriginated) {
  6646. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  6647. isUserOriginated));
  6648. }
  6649. /**
  6650. * Sets a new details generator for row details.
  6651. * <p>
  6652. * The currently opened row details will be re-rendered.
  6653. *
  6654. * @since 7.5.0
  6655. * @param detailsGenerator
  6656. * the details generator to set
  6657. * @throws IllegalArgumentException
  6658. * if detailsGenerator is <code>null</code>;
  6659. */
  6660. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  6661. throws IllegalArgumentException {
  6662. detailComponentManager.setDetailsGenerator(detailsGenerator);
  6663. }
  6664. /**
  6665. * Gets the current details generator for row details.
  6666. *
  6667. * @since 7.5.0
  6668. * @return the detailsGenerator the current details generator
  6669. */
  6670. public DetailsGenerator getDetailsGenerator() {
  6671. return detailComponentManager.getDetailsGenerator();
  6672. }
  6673. /**
  6674. * Shows or hides the details for a specific item.
  6675. *
  6676. * @since 7.5.0
  6677. * @param itemId
  6678. * the id of the item for which to set details visibility
  6679. * @param visible
  6680. * <code>true</code> to show the details, or <code>false</code>
  6681. * to hide them
  6682. */
  6683. public void setDetailsVisible(Object itemId, boolean visible) {
  6684. detailComponentManager.setDetailsVisible(itemId, visible);
  6685. }
  6686. /**
  6687. * Checks whether details are visible for the given item.
  6688. *
  6689. * @since 7.5.0
  6690. * @param itemId
  6691. * the id of the item for which to check details visibility
  6692. * @return <code>true</code> iff the details are visible
  6693. */
  6694. public boolean isDetailsVisible(Object itemId) {
  6695. return detailComponentManager.isDetailsVisible(itemId);
  6696. }
  6697. private static SelectionMode getDefaultSelectionMode() {
  6698. return SelectionMode.SINGLE;
  6699. }
  6700. @Override
  6701. public void readDesign(Element design, DesignContext context) {
  6702. super.readDesign(design, context);
  6703. Attributes attrs = design.attributes();
  6704. if (attrs.hasKey("editable")) {
  6705. setEditorEnabled(DesignAttributeHandler.readAttribute("editable",
  6706. attrs, boolean.class));
  6707. }
  6708. if (attrs.hasKey("rows")) {
  6709. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  6710. double.class));
  6711. setHeightMode(HeightMode.ROW);
  6712. }
  6713. if (attrs.hasKey("selection-mode")) {
  6714. setSelectionMode(DesignAttributeHandler.readAttribute(
  6715. "selection-mode", attrs, SelectionMode.class));
  6716. }
  6717. if (design.children().size() > 0) {
  6718. if (design.children().size() > 1
  6719. || !design.child(0).tagName().equals("table")) {
  6720. throw new DesignException(
  6721. "Grid needs to have a table element as its only child");
  6722. }
  6723. Element table = design.child(0);
  6724. Elements colgroups = table.getElementsByTag("colgroup");
  6725. if (colgroups.size() != 1) {
  6726. throw new DesignException(
  6727. "Table element in declarative Grid needs to have a"
  6728. + " colgroup defining the columns used in Grid");
  6729. }
  6730. int i = 0;
  6731. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  6732. String propertyId = DesignAttributeHandler.readAttribute(
  6733. "property-id", col.attributes(), "property-" + i,
  6734. String.class);
  6735. addColumn(propertyId, String.class).readDesign(col, context);
  6736. ++i;
  6737. }
  6738. for (Element child : table.children()) {
  6739. if (child.tagName().equals("thead")) {
  6740. header.readDesign(child, context);
  6741. } else if (child.tagName().equals("tbody")) {
  6742. for (Element row : child.children()) {
  6743. Elements cells = row.children();
  6744. Object[] data = new String[cells.size()];
  6745. for (int c = 0; c < cells.size(); ++c) {
  6746. data[c] = cells.get(c).html();
  6747. }
  6748. addRow(data);
  6749. }
  6750. // Since inline data is used, set HTML renderer for columns
  6751. for (Column c : getColumns()) {
  6752. c.setRenderer(new HtmlRenderer());
  6753. }
  6754. } else if (child.tagName().equals("tfoot")) {
  6755. footer.readDesign(child, context);
  6756. }
  6757. }
  6758. }
  6759. // Read frozen columns after columns are read.
  6760. if (attrs.hasKey("frozen-columns")) {
  6761. setFrozenColumnCount(DesignAttributeHandler
  6762. .readAttribute("frozen-columns", attrs, int.class));
  6763. }
  6764. }
  6765. @Override
  6766. public void writeDesign(Element design, DesignContext context) {
  6767. super.writeDesign(design, context);
  6768. Attributes attrs = design.attributes();
  6769. Grid def = context.getDefaultInstance(this);
  6770. DesignAttributeHandler.writeAttribute("editable", attrs,
  6771. isEditorEnabled(), def.isEditorEnabled(), boolean.class,
  6772. context);
  6773. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  6774. getFrozenColumnCount(), def.getFrozenColumnCount(), int.class,
  6775. context);
  6776. if (getHeightMode() == HeightMode.ROW) {
  6777. DesignAttributeHandler.writeAttribute("rows", attrs,
  6778. getHeightByRows(), def.getHeightByRows(), double.class,
  6779. context);
  6780. }
  6781. SelectionMode selectionMode = null;
  6782. if (selectionModel.getClass().equals(SingleSelectionModel.class)) {
  6783. selectionMode = SelectionMode.SINGLE;
  6784. } else if (selectionModel.getClass()
  6785. .equals(MultiSelectionModel.class)) {
  6786. selectionMode = SelectionMode.MULTI;
  6787. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  6788. selectionMode = SelectionMode.NONE;
  6789. }
  6790. assert selectionMode != null : "Unexpected selection model "
  6791. + selectionModel.getClass().getName();
  6792. DesignAttributeHandler.writeAttribute("selection-mode", attrs,
  6793. selectionMode, getDefaultSelectionMode(), SelectionMode.class,
  6794. context);
  6795. if (columns.isEmpty()) {
  6796. // Empty grid. Structure not needed.
  6797. return;
  6798. }
  6799. // Do structure.
  6800. Element tableElement = design.appendElement("table");
  6801. Element colGroup = tableElement.appendElement("colgroup");
  6802. List<Column> columnOrder = getColumns();
  6803. for (int i = 0; i < columnOrder.size(); ++i) {
  6804. Column column = columnOrder.get(i);
  6805. Element colElement = colGroup.appendElement("col");
  6806. column.writeDesign(colElement, context);
  6807. }
  6808. // Always write thead. Reads correctly when there no header rows
  6809. header.writeDesign(tableElement.appendElement("thead"), context);
  6810. if (context.shouldWriteData(this)) {
  6811. Element bodyElement = tableElement.appendElement("tbody");
  6812. for (Object itemId : datasource.getItemIds()) {
  6813. Element tableRow = bodyElement.appendElement("tr");
  6814. for (Column c : getColumns()) {
  6815. Object value = datasource.getItem(itemId)
  6816. .getItemProperty(c.getPropertyId()).getValue();
  6817. tableRow.appendElement("td")
  6818. .append((value != null ? DesignFormatter
  6819. .encodeForTextNode(value.toString()) : ""));
  6820. }
  6821. }
  6822. }
  6823. if (footer.getRowCount() > 0) {
  6824. footer.writeDesign(tableElement.appendElement("tfoot"), context);
  6825. }
  6826. }
  6827. @Override
  6828. public void addBlurListener(BlurListener listener) {
  6829. addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener,
  6830. BlurListener.blurMethod);
  6831. }
  6832. @Override
  6833. public void removeBlurListener(BlurListener listener) {
  6834. removeListener(BlurEvent.EVENT_ID, BlurEvent.class, listener);
  6835. }
  6836. @Override
  6837. public void addFocusListener(FocusListener listener) {
  6838. addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener,
  6839. FocusListener.focusMethod);
  6840. }
  6841. @Override
  6842. public void removeFocusListener(FocusListener listener) {
  6843. removeListener(FocusEvent.EVENT_ID, FocusEvent.class, listener);
  6844. }
  6845. @Override
  6846. public void focus() {
  6847. super.focus();
  6848. }
  6849. @Override
  6850. public int getTabIndex() {
  6851. return getState(false).tabIndex;
  6852. }
  6853. @Override
  6854. public void setTabIndex(int tabIndex) {
  6855. getState().tabIndex = tabIndex;
  6856. }
  6857. @Override
  6858. protected Collection<String> getCustomAttributes() {
  6859. Collection<String> result = super.getCustomAttributes();
  6860. result.add("editor-enabled");
  6861. result.add("editable");
  6862. result.add("frozen-column-count");
  6863. result.add("frozen-columns");
  6864. result.add("height-by-rows");
  6865. result.add("rows");
  6866. result.add("selection-mode");
  6867. result.add("header-visible");
  6868. result.add("footer-visible");
  6869. result.add("editor-error-handler");
  6870. result.add("height-mode");
  6871. return result;
  6872. }
  6873. }