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

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