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

LegacyGrid.java 253KB

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