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

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