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

Grid.java 174KB

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