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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Type;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.Comparator;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.LinkedHashSet;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Objects;
  32. import java.util.Optional;
  33. import java.util.Set;
  34. import java.util.UUID;
  35. import java.util.function.BinaryOperator;
  36. import java.util.function.Function;
  37. import java.util.stream.Collectors;
  38. import java.util.stream.Stream;
  39. import org.jsoup.nodes.Attributes;
  40. import org.jsoup.nodes.Element;
  41. import org.jsoup.select.Elements;
  42. import com.vaadin.data.BeanPropertySet;
  43. import com.vaadin.data.Binder;
  44. import com.vaadin.data.Binder.Binding;
  45. import com.vaadin.data.HasDataProvider;
  46. import com.vaadin.data.HasValue;
  47. import com.vaadin.data.PropertyDefinition;
  48. import com.vaadin.data.PropertySet;
  49. import com.vaadin.data.ValueProvider;
  50. import com.vaadin.data.provider.CallbackDataProvider;
  51. import com.vaadin.data.provider.DataCommunicator;
  52. import com.vaadin.data.provider.DataGenerator;
  53. import com.vaadin.data.provider.DataProvider;
  54. import com.vaadin.data.provider.GridSortOrder;
  55. import com.vaadin.data.provider.GridSortOrderBuilder;
  56. import com.vaadin.data.provider.Query;
  57. import com.vaadin.data.provider.QuerySortOrder;
  58. import com.vaadin.event.ConnectorEvent;
  59. import com.vaadin.event.ContextClickEvent;
  60. import com.vaadin.event.HasUserOriginated;
  61. import com.vaadin.event.SortEvent;
  62. import com.vaadin.event.SortEvent.SortListener;
  63. import com.vaadin.event.SortEvent.SortNotifier;
  64. import com.vaadin.event.selection.MultiSelectionListener;
  65. import com.vaadin.event.selection.SelectionListener;
  66. import com.vaadin.event.selection.SingleSelectionListener;
  67. import com.vaadin.server.AbstractExtension;
  68. import com.vaadin.server.EncodeResult;
  69. import com.vaadin.server.Extension;
  70. import com.vaadin.server.JsonCodec;
  71. import com.vaadin.server.SerializableComparator;
  72. import com.vaadin.server.SerializableSupplier;
  73. import com.vaadin.server.Setter;
  74. import com.vaadin.server.VaadinServiceClassLoaderUtil;
  75. import com.vaadin.shared.Connector;
  76. import com.vaadin.shared.MouseEventDetails;
  77. import com.vaadin.shared.Registration;
  78. import com.vaadin.shared.data.DataCommunicatorConstants;
  79. import com.vaadin.shared.data.sort.SortDirection;
  80. import com.vaadin.shared.ui.grid.AbstractGridExtensionState;
  81. import com.vaadin.shared.ui.grid.ColumnResizeMode;
  82. import com.vaadin.shared.ui.grid.ColumnState;
  83. import com.vaadin.shared.ui.grid.DetailsManagerState;
  84. import com.vaadin.shared.ui.grid.GridClientRpc;
  85. import com.vaadin.shared.ui.grid.GridConstants;
  86. import com.vaadin.shared.ui.grid.GridConstants.Section;
  87. import com.vaadin.shared.ui.grid.GridServerRpc;
  88. import com.vaadin.shared.ui.grid.GridState;
  89. import com.vaadin.shared.ui.grid.GridStaticCellType;
  90. import com.vaadin.shared.ui.grid.HeightMode;
  91. import com.vaadin.shared.ui.grid.ScrollDestination;
  92. import com.vaadin.shared.ui.grid.SectionState;
  93. import com.vaadin.ui.components.grid.ColumnReorderListener;
  94. import com.vaadin.ui.components.grid.ColumnResizeListener;
  95. import com.vaadin.ui.components.grid.ColumnVisibilityChangeListener;
  96. import com.vaadin.ui.components.grid.DescriptionGenerator;
  97. import com.vaadin.ui.components.grid.DetailsGenerator;
  98. import com.vaadin.ui.components.grid.Editor;
  99. import com.vaadin.ui.components.grid.EditorImpl;
  100. import com.vaadin.ui.components.grid.Footer;
  101. import com.vaadin.ui.components.grid.FooterRow;
  102. import com.vaadin.ui.components.grid.GridSelectionModel;
  103. import com.vaadin.ui.components.grid.Header;
  104. import com.vaadin.ui.components.grid.Header.Row;
  105. import com.vaadin.ui.components.grid.HeaderCell;
  106. import com.vaadin.ui.components.grid.HeaderRow;
  107. import com.vaadin.ui.components.grid.ItemClickListener;
  108. import com.vaadin.ui.components.grid.MultiSelectionModel;
  109. import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
  110. import com.vaadin.ui.components.grid.NoSelectionModel;
  111. import com.vaadin.ui.components.grid.SingleSelectionModel;
  112. import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
  113. import com.vaadin.ui.components.grid.SortOrderProvider;
  114. import com.vaadin.ui.declarative.DesignAttributeHandler;
  115. import com.vaadin.ui.declarative.DesignContext;
  116. import com.vaadin.ui.declarative.DesignException;
  117. import com.vaadin.ui.declarative.DesignFormatter;
  118. import com.vaadin.ui.renderers.AbstractRenderer;
  119. import com.vaadin.ui.renderers.ComponentRenderer;
  120. import com.vaadin.ui.renderers.HtmlRenderer;
  121. import com.vaadin.ui.renderers.Renderer;
  122. import com.vaadin.ui.renderers.TextRenderer;
  123. import com.vaadin.util.ReflectTools;
  124. import elemental.json.Json;
  125. import elemental.json.JsonObject;
  126. import elemental.json.JsonValue;
  127. /**
  128. * A grid component for displaying tabular data.
  129. *
  130. * @author Vaadin Ltd
  131. * @since 8.0
  132. *
  133. * @param <T>
  134. * the grid bean type
  135. */
  136. public class Grid<T> extends AbstractListing<T> implements HasComponents,
  137. HasDataProvider<T>, SortNotifier<GridSortOrder<T>> {
  138. private static final String DECLARATIVE_DATA_ITEM_TYPE = "data-item-type";
  139. /**
  140. * A callback method for fetching items. The callback is provided with a
  141. * list of sort orders, offset index and limit.
  142. *
  143. * @param <T>
  144. * the grid bean type
  145. */
  146. @FunctionalInterface
  147. public interface FetchItemsCallback<T> extends Serializable {
  148. /**
  149. * Returns a stream of items ordered by given sort orders, limiting the
  150. * results with given offset and limit.
  151. * <p>
  152. * This method is called after the size of the data set is asked from a
  153. * related size callback. The offset and limit are promised to be within
  154. * the size of the data set.
  155. *
  156. * @param sortOrder
  157. * a list of sort orders
  158. * @param offset
  159. * the first index to fetch
  160. * @param limit
  161. * the fetched item count
  162. * @return stream of items
  163. */
  164. public Stream<T> fetchItems(List<QuerySortOrder> sortOrder, int offset,
  165. int limit);
  166. }
  167. @Deprecated
  168. private static final Method COLUMN_REORDER_METHOD = ReflectTools.findMethod(
  169. ColumnReorderListener.class, "columnReorder",
  170. ColumnReorderEvent.class);
  171. private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
  172. .findMethod(SortListener.class, "sort", SortEvent.class);
  173. @Deprecated
  174. private static final Method COLUMN_RESIZE_METHOD = ReflectTools.findMethod(
  175. ColumnResizeListener.class, "columnResize",
  176. ColumnResizeEvent.class);
  177. @Deprecated
  178. private static final Method ITEM_CLICK_METHOD = ReflectTools
  179. .findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
  180. @Deprecated
  181. private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
  182. .findMethod(ColumnVisibilityChangeListener.class,
  183. "columnVisibilityChanged",
  184. ColumnVisibilityChangeEvent.class);
  185. /**
  186. * Selection mode representing the built-in selection models in grid.
  187. * <p>
  188. * These enums can be used in {@link Grid#setSelectionMode(SelectionMode)}
  189. * to easily switch between the build-in selection models.
  190. *
  191. * @see Grid#setSelectionMode(SelectionMode)
  192. * @see Grid#setSelectionModel(GridSelectionModel)
  193. */
  194. public enum SelectionMode {
  195. /**
  196. * Single selection mode that maps to build-in
  197. * {@link SingleSelectionModel}.
  198. *
  199. * @see SingleSelectionModelImpl
  200. */
  201. SINGLE {
  202. @Override
  203. protected <T> GridSelectionModel<T> createModel() {
  204. return new SingleSelectionModelImpl<>();
  205. }
  206. },
  207. /**
  208. * Multiselection mode that maps to build-in {@link MultiSelectionModel}
  209. * .
  210. *
  211. * @see MultiSelectionModelImpl
  212. */
  213. MULTI {
  214. @Override
  215. protected <T> GridSelectionModel<T> createModel() {
  216. return new MultiSelectionModelImpl<>();
  217. }
  218. },
  219. /**
  220. * Selection model that doesn't allow selection.
  221. *
  222. * @see NoSelectionModel
  223. */
  224. NONE {
  225. @Override
  226. protected <T> GridSelectionModel<T> createModel() {
  227. return new NoSelectionModel<>();
  228. }
  229. };
  230. /**
  231. * Creates the selection model to use with this enum.
  232. *
  233. * @param <T>
  234. * the type of items in the grid
  235. * @return the selection model
  236. */
  237. protected abstract <T> GridSelectionModel<T> createModel();
  238. }
  239. /**
  240. * An event that is fired when the columns are reordered.
  241. */
  242. public static class ColumnReorderEvent extends Component.Event
  243. implements HasUserOriginated {
  244. private final boolean userOriginated;
  245. /**
  246. *
  247. * @param source
  248. * the grid where the event originated from
  249. * @param userOriginated
  250. * <code>true</code> if event is a result of user
  251. * interaction, <code>false</code> if from API call
  252. */
  253. public ColumnReorderEvent(Grid source, boolean userOriginated) {
  254. super(source);
  255. this.userOriginated = userOriginated;
  256. }
  257. /**
  258. * Returns <code>true</code> if the column reorder was done by the user,
  259. * <code>false</code> if not and it was triggered by server side code.
  260. *
  261. * @return <code>true</code> if event is a result of user interaction
  262. */
  263. @Override
  264. public boolean isUserOriginated() {
  265. return userOriginated;
  266. }
  267. }
  268. /**
  269. * An event that is fired when a column is resized, either programmatically
  270. * or by the user.
  271. */
  272. public static class ColumnResizeEvent extends Component.Event
  273. implements HasUserOriginated {
  274. private final Column<?, ?> column;
  275. private final boolean userOriginated;
  276. /**
  277. *
  278. * @param source
  279. * the grid where the event originated from
  280. * @param userOriginated
  281. * <code>true</code> if event is a result of user
  282. * interaction, <code>false</code> if from API call
  283. */
  284. public ColumnResizeEvent(Grid<?> source, Column<?, ?> column,
  285. boolean userOriginated) {
  286. super(source);
  287. this.column = column;
  288. this.userOriginated = userOriginated;
  289. }
  290. /**
  291. * Returns the column that was resized.
  292. *
  293. * @return the resized column.
  294. */
  295. public Column<?, ?> getColumn() {
  296. return column;
  297. }
  298. /**
  299. * Returns <code>true</code> if the column resize was done by the user,
  300. * <code>false</code> if not and it was triggered by server side code.
  301. *
  302. * @return <code>true</code> if event is a result of user interaction
  303. */
  304. @Override
  305. public boolean isUserOriginated() {
  306. return userOriginated;
  307. }
  308. }
  309. /**
  310. * An event fired when an item in the Grid has been clicked.
  311. *
  312. * @param <T>
  313. * the grid bean type
  314. */
  315. public static class ItemClick<T> extends ConnectorEvent {
  316. private final T item;
  317. private final Column<T, ?> column;
  318. private final MouseEventDetails mouseEventDetails;
  319. /**
  320. * Creates a new {@code ItemClick} event containing the given item and
  321. * Column originating from the given Grid.
  322. *
  323. */
  324. public ItemClick(Grid<T> source, Column<T, ?> column, T item,
  325. MouseEventDetails mouseEventDetails) {
  326. super(source);
  327. this.column = column;
  328. this.item = item;
  329. this.mouseEventDetails = mouseEventDetails;
  330. }
  331. /**
  332. * Returns the clicked item.
  333. *
  334. * @return the clicked item
  335. */
  336. public T getItem() {
  337. return item;
  338. }
  339. /**
  340. * Returns the clicked column.
  341. *
  342. * @return the clicked column
  343. */
  344. public Column<T, ?> getColumn() {
  345. return column;
  346. }
  347. /**
  348. * Returns the source Grid.
  349. *
  350. * @return the grid
  351. */
  352. @Override
  353. public Grid<T> getSource() {
  354. return (Grid<T>) super.getSource();
  355. }
  356. /**
  357. * Returns the mouse event details.
  358. *
  359. * @return the mouse event details
  360. */
  361. public MouseEventDetails getMouseEventDetails() {
  362. return mouseEventDetails;
  363. }
  364. }
  365. /**
  366. * ContextClickEvent for the Grid Component.
  367. *
  368. * <p>
  369. * Usage:
  370. *
  371. * <pre>
  372. * grid.addContextClickListener(event -&gt; Notification.show(
  373. * ((GridContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
  374. * </pre>
  375. *
  376. * @param <T>
  377. * the grid bean type
  378. */
  379. public static class GridContextClickEvent<T> extends ContextClickEvent {
  380. private final T item;
  381. private final int rowIndex;
  382. private final Column<T, ?> column;
  383. private final Section section;
  384. /**
  385. * Creates a new context click event.
  386. *
  387. * @param source
  388. * the grid where the context click occurred
  389. * @param mouseEventDetails
  390. * details about mouse position
  391. * @param section
  392. * the section of the grid which was clicked
  393. * @param rowIndex
  394. * the index of the row which was clicked
  395. * @param item
  396. * the item which was clicked
  397. * @param column
  398. * the column which was clicked
  399. */
  400. public GridContextClickEvent(Grid<T> source,
  401. MouseEventDetails mouseEventDetails, Section section,
  402. int rowIndex, T item, Column<T, ?> column) {
  403. super(source, mouseEventDetails);
  404. this.item = item;
  405. this.section = section;
  406. this.column = column;
  407. this.rowIndex = rowIndex;
  408. }
  409. /**
  410. * Returns the item of context clicked row.
  411. *
  412. * @return item of clicked row; <code>null</code> if header or footer
  413. */
  414. public T getItem() {
  415. return item;
  416. }
  417. /**
  418. * Returns the clicked column.
  419. *
  420. * @return the clicked column
  421. */
  422. public Column<T, ?> getColumn() {
  423. return column;
  424. }
  425. /**
  426. * Return the clicked section of Grid.
  427. *
  428. * @return section of grid
  429. */
  430. public Section getSection() {
  431. return section;
  432. }
  433. /**
  434. * Returns the clicked row index.
  435. * <p>
  436. * Header and Footer rows for index can be fetched with
  437. * {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
  438. *
  439. * @return row index in section
  440. */
  441. public int getRowIndex() {
  442. return rowIndex;
  443. }
  444. @Override
  445. public Grid<T> getComponent() {
  446. return (Grid<T>) super.getComponent();
  447. }
  448. }
  449. /**
  450. * An event that is fired when a column's visibility changes.
  451. *
  452. * @since 7.5.0
  453. */
  454. public static class ColumnVisibilityChangeEvent extends Component.Event
  455. implements HasUserOriginated {
  456. private final Column<?, ?> column;
  457. private final boolean userOriginated;
  458. private final boolean hidden;
  459. /**
  460. * Constructor for a column visibility change event.
  461. *
  462. * @param source
  463. * the grid from which this event originates
  464. * @param column
  465. * the column that changed its visibility
  466. * @param hidden
  467. * <code>true</code> if the column was hidden,
  468. * <code>false</code> if it became visible
  469. * @param isUserOriginated
  470. * <code>true</code> if the event was triggered by an UI
  471. * interaction
  472. */
  473. public ColumnVisibilityChangeEvent(Grid<?> source, Column<?, ?> column,
  474. boolean hidden, boolean isUserOriginated) {
  475. super(source);
  476. this.column = column;
  477. this.hidden = hidden;
  478. userOriginated = isUserOriginated;
  479. }
  480. /**
  481. * Gets the column that became hidden or visible.
  482. *
  483. * @return the column that became hidden or visible.
  484. * @see Column#isHidden()
  485. */
  486. public Column<?, ?> getColumn() {
  487. return column;
  488. }
  489. /**
  490. * Was the column set hidden or visible.
  491. *
  492. * @return <code>true</code> if the column was hidden <code>false</code>
  493. * if it was set visible
  494. */
  495. public boolean isHidden() {
  496. return hidden;
  497. }
  498. @Override
  499. public boolean isUserOriginated() {
  500. return userOriginated;
  501. }
  502. }
  503. /**
  504. * A helper base class for creating extensions for the Grid component.
  505. *
  506. * @param <T>
  507. */
  508. public abstract static class AbstractGridExtension<T>
  509. extends AbstractListingExtension<T> {
  510. @Override
  511. public void extend(AbstractListing<T> grid) {
  512. if (!(grid instanceof Grid)) {
  513. throw new IllegalArgumentException(
  514. getClass().getSimpleName() + " can only extend Grid");
  515. }
  516. super.extend(grid);
  517. }
  518. /**
  519. * Adds given component to the connector hierarchy of Grid.
  520. *
  521. * @param c
  522. * the component to add
  523. */
  524. protected void addComponentToGrid(Component c) {
  525. getParent().addExtensionComponent(c);
  526. }
  527. /**
  528. * Removes given component from the connector hierarchy of Grid.
  529. *
  530. * @param c
  531. * the component to remove
  532. */
  533. protected void removeComponentFromGrid(Component c) {
  534. getParent().removeExtensionComponent(c);
  535. }
  536. @Override
  537. public Grid<T> getParent() {
  538. return (Grid<T>) super.getParent();
  539. }
  540. @Override
  541. protected AbstractGridExtensionState getState() {
  542. return (AbstractGridExtensionState) super.getState();
  543. }
  544. @Override
  545. protected AbstractGridExtensionState getState(boolean markAsDirty) {
  546. return (AbstractGridExtensionState) super.getState(markAsDirty);
  547. }
  548. protected String getInternalIdForColumn(Column<T, ?> column) {
  549. return getParent().getInternalIdForColumn(column);
  550. }
  551. }
  552. private final class GridServerRpcImpl implements GridServerRpc {
  553. @Override
  554. public void sort(String[] columnInternalIds, SortDirection[] directions,
  555. boolean isUserOriginated) {
  556. assert columnInternalIds.length == directions.length : "Column and sort direction counts don't match.";
  557. List<GridSortOrder<T>> list = new ArrayList<>(directions.length);
  558. for (int i = 0; i < columnInternalIds.length; ++i) {
  559. Column<T, ?> column = columnKeys.get(columnInternalIds[i]);
  560. list.add(new GridSortOrder<>(column, directions[i]));
  561. }
  562. setSortOrder(list, isUserOriginated);
  563. }
  564. @Override
  565. public void itemClick(String rowKey, String columnInternalId,
  566. MouseEventDetails details) {
  567. Column<T, ?> column = getColumnByInternalId(columnInternalId);
  568. T item = getDataCommunicator().getKeyMapper().get(rowKey);
  569. fireEvent(new ItemClick<>(Grid.this, column, item, details));
  570. }
  571. @Override
  572. public void contextClick(int rowIndex, String rowKey,
  573. String columnInternalId, Section section,
  574. MouseEventDetails details) {
  575. T item = null;
  576. if (rowKey != null) {
  577. item = getDataCommunicator().getKeyMapper().get(rowKey);
  578. }
  579. fireEvent(new GridContextClickEvent<>(Grid.this, details, section,
  580. rowIndex, item, getColumnByInternalId(columnInternalId)));
  581. }
  582. @Override
  583. public void columnsReordered(List<String> newColumnOrder,
  584. List<String> oldColumnOrder) {
  585. final String diffStateKey = "columnOrder";
  586. ConnectorTracker connectorTracker = getUI().getConnectorTracker();
  587. JsonObject diffState = connectorTracker.getDiffState(Grid.this);
  588. // discard the change if the columns have been reordered from
  589. // the server side, as the server side is always right
  590. if (getState(false).columnOrder.equals(oldColumnOrder)) {
  591. // Don't mark as dirty since client has the state already
  592. getState(false).columnOrder = newColumnOrder;
  593. // write changes to diffState so that possible reverting the
  594. // column order is sent to client
  595. assert diffState
  596. .hasKey(diffStateKey) : "Field name has changed";
  597. Type type = null;
  598. try {
  599. type = getState(false).getClass().getField(diffStateKey)
  600. .getGenericType();
  601. } catch (NoSuchFieldException | SecurityException e) {
  602. e.printStackTrace();
  603. }
  604. EncodeResult encodeResult = JsonCodec.encode(
  605. getState(false).columnOrder, diffState, type,
  606. connectorTracker);
  607. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  608. fireColumnReorderEvent(true);
  609. } else {
  610. // make sure the client is reverted to the order that the
  611. // server thinks it is
  612. diffState.remove(diffStateKey);
  613. markAsDirty();
  614. }
  615. }
  616. @Override
  617. public void columnVisibilityChanged(String internalId, boolean hidden) {
  618. Column<T, ?> column = getColumnByInternalId(internalId);
  619. if (column.isHidden() != hidden) {
  620. column.setHidden(hidden);
  621. fireColumnVisibilityChangeEvent(column, hidden, true);
  622. }
  623. }
  624. @Override
  625. public void columnResized(String internalId, double pixels) {
  626. final Column<T, ?> column = getColumnByInternalId(internalId);
  627. if (column != null && column.isResizable()) {
  628. column.getState().width = pixels;
  629. fireColumnResizeEvent(column, true);
  630. }
  631. }
  632. }
  633. /**
  634. * Class for managing visible details rows.
  635. *
  636. * @param <T>
  637. * the grid bean type
  638. */
  639. public static class DetailsManager<T> extends AbstractGridExtension<T> {
  640. private final Set<T> visibleDetails = new HashSet<>();
  641. private final Map<T, Component> components = new HashMap<>();
  642. private DetailsGenerator<T> generator;
  643. /**
  644. * Sets the details component generator.
  645. *
  646. * @param generator
  647. * the generator for details components
  648. */
  649. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  650. if (this.generator != generator) {
  651. removeAllComponents();
  652. }
  653. this.generator = generator;
  654. visibleDetails.forEach(this::refresh);
  655. }
  656. @Override
  657. public void remove() {
  658. removeAllComponents();
  659. super.remove();
  660. }
  661. private void removeAllComponents() {
  662. // Clean up old components
  663. components.values().forEach(this::removeComponentFromGrid);
  664. components.clear();
  665. }
  666. @Override
  667. public void generateData(T item, JsonObject jsonObject) {
  668. if (generator == null || !visibleDetails.contains(item)) {
  669. return;
  670. }
  671. if (!components.containsKey(item)) {
  672. Component detailsComponent = generator.apply(item);
  673. Objects.requireNonNull(detailsComponent,
  674. "Details generator can't create null components");
  675. if (detailsComponent.getParent() != null) {
  676. throw new IllegalStateException(
  677. "Details component was already attached");
  678. }
  679. addComponentToGrid(detailsComponent);
  680. components.put(item, detailsComponent);
  681. }
  682. jsonObject.put(GridState.JSONKEY_DETAILS_VISIBLE,
  683. components.get(item).getConnectorId());
  684. }
  685. @Override
  686. public void destroyData(T item) {
  687. // No clean up needed. Components are removed when hiding details
  688. // and/or changing details generator
  689. }
  690. /**
  691. * Sets the visibility of details component for given item.
  692. *
  693. * @param item
  694. * the item to show details for
  695. * @param visible
  696. * {@code true} if details component should be visible;
  697. * {@code false} if it should be hidden
  698. */
  699. public void setDetailsVisible(T item, boolean visible) {
  700. boolean refresh = false;
  701. if (!visible) {
  702. refresh = visibleDetails.remove(item);
  703. if (components.containsKey(item)) {
  704. removeComponentFromGrid(components.remove(item));
  705. }
  706. } else {
  707. refresh = visibleDetails.add(item);
  708. }
  709. if (refresh) {
  710. refresh(item);
  711. }
  712. }
  713. /**
  714. * Returns the visibility of details component for given item.
  715. *
  716. * @param item
  717. * the item to show details for
  718. *
  719. * @return {@code true} if details component should be visible;
  720. * {@code false} if it should be hidden
  721. */
  722. public boolean isDetailsVisible(T item) {
  723. return visibleDetails.contains(item);
  724. }
  725. @Override
  726. public Grid<T> getParent() {
  727. return super.getParent();
  728. }
  729. @Override
  730. protected DetailsManagerState getState() {
  731. return (DetailsManagerState) super.getState();
  732. }
  733. @Override
  734. protected DetailsManagerState getState(boolean markAsDirty) {
  735. return (DetailsManagerState) super.getState(markAsDirty);
  736. }
  737. }
  738. /**
  739. * This extension manages the configuration and data communication for a
  740. * Column inside of a Grid component.
  741. *
  742. * @param <T>
  743. * the grid bean type
  744. * @param <V>
  745. * the column value type
  746. */
  747. public static class Column<T, V> extends AbstractExtension {
  748. private final ValueProvider<T, V> valueProvider;
  749. private ValueProvider<V, ?> presentationProvider;
  750. private SortOrderProvider sortOrderProvider = direction -> {
  751. String id = getId();
  752. if (id == null) {
  753. return Stream.empty();
  754. } else {
  755. return Stream.of(new QuerySortOrder(id, direction));
  756. }
  757. };
  758. private SerializableComparator<T> comparator;
  759. private StyleGenerator<T> styleGenerator = item -> null;
  760. private DescriptionGenerator<T> descriptionGenerator;
  761. private DataGenerator<T> dataGenerator = new DataGenerator<T>() {
  762. @Override
  763. public void generateData(T item, JsonObject jsonObject) {
  764. ColumnState state = getState(false);
  765. String communicationId = getConnectorId();
  766. assert communicationId != null : "No communication ID set for column "
  767. + state.caption;
  768. JsonObject obj = getDataObject(jsonObject,
  769. DataCommunicatorConstants.DATA);
  770. obj.put(communicationId, generateRendererValue(item,
  771. presentationProvider, state.renderer));
  772. String style = styleGenerator.apply(item);
  773. if (style != null && !style.isEmpty()) {
  774. JsonObject styleObj = getDataObject(jsonObject,
  775. GridState.JSONKEY_CELLSTYLES);
  776. styleObj.put(communicationId, style);
  777. }
  778. if (descriptionGenerator != null) {
  779. String description = descriptionGenerator.apply(item);
  780. if (description != null && !description.isEmpty()) {
  781. JsonObject descriptionObj = getDataObject(jsonObject,
  782. GridState.JSONKEY_CELLDESCRIPTION);
  783. descriptionObj.put(communicationId, description);
  784. }
  785. }
  786. }
  787. @Override
  788. public void destroyData(T item) {
  789. removeComponent(getGrid().getDataProvider().getId(item));
  790. }
  791. @Override
  792. public void destroyAllData() {
  793. // Make a defensive copy of keys, as the map gets cleared when
  794. // removing components.
  795. new HashSet<>(activeComponents.keySet())
  796. .forEach(component -> removeComponent(component));
  797. }
  798. };
  799. private Binding<T, ?> editorBinding;
  800. private Map<Object, Component> activeComponents = new HashMap<>();
  801. private String userId;
  802. /**
  803. * Constructs a new Column configuration with given renderer and value
  804. * provider.
  805. *
  806. * @param valueProvider
  807. * the function to get values from items, not
  808. * <code>null</code>
  809. * @param renderer
  810. * the value renderer, not <code>null</code>
  811. */
  812. protected Column(ValueProvider<T, V> valueProvider,
  813. Renderer<? super V> renderer) {
  814. this(valueProvider, ValueProvider.identity(), renderer);
  815. }
  816. /**
  817. * Constructs a new Column configuration with given renderer and value
  818. * provider.
  819. * <p>
  820. * For a more complete explanation on presentation provider, see
  821. * {@link #setRenderer(ValueProvider, Renderer)}.
  822. *
  823. * @param valueProvider
  824. * the function to get values from items, not
  825. * <code>null</code>
  826. * @param presentationProvider
  827. * the function to get presentations from the value of this
  828. * column, not <code>null</code>. For more details, see
  829. * {@link #setRenderer(ValueProvider, Renderer)}
  830. * @param renderer
  831. * the presentation renderer, not <code>null</code>
  832. * @param <P>
  833. * the presentation type
  834. *
  835. * @since 8.1
  836. */
  837. protected <P> Column(ValueProvider<T, V> valueProvider,
  838. ValueProvider<V, P> presentationProvider,
  839. Renderer<? super P> renderer) {
  840. Objects.requireNonNull(valueProvider,
  841. "Value provider can't be null");
  842. Objects.requireNonNull(presentationProvider,
  843. "Presentation provider can't be null");
  844. Objects.requireNonNull(renderer, "Renderer can't be null");
  845. ColumnState state = getState();
  846. this.valueProvider = valueProvider;
  847. this.presentationProvider = presentationProvider;
  848. state.renderer = renderer;
  849. state.caption = "";
  850. // Add the renderer as a child extension of this extension, thus
  851. // ensuring the renderer will be unregistered when this column is
  852. // removed
  853. addExtension(renderer);
  854. Class<? super P> valueType = renderer.getPresentationType();
  855. if (Comparable.class.isAssignableFrom(valueType)) {
  856. comparator = (a, b) -> compareComparables(
  857. valueProvider.apply(a), valueProvider.apply(b));
  858. } else if (Number.class.isAssignableFrom(valueType)) {
  859. /*
  860. * Value type will be Number whenever using NumberRenderer.
  861. * Provide explicit comparison support in this case even though
  862. * Number itself isn't Comparable.
  863. */
  864. comparator = (a, b) -> compareNumbers(
  865. (Number) valueProvider.apply(a),
  866. (Number) valueProvider.apply(b));
  867. } else {
  868. comparator = (a, b) -> compareMaybeComparables(
  869. valueProvider.apply(a), valueProvider.apply(b));
  870. }
  871. }
  872. private static int compareMaybeComparables(Object a, Object b) {
  873. if (hasCommonComparableBaseType(a, b)) {
  874. return compareComparables(a, b);
  875. } else {
  876. return compareComparables(Objects.toString(a, ""),
  877. Objects.toString(b, ""));
  878. }
  879. }
  880. private static boolean hasCommonComparableBaseType(Object a, Object b) {
  881. if (a instanceof Comparable<?> && b instanceof Comparable<?>) {
  882. Class<?> aClass = a.getClass();
  883. Class<?> bClass = b.getClass();
  884. if (aClass == bClass) {
  885. return true;
  886. }
  887. Class<?> baseType = ReflectTools.findCommonBaseType(aClass,
  888. bClass);
  889. if (Comparable.class.isAssignableFrom(baseType)) {
  890. return true;
  891. }
  892. }
  893. if ((a == null && b instanceof Comparable<?>)
  894. || (b == null && a instanceof Comparable<?>)) {
  895. return true;
  896. }
  897. return false;
  898. }
  899. @SuppressWarnings("unchecked")
  900. private static int compareComparables(Object a, Object b) {
  901. return ((Comparator) Comparator
  902. .nullsLast(Comparator.naturalOrder())).compare(a, b);
  903. }
  904. @SuppressWarnings("unchecked")
  905. private static int compareNumbers(Number a, Number b) {
  906. Number valueA = a != null ? a : Double.POSITIVE_INFINITY;
  907. Number valueB = b != null ? b : Double.POSITIVE_INFINITY;
  908. // Most Number implementations are Comparable
  909. if (valueA instanceof Comparable
  910. && valueA.getClass().isInstance(valueB)) {
  911. return ((Comparable<Number>) valueA).compareTo(valueB);
  912. } else if (valueA.equals(valueB)) {
  913. return 0;
  914. } else {
  915. // Fall back to comparing based on potentially truncated values
  916. int compare = Long.compare(valueA.longValue(),
  917. valueB.longValue());
  918. if (compare == 0) {
  919. // This might still produce 0 even though the values are not
  920. // equals, but there's nothing more we can do about that
  921. compare = Double.compare(valueA.doubleValue(),
  922. valueB.doubleValue());
  923. }
  924. return compare;
  925. }
  926. }
  927. @SuppressWarnings("unchecked")
  928. private <P> JsonValue generateRendererValue(T item,
  929. ValueProvider<V, P> presentationProvider, Connector renderer) {
  930. P presentationValue = presentationProvider
  931. .apply(valueProvider.apply(item));
  932. // Make Grid track components.
  933. if (renderer instanceof ComponentRenderer
  934. && presentationValue instanceof Component) {
  935. addComponent(getGrid().getDataProvider().getId(item),
  936. (Component) presentationValue);
  937. }
  938. return ((Renderer<P>) renderer).encode(presentationValue);
  939. }
  940. private void addComponent(Object item, Component component) {
  941. if (activeComponents.containsKey(item)) {
  942. if (activeComponents.get(item).equals(component)) {
  943. // Reusing old component
  944. return;
  945. }
  946. removeComponent(item);
  947. }
  948. activeComponents.put(item, component);
  949. getGrid().addExtensionComponent(component);
  950. }
  951. private void removeComponent(Object item) {
  952. Component component = activeComponents.remove(item);
  953. if (component != null) {
  954. getGrid().removeExtensionComponent(component);
  955. }
  956. }
  957. /**
  958. * Gets a data object with the given key from the given JsonObject. If
  959. * there is no object with the key, this method creates a new
  960. * JsonObject.
  961. *
  962. * @param jsonObject
  963. * the json object
  964. * @param key
  965. * the key where the desired data object is stored
  966. * @return data object for the given key
  967. */
  968. private JsonObject getDataObject(JsonObject jsonObject, String key) {
  969. if (!jsonObject.hasKey(key)) {
  970. jsonObject.put(key, Json.createObject());
  971. }
  972. return jsonObject.getObject(key);
  973. }
  974. @Override
  975. protected ColumnState getState() {
  976. return getState(true);
  977. }
  978. @Override
  979. protected ColumnState getState(boolean markAsDirty) {
  980. return (ColumnState) super.getState(markAsDirty);
  981. }
  982. /**
  983. * This method extends the given Grid with this Column.
  984. *
  985. * @param grid
  986. * the grid to extend
  987. */
  988. private void extend(Grid<T> grid) {
  989. super.extend(grid);
  990. }
  991. /**
  992. * Returns the identifier used with this Column in communication.
  993. *
  994. * @return the identifier string
  995. */
  996. private String getInternalId() {
  997. return getState(false).internalId;
  998. }
  999. /**
  1000. * Sets the identifier to use with this Column in communication.
  1001. *
  1002. * @param id
  1003. * the identifier string
  1004. */
  1005. private void setInternalId(String id) {
  1006. Objects.requireNonNull(id, "Communication ID can't be null");
  1007. getState().internalId = id;
  1008. }
  1009. /**
  1010. * Returns the user-defined identifier for this column.
  1011. *
  1012. * @return the identifier string
  1013. */
  1014. public String getId() {
  1015. return userId;
  1016. }
  1017. /**
  1018. * Sets the user-defined identifier to map this column. The identifier
  1019. * can be used for example in {@link Grid#getColumn(String)}.
  1020. * <p>
  1021. * The id is also used as the {@link #setSortProperty(String...) backend
  1022. * sort property} for this column if no sort property or sort order
  1023. * provider has been set for this column.
  1024. *
  1025. * @see #setSortProperty(String...)
  1026. * @see #setSortOrderProvider(SortOrderProvider)
  1027. *
  1028. * @param id
  1029. * the identifier string
  1030. * @return this column
  1031. */
  1032. public Column<T, V> setId(String id) {
  1033. Objects.requireNonNull(id, "Column identifier cannot be null");
  1034. if (this.userId != null) {
  1035. throw new IllegalStateException(
  1036. "Column identifier cannot be changed");
  1037. }
  1038. this.userId = id;
  1039. getGrid().setColumnId(id, this);
  1040. return this;
  1041. }
  1042. /**
  1043. * Gets the function used to produce the value for data in this column
  1044. * based on the row item.
  1045. *
  1046. * @return the value provider function
  1047. *
  1048. * @since 8.0.3
  1049. */
  1050. public ValueProvider<T, V> getValueProvider() {
  1051. return valueProvider;
  1052. }
  1053. /**
  1054. * Sets whether the user can sort this column or not.
  1055. *
  1056. * @param sortable
  1057. * {@code true} if the column can be sorted by the user;
  1058. * {@code false} if not
  1059. * @return this column
  1060. */
  1061. public Column<T, V> setSortable(boolean sortable) {
  1062. getState().sortable = sortable;
  1063. return this;
  1064. }
  1065. /**
  1066. * Gets whether the user can sort this column or not.
  1067. *
  1068. * @return {@code true} if the column can be sorted by the user;
  1069. * {@code false} if not
  1070. */
  1071. public boolean isSortable() {
  1072. return getState(false).sortable;
  1073. }
  1074. /**
  1075. * Sets the header caption for this column.
  1076. *
  1077. * @param caption
  1078. * the header caption, not null
  1079. *
  1080. * @return this column
  1081. */
  1082. public Column<T, V> setCaption(String caption) {
  1083. Objects.requireNonNull(caption, "Header caption can't be null");
  1084. if (caption.equals(getState(false).caption)) {
  1085. return this;
  1086. }
  1087. getState().caption = caption;
  1088. HeaderRow row = getGrid().getDefaultHeaderRow();
  1089. if (row != null) {
  1090. row.getCell(this).setText(caption);
  1091. }
  1092. return this;
  1093. }
  1094. /**
  1095. * Gets the header caption for this column.
  1096. *
  1097. * @return header caption
  1098. */
  1099. public String getCaption() {
  1100. return getState(false).caption;
  1101. }
  1102. /**
  1103. * Sets a comparator to use with in-memory sorting with this column.
  1104. * Sorting with a back-end is done using
  1105. * {@link Column#setSortProperty(String...)}.
  1106. *
  1107. * @param comparator
  1108. * the comparator to use when sorting data in this column
  1109. * @return this column
  1110. */
  1111. public Column<T, V> setComparator(
  1112. SerializableComparator<T> comparator) {
  1113. Objects.requireNonNull(comparator, "Comparator can't be null");
  1114. this.comparator = comparator;
  1115. return this;
  1116. }
  1117. /**
  1118. * Gets the comparator to use with in-memory sorting for this column
  1119. * when sorting in the given direction.
  1120. *
  1121. * @param sortDirection
  1122. * the direction this column is sorted by
  1123. * @return comparator for this column
  1124. */
  1125. public SerializableComparator<T> getComparator(
  1126. SortDirection sortDirection) {
  1127. Objects.requireNonNull(comparator,
  1128. "No comparator defined for sorted column.");
  1129. boolean reverse = sortDirection != SortDirection.ASCENDING;
  1130. return reverse ? (t1, t2) -> comparator.reversed().compare(t1, t2)
  1131. : comparator;
  1132. }
  1133. /**
  1134. * Sets strings describing back end properties to be used when sorting
  1135. * this column.
  1136. * <p>
  1137. * By default, the {@link #setId(String) column id} will be used as the
  1138. * sort property.
  1139. *
  1140. * @param properties
  1141. * the array of strings describing backend properties
  1142. * @return this column
  1143. */
  1144. public Column<T, V> setSortProperty(String... properties) {
  1145. Objects.requireNonNull(properties, "Sort properties can't be null");
  1146. sortOrderProvider = dir -> Arrays.stream(properties)
  1147. .map(s -> new QuerySortOrder(s, dir));
  1148. return this;
  1149. }
  1150. /**
  1151. * Sets the sort orders when sorting this column. The sort order
  1152. * provider is a function which provides {@link QuerySortOrder} objects
  1153. * to describe how to sort by this column.
  1154. * <p>
  1155. * By default, the {@link #setId(String) column id} will be used as the
  1156. * sort property.
  1157. *
  1158. * @param provider
  1159. * the function to use when generating sort orders with the
  1160. * given direction
  1161. * @return this column
  1162. */
  1163. public Column<T, V> setSortOrderProvider(SortOrderProvider provider) {
  1164. Objects.requireNonNull(provider,
  1165. "Sort order provider can't be null");
  1166. sortOrderProvider = provider;
  1167. return this;
  1168. }
  1169. /**
  1170. * Gets the sort orders to use with back-end sorting for this column
  1171. * when sorting in the given direction.
  1172. *
  1173. * @see #setSortProperty(String...)
  1174. * @see #setId(String)
  1175. * @see #setSortOrderProvider(SortOrderProvider)
  1176. *
  1177. * @param direction
  1178. * the sorting direction
  1179. * @return stream of sort orders
  1180. */
  1181. public Stream<QuerySortOrder> getSortOrder(SortDirection direction) {
  1182. return sortOrderProvider.apply(direction);
  1183. }
  1184. /**
  1185. * Sets the style generator that is used for generating class names for
  1186. * cells in this column. Returning null from the generator results in no
  1187. * custom style name being set.
  1188. *
  1189. * @param cellStyleGenerator
  1190. * the cell style generator to set, not null
  1191. * @return this column
  1192. * @throws NullPointerException
  1193. * if {@code cellStyleGenerator} is {@code null}
  1194. */
  1195. public Column<T, V> setStyleGenerator(
  1196. StyleGenerator<T> cellStyleGenerator) {
  1197. Objects.requireNonNull(cellStyleGenerator,
  1198. "Cell style generator must not be null");
  1199. this.styleGenerator = cellStyleGenerator;
  1200. getGrid().getDataCommunicator().reset();
  1201. return this;
  1202. }
  1203. /**
  1204. * Gets the style generator that is used for generating styles for
  1205. * cells.
  1206. *
  1207. * @return the cell style generator
  1208. */
  1209. public StyleGenerator<T> getStyleGenerator() {
  1210. return styleGenerator;
  1211. }
  1212. /**
  1213. * Sets the description generator that is used for generating
  1214. * descriptions for cells in this column.
  1215. *
  1216. * @param cellDescriptionGenerator
  1217. * the cell description generator to set, or
  1218. * <code>null</code> to remove a previously set generator
  1219. * @return this column
  1220. */
  1221. public Column<T, V> setDescriptionGenerator(
  1222. DescriptionGenerator<T> cellDescriptionGenerator) {
  1223. this.descriptionGenerator = cellDescriptionGenerator;
  1224. getGrid().getDataCommunicator().reset();
  1225. return this;
  1226. }
  1227. /**
  1228. * Gets the description generator that is used for generating
  1229. * descriptions for cells.
  1230. *
  1231. * @return the cell description generator, or <code>null</code> if no
  1232. * generator is set
  1233. */
  1234. public DescriptionGenerator<T> getDescriptionGenerator() {
  1235. return descriptionGenerator;
  1236. }
  1237. /**
  1238. * Sets the ratio with which the column expands.
  1239. * <p>
  1240. * By default, all columns expand equally (treated as if all of them had
  1241. * an expand ratio of 1). Once at least one column gets a defined expand
  1242. * ratio, the implicit expand ratio is removed, and only the defined
  1243. * expand ratios are taken into account.
  1244. * <p>
  1245. * If a column has a defined width ({@link #setWidth(double)}), it
  1246. * overrides this method's effects.
  1247. * <p>
  1248. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  1249. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  1250. * as wide as its contents requires</strong>. The column with a ratio of
  1251. * 1 is as wide as it needs, <strong>plus a third of any excess
  1252. * space</strong>, because we have 3 parts total, and this column
  1253. * reserves only one of those. The column with a ratio of 2, is as wide
  1254. * as it needs to be, <strong>plus two thirds</strong> of the excess
  1255. * width.
  1256. *
  1257. * @param expandRatio
  1258. * the expand ratio of this column. {@code 0} to not have it
  1259. * expand at all. A negative number to clear the expand
  1260. * value.
  1261. * @throws IllegalStateException
  1262. * if the column is no longer attached to any grid
  1263. * @see #setWidth(double)
  1264. */
  1265. public Column<T, V> setExpandRatio(int expandRatio)
  1266. throws IllegalStateException {
  1267. checkColumnIsAttached();
  1268. if (expandRatio != getExpandRatio()) {
  1269. getState().expandRatio = expandRatio;
  1270. getGrid().markAsDirty();
  1271. }
  1272. return this;
  1273. }
  1274. /**
  1275. * Returns the column's expand ratio.
  1276. *
  1277. * @return the column's expand ratio
  1278. * @see #setExpandRatio(int)
  1279. */
  1280. public int getExpandRatio() {
  1281. return getState(false).expandRatio;
  1282. }
  1283. /**
  1284. * Clears the expand ratio for this column.
  1285. * <p>
  1286. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  1287. *
  1288. * @throws IllegalStateException
  1289. * if the column is no longer attached to any grid
  1290. */
  1291. public Column<T, V> clearExpandRatio() throws IllegalStateException {
  1292. return setExpandRatio(-1);
  1293. }
  1294. /**
  1295. * Returns the width (in pixels). By default a column is 100px wide.
  1296. *
  1297. * @return the width in pixels of the column
  1298. * @throws IllegalStateException
  1299. * if the column is no longer attached to any grid
  1300. */
  1301. public double getWidth() throws IllegalStateException {
  1302. checkColumnIsAttached();
  1303. return getState(false).width;
  1304. }
  1305. /**
  1306. * Sets the width (in pixels).
  1307. * <p>
  1308. * This overrides any configuration set by any of
  1309. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  1310. * {@link #setMaximumWidth(double)}.
  1311. *
  1312. * @param pixelWidth
  1313. * the new pixel width of the column
  1314. * @return the column itself
  1315. *
  1316. * @throws IllegalStateException
  1317. * if the column is no longer attached to any grid
  1318. * @throws IllegalArgumentException
  1319. * thrown if pixel width is less than zero
  1320. */
  1321. public Column<T, V> setWidth(double pixelWidth)
  1322. throws IllegalStateException, IllegalArgumentException {
  1323. checkColumnIsAttached();
  1324. if (pixelWidth < 0) {
  1325. throw new IllegalArgumentException(
  1326. "Pixel width should be greated than 0 (in " + toString()
  1327. + ")");
  1328. }
  1329. if (pixelWidth != getWidth()) {
  1330. getState().width = pixelWidth;
  1331. getGrid().markAsDirty();
  1332. getGrid().fireColumnResizeEvent(this, false);
  1333. }
  1334. return this;
  1335. }
  1336. /**
  1337. * Returns whether this column has an undefined width.
  1338. *
  1339. * @since 7.6
  1340. * @return whether the width is undefined
  1341. * @throws IllegalStateException
  1342. * if the column is no longer attached to any grid
  1343. */
  1344. public boolean isWidthUndefined() {
  1345. checkColumnIsAttached();
  1346. return getState(false).width < 0;
  1347. }
  1348. /**
  1349. * Marks the column width as undefined. An undefined width means the
  1350. * grid is free to resize the column based on the cell contents and
  1351. * available space in the grid.
  1352. *
  1353. * @return the column itself
  1354. */
  1355. public Column<T, V> setWidthUndefined() {
  1356. checkColumnIsAttached();
  1357. if (!isWidthUndefined()) {
  1358. getState().width = -1;
  1359. getGrid().markAsDirty();
  1360. getGrid().fireColumnResizeEvent(this, false);
  1361. }
  1362. return this;
  1363. }
  1364. /**
  1365. * Sets the minimum width for this column.
  1366. * <p>
  1367. * This defines the minimum guaranteed pixel width of the column
  1368. * <em>when it is set to expand</em>.
  1369. *
  1370. * @param pixels
  1371. * the minimum width for the column
  1372. * @throws IllegalStateException
  1373. * if the column is no longer attached to any grid
  1374. * @see #setExpandRatio(int)
  1375. * @return the column itself
  1376. */
  1377. public Column<T, V> setMinimumWidth(double pixels)
  1378. throws IllegalStateException {
  1379. checkColumnIsAttached();
  1380. final double maxwidth = getMaximumWidth();
  1381. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  1382. throw new IllegalArgumentException("New minimum width ("
  1383. + pixels + ") was greater than maximum width ("
  1384. + maxwidth + ")");
  1385. }
  1386. getState().minWidth = pixels;
  1387. getGrid().markAsDirty();
  1388. return this;
  1389. }
  1390. /**
  1391. * Return the minimum width for this column.
  1392. *
  1393. * @return the minimum width for this column
  1394. * @see #setMinimumWidth(double)
  1395. */
  1396. public double getMinimumWidth() {
  1397. return getState(false).minWidth;
  1398. }
  1399. /**
  1400. * Sets whether the width of the contents in the column should be
  1401. * considered minimum width for this column.
  1402. * <p>
  1403. * If this is set to <code>true</code> (default for backwards
  1404. * compatibility), then a column will not shrink to smaller than the
  1405. * width required to show the contents available when calculating the
  1406. * widths (only the widths of the initially rendered rows are
  1407. * considered).
  1408. * <p>
  1409. * If this is set to <code>false</code> and the column has been set to
  1410. * expand using #setExpandRatio(int), then the contents of the column
  1411. * will be ignored when calculating the width, and the column will thus
  1412. * shrink down to the minimum width defined by #setMinimumWidth(double)
  1413. * if necessary.
  1414. *
  1415. * @param minimumWidthFromContent
  1416. * <code>true</code> to reserve space for all contents,
  1417. * <code>false</code> to allow the column to shrink smaller
  1418. * than the contents
  1419. * @return the column itself
  1420. * @throws IllegalStateException
  1421. * if the column is no longer attached to any grid
  1422. * @see #setMinimumWidth(double)
  1423. * @since 8.1
  1424. */
  1425. public Column<T, V> setMinimumWidthFromContent(
  1426. boolean minimumWidthFromContent) throws IllegalStateException {
  1427. checkColumnIsAttached();
  1428. if (isMinimumWidthFromContent() != minimumWidthFromContent) {
  1429. getState().minimumWidthFromContent = minimumWidthFromContent;
  1430. getGrid().markAsDirty();
  1431. }
  1432. return this;
  1433. }
  1434. /**
  1435. * Gets whether the width of the contents in the column should be
  1436. * considered minimum width for this column.
  1437. *
  1438. * @return <code>true</code> to reserve space for all contents,
  1439. * <code>false</code> to allow the column to shrink smaller than
  1440. * the contents
  1441. * @see #setMinimumWidthFromContent(boolean)
  1442. * @since 8.1
  1443. */
  1444. public boolean isMinimumWidthFromContent() {
  1445. return getState(false).minimumWidthFromContent;
  1446. }
  1447. /**
  1448. * Sets the maximum width for this column.
  1449. * <p>
  1450. * This defines the maximum allowed pixel width of the column <em>when
  1451. * it is set to expand</em>.
  1452. *
  1453. * @param pixels
  1454. * the maximum width
  1455. * @throws IllegalStateException
  1456. * if the column is no longer attached to any grid
  1457. * @see #setExpandRatio(int)
  1458. */
  1459. public Column<T, V> setMaximumWidth(double pixels) {
  1460. checkColumnIsAttached();
  1461. final double minwidth = getMinimumWidth();
  1462. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  1463. throw new IllegalArgumentException("New maximum width ("
  1464. + pixels + ") was less than minimum width (" + minwidth
  1465. + ")");
  1466. }
  1467. getState().maxWidth = pixels;
  1468. getGrid().markAsDirty();
  1469. return this;
  1470. }
  1471. /**
  1472. * Returns the maximum width for this column.
  1473. *
  1474. * @return the maximum width for this column
  1475. * @see #setMaximumWidth(double)
  1476. */
  1477. public double getMaximumWidth() {
  1478. return getState(false).maxWidth;
  1479. }
  1480. /**
  1481. * Sets whether this column can be resized by the user.
  1482. *
  1483. * @since 7.6
  1484. * @param resizable
  1485. * {@code true} if this column should be resizable,
  1486. * {@code false} otherwise
  1487. * @throws IllegalStateException
  1488. * if the column is no longer attached to any grid
  1489. */
  1490. public Column<T, V> setResizable(boolean resizable) {
  1491. checkColumnIsAttached();
  1492. if (resizable != isResizable()) {
  1493. getState().resizable = resizable;
  1494. getGrid().markAsDirty();
  1495. }
  1496. return this;
  1497. }
  1498. /**
  1499. * Gets the caption of the hiding toggle for this column.
  1500. *
  1501. * @since 7.5.0
  1502. * @see #setHidingToggleCaption(String)
  1503. * @return the caption for the hiding toggle for this column
  1504. */
  1505. public String getHidingToggleCaption() {
  1506. return getState(false).hidingToggleCaption;
  1507. }
  1508. /**
  1509. * Sets the caption of the hiding toggle for this column. Shown in the
  1510. * toggle for this column in the grid's sidebar when the column is
  1511. * {@link #isHidable() hidable}.
  1512. * <p>
  1513. * The default value is <code>null</code>, and in that case the column's
  1514. * {@link #getCaption() header caption} is used.
  1515. * <p>
  1516. * <em>NOTE:</em> setting this to empty string might cause the hiding
  1517. * toggle to not render correctly.
  1518. *
  1519. * @since 7.5.0
  1520. * @param hidingToggleCaption
  1521. * the text to show in the column hiding toggle
  1522. * @return the column itself
  1523. */
  1524. public Column<T, V> setHidingToggleCaption(String hidingToggleCaption) {
  1525. if (hidingToggleCaption != getHidingToggleCaption()) {
  1526. getState().hidingToggleCaption = hidingToggleCaption;
  1527. }
  1528. return this;
  1529. }
  1530. /**
  1531. * Hides or shows the column. By default columns are visible before
  1532. * explicitly hiding them.
  1533. *
  1534. * @since 7.5.0
  1535. * @param hidden
  1536. * <code>true</code> to hide the column, <code>false</code>
  1537. * to show
  1538. * @return this column
  1539. * @throws IllegalStateException
  1540. * if the column is no longer attached to any grid
  1541. */
  1542. public Column<T, V> setHidden(boolean hidden) {
  1543. checkColumnIsAttached();
  1544. if (hidden != isHidden()) {
  1545. getState().hidden = hidden;
  1546. getGrid().fireColumnVisibilityChangeEvent(this, hidden, false);
  1547. }
  1548. return this;
  1549. }
  1550. /**
  1551. * Returns whether this column is hidden. Default is {@code false}.
  1552. *
  1553. * @since 7.5.0
  1554. * @return <code>true</code> if the column is currently hidden,
  1555. * <code>false</code> otherwise
  1556. */
  1557. public boolean isHidden() {
  1558. return getState(false).hidden;
  1559. }
  1560. /**
  1561. * Sets whether this column can be hidden by the user. Hidable columns
  1562. * can be hidden and shown via the sidebar menu.
  1563. *
  1564. * @since 7.5.0
  1565. * @param hidable
  1566. * <code>true</code> if the column may be hidable by the user
  1567. * via UI interaction
  1568. * @return this column
  1569. */
  1570. public Column<T, V> setHidable(boolean hidable) {
  1571. if (hidable != isHidable()) {
  1572. getState().hidable = hidable;
  1573. }
  1574. return this;
  1575. }
  1576. /**
  1577. * Returns whether this column can be hidden by the user. Default is
  1578. * {@code false}.
  1579. * <p>
  1580. * <em>Note:</em> the column can be programmatically hidden using
  1581. * {@link #setHidden(boolean)} regardless of the returned value.
  1582. *
  1583. * @since 7.5.0
  1584. * @return <code>true</code> if the user can hide the column,
  1585. * <code>false</code> if not
  1586. */
  1587. public boolean isHidable() {
  1588. return getState(false).hidable;
  1589. }
  1590. /**
  1591. * Returns whether this column can be resized by the user. Default is
  1592. * {@code true}.
  1593. * <p>
  1594. * <em>Note:</em> the column can be programmatically resized using
  1595. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  1596. * of the returned value.
  1597. *
  1598. * @since 7.6
  1599. * @return {@code true} if this column is resizable, {@code false}
  1600. * otherwise
  1601. */
  1602. public boolean isResizable() {
  1603. return getState(false).resizable;
  1604. }
  1605. /**
  1606. * Sets whether this Column has a component displayed in Editor or not.
  1607. * A column can only be editable if an editor component or binding has
  1608. * been set.
  1609. *
  1610. * @param editable
  1611. * {@code true} if column is editable; {@code false} if not
  1612. * @return this column
  1613. *
  1614. * @see #setEditorComponent(HasValue, Setter)
  1615. * @see #setEditorBinding(Binding)
  1616. */
  1617. public Column<T, V> setEditable(boolean editable) {
  1618. Objects.requireNonNull(editorBinding,
  1619. "Column has no editor binding or component defined");
  1620. getState().editable = editable;
  1621. return this;
  1622. }
  1623. /**
  1624. * Gets whether this Column has a component displayed in Editor or not.
  1625. *
  1626. * @return {@code true} if the column displays an editor component;
  1627. * {@code false} if not
  1628. */
  1629. public boolean isEditable() {
  1630. return getState(false).editable;
  1631. }
  1632. /**
  1633. * Sets an editor binding for this column. The {@link Binding} is used
  1634. * when a row is in editor mode to define how to populate an editor
  1635. * component based on the edited row and how to update an item based on
  1636. * the value in the editor component.
  1637. * <p>
  1638. * To create a binding to use with a column, define a binding for the
  1639. * editor binder (<code>grid.getEditor().getBinder()</code>) using e.g.
  1640. * {@link Binder#forField(HasValue)}. You can also use
  1641. * {@link #setEditorComponent(HasValue, Setter)} if no validator or
  1642. * converter is needed for the binding.
  1643. * <p>
  1644. * The {@link HasValue} that the binding is defined to use must be a
  1645. * {@link Component}.
  1646. *
  1647. * @param binding
  1648. * the binding to use for this column
  1649. * @return this column
  1650. *
  1651. * @see #setEditorComponent(HasValue, Setter)
  1652. * @see Binding
  1653. * @see Grid#getEditor()
  1654. * @see Editor#getBinder()
  1655. */
  1656. public Column<T, V> setEditorBinding(Binding<T, ?> binding) {
  1657. Objects.requireNonNull(binding, "null is not a valid editor field");
  1658. if (!(binding.getField() instanceof Component)) {
  1659. throw new IllegalArgumentException(
  1660. "Binding target must be a component.");
  1661. }
  1662. this.editorBinding = binding;
  1663. return setEditable(true);
  1664. }
  1665. /**
  1666. * Gets the binder binding that is currently used for this column.
  1667. *
  1668. * @return the used binder binding, or <code>null</code> if no binding
  1669. * is configured
  1670. *
  1671. * @see #setEditorBinding(Binding)
  1672. */
  1673. public Binding<T, ?> getEditorBinding() {
  1674. return editorBinding;
  1675. }
  1676. /**
  1677. * Sets a component and setter to use for editing values of this column
  1678. * in the editor row. This is a shorthand for use in simple cases where
  1679. * no validator or converter is needed. Use
  1680. * {@link #setEditorBinding(Binding)} to support more complex cases.
  1681. * <p>
  1682. * <strong>Note:</strong> The same component cannot be used for multiple
  1683. * columns.
  1684. *
  1685. * @param editorComponent
  1686. * the editor component
  1687. * @param setter
  1688. * a setter that stores the component value in the row item
  1689. * @return this column
  1690. *
  1691. * @see #setEditorBinding(Binding)
  1692. * @see Grid#getEditor()
  1693. * @see Binder#bind(HasValue, ValueProvider, Setter)
  1694. */
  1695. public <C extends HasValue<V> & Component> Column<T, V> setEditorComponent(
  1696. C editorComponent, Setter<T, V> setter) {
  1697. Objects.requireNonNull(editorComponent,
  1698. "Editor component cannot be null");
  1699. Objects.requireNonNull(setter, "Setter cannot be null");
  1700. Binding<T, V> binding = getGrid().getEditor().getBinder()
  1701. .bind(editorComponent, valueProvider::apply, setter);
  1702. return setEditorBinding(binding);
  1703. }
  1704. /**
  1705. * Sets a component to use for editing values of this columns in the
  1706. * editor row. This method can only be used if the column has an
  1707. * {@link #setId(String) id} and the {@link Grid} has been created using
  1708. * {@link Grid#Grid(Class)} or some other way that allows finding
  1709. * properties based on property names.
  1710. * <p>
  1711. * This is a shorthand for use in simple cases where no validator or
  1712. * converter is needed. Use {@link #setEditorBinding(Binding)} to
  1713. * support more complex cases.
  1714. * <p>
  1715. * <strong>Note:</strong> The same component cannot be used for multiple
  1716. * columns.
  1717. *
  1718. * @param editorComponent
  1719. * the editor component
  1720. * @return this column
  1721. *
  1722. * @see #setEditorBinding(Binding)
  1723. * @see Grid#getEditor()
  1724. * @see Binder#bind(HasValue, String)
  1725. * @see Grid#Grid(Class)
  1726. */
  1727. public <F, C extends HasValue<F> & Component> Column<T, V> setEditorComponent(
  1728. C editorComponent) {
  1729. Objects.requireNonNull(editorComponent,
  1730. "Editor component cannot be null");
  1731. String propertyName = getId();
  1732. if (propertyName == null) {
  1733. throw new IllegalStateException(
  1734. "setEditorComponent without a setter can only be used if the column has an id. "
  1735. + "Use another setEditorComponent(Component, Setter) or setEditorBinding(Binding) instead.");
  1736. }
  1737. Binding<T, F> binding = getGrid().getEditor().getBinder()
  1738. .bind(editorComponent, propertyName);
  1739. return setEditorBinding(binding);
  1740. }
  1741. /**
  1742. * Sets the Renderer for this Column. Setting the renderer will cause
  1743. * all currently available row data to be recreated and sent to the
  1744. * client.
  1745. *
  1746. * @param renderer
  1747. * the new renderer
  1748. * @return this column
  1749. *
  1750. * @since 8.0.3
  1751. */
  1752. public Column<T, V> setRenderer(Renderer<? super V> renderer) {
  1753. return setRenderer(ValueProvider.identity(), renderer);
  1754. }
  1755. /**
  1756. * Sets the Renderer for this Column. Setting the renderer will cause
  1757. * all currently available row data to be recreated and sent to the
  1758. * client.
  1759. * <p>
  1760. * The presentation provider is a method that takes the value of this
  1761. * column on a single row, and maps that to a value that the renderer
  1762. * accepts. This feature can be used for storing a complex value in a
  1763. * column for editing, but providing a simplified presentation for the
  1764. * user when not editing.
  1765. *
  1766. * @param presentationProvider
  1767. * the function to get presentations from the value of this
  1768. * column, not {@code null}
  1769. * @param renderer
  1770. * the new renderer, not {@code null}
  1771. *
  1772. * @param <P>
  1773. * the presentation type
  1774. *
  1775. * @return this column
  1776. *
  1777. * @since 8.1
  1778. */
  1779. public <P> Column<T, V> setRenderer(
  1780. ValueProvider<V, P> presentationProvider,
  1781. Renderer<? super P> renderer) {
  1782. Objects.requireNonNull(renderer, "Renderer can not be null");
  1783. Objects.requireNonNull(presentationProvider,
  1784. "Presentation provider can not be null");
  1785. // Remove old renderer
  1786. Connector oldRenderer = getState().renderer;
  1787. if (oldRenderer != null && oldRenderer instanceof Extension) {
  1788. removeExtension((Extension) oldRenderer);
  1789. }
  1790. // Set new renderer
  1791. getState().renderer = renderer;
  1792. addExtension(renderer);
  1793. this.presentationProvider = presentationProvider;
  1794. // Trigger redraw
  1795. getGrid().getDataCommunicator().reset();
  1796. return this;
  1797. }
  1798. /**
  1799. * Gets the Renderer for this Column.
  1800. *
  1801. * @return the renderer
  1802. * @since 8.1
  1803. */
  1804. public Renderer<?> getRenderer() {
  1805. return (Renderer<?>) getState().renderer;
  1806. }
  1807. /**
  1808. * Gets the grid that this column belongs to.
  1809. *
  1810. * @return the grid that this column belongs to, or <code>null</code> if
  1811. * this column has not yet been associated with any grid
  1812. */
  1813. @SuppressWarnings("unchecked")
  1814. protected Grid<T> getGrid() {
  1815. return (Grid<T>) getParent();
  1816. }
  1817. /**
  1818. * Checks if column is attached and throws an
  1819. * {@link IllegalStateException} if it is not.
  1820. *
  1821. * @throws IllegalStateException
  1822. * if the column is no longer attached to any grid
  1823. */
  1824. protected void checkColumnIsAttached() throws IllegalStateException {
  1825. if (getGrid() == null) {
  1826. throw new IllegalStateException(
  1827. "Column is no longer attached to a grid.");
  1828. }
  1829. }
  1830. /**
  1831. * Writes the design attributes for this column into given element.
  1832. *
  1833. * @since 7.5.0
  1834. *
  1835. * @param element
  1836. * Element to write attributes into
  1837. *
  1838. * @param designContext
  1839. * the design context
  1840. */
  1841. protected void writeDesign(Element element,
  1842. DesignContext designContext) {
  1843. Attributes attributes = element.attributes();
  1844. ColumnState defaultState = new ColumnState();
  1845. if (getId() == null) {
  1846. setId("column" + getGrid().getColumns().indexOf(this));
  1847. }
  1848. DesignAttributeHandler.writeAttribute("column-id", attributes,
  1849. getId(), null, String.class, designContext);
  1850. // Sortable is a special attribute that depends on the data
  1851. // provider.
  1852. DesignAttributeHandler.writeAttribute("sortable", attributes,
  1853. isSortable(), null, boolean.class, designContext);
  1854. DesignAttributeHandler.writeAttribute("editable", attributes,
  1855. isEditable(), defaultState.editable, boolean.class,
  1856. designContext);
  1857. DesignAttributeHandler.writeAttribute("resizable", attributes,
  1858. isResizable(), defaultState.resizable, boolean.class,
  1859. designContext);
  1860. DesignAttributeHandler.writeAttribute("hidable", attributes,
  1861. isHidable(), defaultState.hidable, boolean.class,
  1862. designContext);
  1863. DesignAttributeHandler.writeAttribute("hidden", attributes,
  1864. isHidden(), defaultState.hidden, boolean.class,
  1865. designContext);
  1866. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  1867. attributes, getHidingToggleCaption(),
  1868. defaultState.hidingToggleCaption, String.class,
  1869. designContext);
  1870. DesignAttributeHandler.writeAttribute("width", attributes,
  1871. getWidth(), defaultState.width, Double.class,
  1872. designContext);
  1873. DesignAttributeHandler.writeAttribute("min-width", attributes,
  1874. getMinimumWidth(), defaultState.minWidth, Double.class,
  1875. designContext);
  1876. DesignAttributeHandler.writeAttribute("max-width", attributes,
  1877. getMaximumWidth(), defaultState.maxWidth, Double.class,
  1878. designContext);
  1879. DesignAttributeHandler.writeAttribute("expand", attributes,
  1880. getExpandRatio(), defaultState.expandRatio, Integer.class,
  1881. designContext);
  1882. }
  1883. /**
  1884. * Reads the design attributes for this column from given element.
  1885. *
  1886. * @since 7.5.0
  1887. * @param design
  1888. * Element to read attributes from
  1889. * @param designContext
  1890. * the design context
  1891. */
  1892. @SuppressWarnings("unchecked")
  1893. protected void readDesign(Element design, DesignContext designContext) {
  1894. Attributes attributes = design.attributes();
  1895. if (design.hasAttr("sortable")) {
  1896. setSortable(DesignAttributeHandler.readAttribute("sortable",
  1897. attributes, boolean.class));
  1898. } else {
  1899. setSortable(false);
  1900. }
  1901. if (design.hasAttr("editable")) {
  1902. /*
  1903. * This is a fake editor just to have something (otherwise
  1904. * "setEditable" throws an exception.
  1905. *
  1906. * Let's use TextField here because we support only Strings as
  1907. * inline data type. It will work incorrectly for other types
  1908. * but we don't support them anyway.
  1909. */
  1910. setEditorComponent((HasValue<V> & Component) new TextField(),
  1911. (item, value) -> {
  1912. // Ignore user value since we don't know the setter
  1913. });
  1914. setEditable(DesignAttributeHandler.readAttribute("editable",
  1915. attributes, boolean.class));
  1916. }
  1917. if (design.hasAttr("resizable")) {
  1918. setResizable(DesignAttributeHandler.readAttribute("resizable",
  1919. attributes, boolean.class));
  1920. }
  1921. if (design.hasAttr("hidable")) {
  1922. setHidable(DesignAttributeHandler.readAttribute("hidable",
  1923. attributes, boolean.class));
  1924. }
  1925. if (design.hasAttr("hidden")) {
  1926. setHidden(DesignAttributeHandler.readAttribute("hidden",
  1927. attributes, boolean.class));
  1928. }
  1929. if (design.hasAttr("hiding-toggle-caption")) {
  1930. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  1931. "hiding-toggle-caption", attributes, String.class));
  1932. }
  1933. // Read size info where necessary.
  1934. if (design.hasAttr("width")) {
  1935. setWidth(DesignAttributeHandler.readAttribute("width",
  1936. attributes, Double.class));
  1937. }
  1938. if (design.hasAttr("min-width")) {
  1939. setMinimumWidth(DesignAttributeHandler
  1940. .readAttribute("min-width", attributes, Double.class));
  1941. }
  1942. if (design.hasAttr("max-width")) {
  1943. setMaximumWidth(DesignAttributeHandler
  1944. .readAttribute("max-width", attributes, Double.class));
  1945. }
  1946. if (design.hasAttr("expand")) {
  1947. if (design.attr("expand").isEmpty()) {
  1948. setExpandRatio(1);
  1949. } else {
  1950. setExpandRatio(DesignAttributeHandler.readAttribute(
  1951. "expand", attributes, Integer.class));
  1952. }
  1953. }
  1954. }
  1955. /**
  1956. * Gets the DataGenerator for this Column.
  1957. *
  1958. * @return data generator
  1959. */
  1960. private DataGenerator<T> getDataGenerator() {
  1961. return dataGenerator;
  1962. }
  1963. }
  1964. private class HeaderImpl extends Header {
  1965. @Override
  1966. protected Grid<T> getGrid() {
  1967. return Grid.this;
  1968. }
  1969. @Override
  1970. protected SectionState getState(boolean markAsDirty) {
  1971. return Grid.this.getState(markAsDirty).header;
  1972. }
  1973. @Override
  1974. protected Column<?, ?> getColumnByInternalId(String internalId) {
  1975. return getGrid().getColumnByInternalId(internalId);
  1976. }
  1977. @Override
  1978. @SuppressWarnings("unchecked")
  1979. protected String getInternalIdForColumn(Column<?, ?> column) {
  1980. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  1981. }
  1982. };
  1983. private class FooterImpl extends Footer {
  1984. @Override
  1985. protected Grid<T> getGrid() {
  1986. return Grid.this;
  1987. }
  1988. @Override
  1989. protected SectionState getState(boolean markAsDirty) {
  1990. return Grid.this.getState(markAsDirty).footer;
  1991. }
  1992. @Override
  1993. protected Column<?, ?> getColumnByInternalId(String internalId) {
  1994. return getGrid().getColumnByInternalId(internalId);
  1995. }
  1996. @Override
  1997. @SuppressWarnings("unchecked")
  1998. protected String getInternalIdForColumn(Column<?, ?> column) {
  1999. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  2000. }
  2001. };
  2002. private final Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
  2003. private final Map<String, Column<T, ?>> columnKeys = new HashMap<>();
  2004. private final Map<String, Column<T, ?>> columnIds = new HashMap<>();
  2005. private final List<GridSortOrder<T>> sortOrder = new ArrayList<>();
  2006. private final DetailsManager<T> detailsManager;
  2007. private final Set<Component> extensionComponents = new HashSet<>();
  2008. private StyleGenerator<T> styleGenerator = item -> null;
  2009. private DescriptionGenerator<T> descriptionGenerator;
  2010. private final Header header = new HeaderImpl();
  2011. private final Footer footer = new FooterImpl();
  2012. private int counter = 0;
  2013. private GridSelectionModel<T> selectionModel;
  2014. private Editor<T> editor;
  2015. private PropertySet<T> propertySet;
  2016. private Class<T> beanType = null;
  2017. /**
  2018. * Creates a new grid without support for creating columns based on property
  2019. * names. Use an alternative constructor, such as {@link Grid#Grid(Class)},
  2020. * to create a grid that automatically sets up columns based on the type of
  2021. * presented data.
  2022. *
  2023. * @see #Grid(Class)
  2024. * @see #withPropertySet(PropertySet)
  2025. */
  2026. public Grid() {
  2027. this(new DataCommunicator<>());
  2028. }
  2029. /**
  2030. * Creates a new grid that uses reflection based on the provided bean type
  2031. * to automatically set up an initial set of columns. All columns will be
  2032. * configured using the same {@link Object#toString()} renderer that is used
  2033. * by {@link #addColumn(ValueProvider)}.
  2034. *
  2035. * @param beanType
  2036. * the bean type to use, not <code>null</code>
  2037. * @see #Grid()
  2038. * @see #withPropertySet(PropertySet)
  2039. */
  2040. public Grid(Class<T> beanType) {
  2041. this(beanType, new DataCommunicator<>());
  2042. }
  2043. /**
  2044. * Creates a new grid that uses custom data communicator and provided bean
  2045. * type
  2046. *
  2047. * It uses reflection of the provided bean type to automatically set up an
  2048. * initial set of columns. All columns will be configured using the same
  2049. * {@link Object#toString()} renderer that is used by
  2050. * {@link #addColumn(ValueProvider)}.
  2051. *
  2052. * @param beanType
  2053. * the bean type to use, not <code>null</code>
  2054. * @param dataCommunicator
  2055. * the data communicator to use, not<code>null</code>
  2056. * @since 8.0.7
  2057. */
  2058. protected Grid(Class<T> beanType, DataCommunicator<T> dataCommunicator) {
  2059. this(BeanPropertySet.get(beanType), dataCommunicator);
  2060. this.beanType = beanType;
  2061. }
  2062. /**
  2063. * Creates a new grid with the given data communicator and without support
  2064. * for creating columns based on property names.
  2065. *
  2066. * @param dataCommunicator
  2067. * the custom data communicator to set
  2068. * @see #Grid()
  2069. * @see #Grid(PropertySet, DataCommunicator)
  2070. * @since 8.0.7
  2071. */
  2072. protected Grid(DataCommunicator<T> dataCommunicator) {
  2073. this(new PropertySet<T>() {
  2074. @Override
  2075. public Stream<PropertyDefinition<T, ?>> getProperties() {
  2076. // No columns configured by default
  2077. return Stream.empty();
  2078. }
  2079. @Override
  2080. public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
  2081. throw new IllegalStateException(
  2082. "A Grid created without a bean type class literal or a custom property set"
  2083. + " doesn't support finding properties by name.");
  2084. }
  2085. }, dataCommunicator);
  2086. }
  2087. /**
  2088. * Creates a grid using a custom {@link PropertySet} implementation for
  2089. * configuring the initial columns and resolving property names for
  2090. * {@link #addColumn(String)} and
  2091. * {@link Column#setEditorComponent(HasValue)}.
  2092. *
  2093. * @see #withPropertySet(PropertySet)
  2094. *
  2095. * @param propertySet
  2096. * the property set implementation to use, not <code>null</code>.
  2097. */
  2098. protected Grid(PropertySet<T> propertySet) {
  2099. this(propertySet, new DataCommunicator<>());
  2100. }
  2101. /**
  2102. * Creates a grid using a custom {@link PropertySet} implementation and
  2103. * custom data communicator.
  2104. * <p>
  2105. * Property set is used for configuring the initial columns and resolving
  2106. * property names for {@link #addColumn(String)} and
  2107. * {@link Column#setEditorComponent(HasValue)}.
  2108. *
  2109. * @see #withPropertySet(PropertySet)
  2110. *
  2111. * @param propertySet
  2112. * the property set implementation to use, not <code>null</code>.
  2113. * @param dataCommunicator
  2114. * the data communicator to use, not<code>null</code>
  2115. * @since 8.0.7
  2116. */
  2117. protected Grid(PropertySet<T> propertySet,
  2118. DataCommunicator<T> dataCommunicator) {
  2119. super(dataCommunicator);
  2120. registerRpc(new GridServerRpcImpl());
  2121. setDefaultHeaderRow(appendHeaderRow());
  2122. setSelectionModel(new SingleSelectionModelImpl<>());
  2123. detailsManager = new DetailsManager<>();
  2124. addExtension(detailsManager);
  2125. addDataGenerator(detailsManager);
  2126. addDataGenerator((item, json) -> {
  2127. String styleName = styleGenerator.apply(item);
  2128. if (styleName != null && !styleName.isEmpty()) {
  2129. json.put(GridState.JSONKEY_ROWSTYLE, styleName);
  2130. }
  2131. if (descriptionGenerator != null) {
  2132. String description = descriptionGenerator.apply(item);
  2133. if (description != null && !description.isEmpty()) {
  2134. json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
  2135. }
  2136. }
  2137. });
  2138. setPropertySet(propertySet);
  2139. // Automatically add columns for all available properties
  2140. propertySet.getProperties().map(PropertyDefinition::getName)
  2141. .forEach(this::addColumn);
  2142. }
  2143. /**
  2144. * Sets the property set to use for this grid. Does not create or update
  2145. * columns in any way but will delete and re-create the editor.
  2146. * <p>
  2147. * This is only meant to be called from constructors and readDesign, at a
  2148. * stage where it does not matter if you throw away the editor.
  2149. *
  2150. * @param propertySet
  2151. * the property set to use
  2152. *
  2153. * @since 8.0.3
  2154. */
  2155. protected void setPropertySet(PropertySet<T> propertySet) {
  2156. Objects.requireNonNull(propertySet, "propertySet cannot be null");
  2157. this.propertySet = propertySet;
  2158. if (editor instanceof Extension) {
  2159. removeExtension((Extension) editor);
  2160. }
  2161. editor = createEditor();
  2162. if (editor instanceof Extension) {
  2163. addExtension((Extension) editor);
  2164. }
  2165. }
  2166. /**
  2167. * Creates a grid using a custom {@link PropertySet} implementation for
  2168. * creating a default set of columns and for resolving property names with
  2169. * {@link #addColumn(String)} and
  2170. * {@link Column#setEditorComponent(HasValue)}.
  2171. * <p>
  2172. * This functionality is provided as static method instead of as a public
  2173. * constructor in order to make it possible to use a custom property set
  2174. * without creating a subclass while still leaving the public constructors
  2175. * focused on the common use cases.
  2176. *
  2177. * @see Grid#Grid()
  2178. * @see Grid#Grid(Class)
  2179. *
  2180. * @param propertySet
  2181. * the property set implementation to use, not <code>null</code>.
  2182. * @return a new grid using the provided property set, not <code>null</code>
  2183. */
  2184. public static <BEAN> Grid<BEAN> withPropertySet(
  2185. PropertySet<BEAN> propertySet) {
  2186. return new Grid<>(propertySet);
  2187. }
  2188. /**
  2189. * Creates a new {@code Grid} using the given caption.
  2190. *
  2191. * @param caption
  2192. * the caption of the grid
  2193. */
  2194. public Grid(String caption) {
  2195. this();
  2196. setCaption(caption);
  2197. }
  2198. /**
  2199. * Creates a new {@code Grid} using the given caption and
  2200. * {@code DataProvider}.
  2201. *
  2202. * @param caption
  2203. * the caption of the grid
  2204. * @param dataProvider
  2205. * the data provider, not {@code null}
  2206. */
  2207. public Grid(String caption, DataProvider<T, ?> dataProvider) {
  2208. this(caption);
  2209. setDataProvider(dataProvider);
  2210. }
  2211. /**
  2212. * Creates a new {@code Grid} using the given {@code DataProvider}.
  2213. *
  2214. * @param dataProvider
  2215. * the data provider, not {@code null}
  2216. */
  2217. public Grid(DataProvider<T, ?> dataProvider) {
  2218. this();
  2219. setDataProvider(dataProvider);
  2220. }
  2221. /**
  2222. * Creates a new {@code Grid} using the given caption and collection of
  2223. * items.
  2224. *
  2225. * @param caption
  2226. * the caption of the grid
  2227. * @param items
  2228. * the data items to use, not {@çode null}
  2229. */
  2230. public Grid(String caption, Collection<T> items) {
  2231. this(caption, DataProvider.ofCollection(items));
  2232. }
  2233. /**
  2234. * Gets the bean type used by this grid.
  2235. * <p>
  2236. * The bean type is used to automatically set up a column added using a
  2237. * property name.
  2238. *
  2239. * @return the used bean type or <code>null</code> if no bean type has been
  2240. * defined
  2241. *
  2242. * @since 8.0.3
  2243. */
  2244. public Class<T> getBeanType() {
  2245. return beanType;
  2246. }
  2247. public <V> void fireColumnVisibilityChangeEvent(Column<T, V> column,
  2248. boolean hidden, boolean userOriginated) {
  2249. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  2250. userOriginated));
  2251. }
  2252. /**
  2253. * Adds a new column with the given property name. The column will use a
  2254. * {@link TextRenderer}. The value is converted to a String using
  2255. * {@link Object#toString()}. The property name will be used as the
  2256. * {@link Column#getId() column id} and the {@link Column#getCaption()
  2257. * column caption} will be set based on the property definition.
  2258. * <p>
  2259. * This method can only be used for a <code>Grid</code> created using
  2260. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2261. *
  2262. * @param propertyName
  2263. * the property name of the new column, not <code>null</code>
  2264. * @return the newly added column, not <code>null</code>
  2265. */
  2266. public Column<T, ?> addColumn(String propertyName) {
  2267. return addColumn(propertyName, new TextRenderer());
  2268. }
  2269. /**
  2270. * Adds a new column with the given property name and renderer. The property
  2271. * name will be used as the {@link Column#getId() column id} and the
  2272. * {@link Column#getCaption() column caption} will be set based on the
  2273. * property definition.
  2274. * <p>
  2275. * This method can only be used for a <code>Grid</code> created using
  2276. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  2277. *
  2278. * @param propertyName
  2279. * the property name of the new column, not <code>null</code>
  2280. * @param renderer
  2281. * the renderer to use, not <code>null</code>
  2282. * @return the newly added column, not <code>null</code>
  2283. */
  2284. public Column<T, ?> addColumn(String propertyName,
  2285. AbstractRenderer<? super T, ?> renderer) {
  2286. Objects.requireNonNull(propertyName, "Property name cannot be null");
  2287. Objects.requireNonNull(renderer, "Renderer cannot be null");
  2288. if (getColumn(propertyName) != null) {
  2289. throw new IllegalStateException(
  2290. "There is already a column for " + propertyName);
  2291. }
  2292. PropertyDefinition<T, ?> definition = propertySet
  2293. .getProperty(propertyName)
  2294. .orElseThrow(() -> new IllegalArgumentException(
  2295. "Could not resolve property name " + propertyName
  2296. + " from " + propertySet));
  2297. if (!renderer.getPresentationType()
  2298. .isAssignableFrom(definition.getType())) {
  2299. throw new IllegalArgumentException(
  2300. renderer + " cannot be used with a property of type "
  2301. + definition.getType().getName());
  2302. }
  2303. @SuppressWarnings({ "unchecked", "rawtypes" })
  2304. Column<T, ?> column = addColumn(definition.getGetter(),
  2305. (AbstractRenderer) renderer).setId(definition.getName())
  2306. .setCaption(definition.getCaption());
  2307. return column;
  2308. }
  2309. /**
  2310. * Adds a new text column to this {@link Grid} with a value provider. The
  2311. * column will use a {@link TextRenderer}. The value is converted to a
  2312. * String using {@link Object#toString()}. In-memory sorting will use the
  2313. * natural ordering of elements if they are mutually comparable and
  2314. * otherwise fall back to comparing the string representations of the
  2315. * values.
  2316. *
  2317. * @param valueProvider
  2318. * the value provider
  2319. *
  2320. * @return the new column
  2321. */
  2322. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider) {
  2323. return addColumn(valueProvider, new TextRenderer());
  2324. }
  2325. /**
  2326. * Adds a new column to this {@link Grid} with typed renderer and value
  2327. * provider.
  2328. *
  2329. * @param valueProvider
  2330. * the value provider
  2331. * @param renderer
  2332. * the column value renderer
  2333. * @param <V>
  2334. * the column value type
  2335. *
  2336. * @return the new column
  2337. *
  2338. * @see AbstractRenderer
  2339. */
  2340. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2341. AbstractRenderer<? super T, ? super V> renderer) {
  2342. return addColumn(valueProvider, ValueProvider.identity(), renderer);
  2343. }
  2344. /**
  2345. * Adds a new column to this {@link Grid} with value provider and
  2346. * presentation provider.
  2347. * <p>
  2348. * <strong>Note:</strong> The presentation type for this method is set to be
  2349. * String. To use any custom renderer with the presentation provider, use
  2350. * {@link #addColumn(ValueProvider, ValueProvider, AbstractRenderer)}.
  2351. *
  2352. * @param valueProvider
  2353. * the value provider
  2354. * @param presentationProvider
  2355. * the value presentation provider
  2356. * @param <V>
  2357. * the column value type
  2358. *
  2359. * @see #addColumn(ValueProvider, ValueProvider, AbstractRenderer)
  2360. *
  2361. * @return the new column
  2362. * @since 8.1
  2363. */
  2364. public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2365. ValueProvider<V, String> presentationProvider) {
  2366. return addColumn(valueProvider, presentationProvider,
  2367. new TextRenderer());
  2368. }
  2369. /**
  2370. * Adds a new column to this {@link Grid} with value provider, presentation
  2371. * provider and typed renderer.
  2372. *
  2373. * <p>
  2374. * The presentation provider is a method that takes the value from the value
  2375. * provider, and maps that to a value that the renderer accepts. This
  2376. * feature can be used for storing a complex value in a column for editing,
  2377. * but providing a simplified presentation for the user when not editing.
  2378. *
  2379. * @param valueProvider
  2380. * the value provider
  2381. * @param presentationProvider
  2382. * the value presentation provider
  2383. * @param renderer
  2384. * the column value renderer
  2385. * @param <V>
  2386. * the column value type
  2387. * @param <P>
  2388. * the column presentation type
  2389. *
  2390. * @return the new column
  2391. *
  2392. * @see AbstractRenderer
  2393. * @since 8.1
  2394. */
  2395. public <V, P> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
  2396. ValueProvider<V, P> presentationProvider,
  2397. AbstractRenderer<? super T, ? super P> renderer) {
  2398. String generatedIdentifier = getGeneratedIdentifier();
  2399. Column<T, V> column = createColumn(valueProvider, presentationProvider,
  2400. renderer);
  2401. addColumn(generatedIdentifier, column);
  2402. return column;
  2403. }
  2404. /**
  2405. * Adds a column that shows components.
  2406. * <p>
  2407. * This is a shorthand for {@link #addColum()} with a
  2408. * {@link ComponentRenderer}.
  2409. *
  2410. * @param componentProvider
  2411. * a value provider that will return a component for the given
  2412. * item
  2413. * @return the new column
  2414. * @param <V>
  2415. * the column value type, extends component
  2416. * @since 8.1
  2417. */
  2418. public <V extends Component> Column<T, V> addComponentColumn(
  2419. ValueProvider<T, V> componentProvider) {
  2420. return addColumn(componentProvider, new ComponentRenderer());
  2421. }
  2422. /**
  2423. * Creates a column instance from a value provider, presentation provider
  2424. * and a renderer.
  2425. *
  2426. * @param valueProvider
  2427. * the value provider
  2428. * @param presentationProvider
  2429. * the presentation provider
  2430. * @param renderer
  2431. * the renderer
  2432. * @return a new column instance
  2433. * @param <V>
  2434. * the column value type
  2435. * @param <P>
  2436. * the column presentation type
  2437. *
  2438. * @since 8.1
  2439. */
  2440. protected <V, P> Column<T, V> createColumn(
  2441. ValueProvider<T, V> valueProvider,
  2442. ValueProvider<V, P> presentationProvider,
  2443. AbstractRenderer<? super T, ? super P> renderer) {
  2444. return new Column<>(valueProvider, presentationProvider, renderer);
  2445. }
  2446. private void addColumn(String identifier, Column<T, ?> column) {
  2447. if (getColumns().contains(column)) {
  2448. return;
  2449. }
  2450. column.extend(this);
  2451. columnSet.add(column);
  2452. columnKeys.put(identifier, column);
  2453. column.setInternalId(identifier);
  2454. addDataGenerator(column.getDataGenerator());
  2455. getState().columnOrder.add(identifier);
  2456. getHeader().addColumn(identifier);
  2457. getFooter().addColumn(identifier);
  2458. if (getDefaultHeaderRow() != null) {
  2459. getDefaultHeaderRow().getCell(column).setText(column.getCaption());
  2460. }
  2461. }
  2462. /**
  2463. * Removes the given column from this {@link Grid}.
  2464. *
  2465. * @param column
  2466. * the column to remove
  2467. */
  2468. public void removeColumn(Column<T, ?> column) {
  2469. if (columnSet.remove(column)) {
  2470. String columnId = column.getInternalId();
  2471. int displayIndex = getState(false).columnOrder.indexOf(columnId);
  2472. assert displayIndex != -1 : "Tried to remove a column which is not included in columnOrder. This should not be possible as all columns should be in columnOrder.";
  2473. columnKeys.remove(columnId);
  2474. columnIds.remove(column.getId());
  2475. column.remove();
  2476. removeDataGenerator(column.getDataGenerator());
  2477. getHeader().removeColumn(columnId);
  2478. getFooter().removeColumn(columnId);
  2479. getState(true).columnOrder.remove(columnId);
  2480. if (displayIndex < getFrozenColumnCount()) {
  2481. setFrozenColumnCount(getFrozenColumnCount() - 1);
  2482. }
  2483. }
  2484. }
  2485. /**
  2486. * Removes the column with the given column id.
  2487. *
  2488. * @see #removeColumn(Column)
  2489. * @see Column#setId(String)
  2490. *
  2491. * @param columnId
  2492. * the id of the column to remove, not <code>null</code>
  2493. */
  2494. public void removeColumn(String columnId) {
  2495. removeColumn(getColumnOrThrow(columnId));
  2496. }
  2497. /**
  2498. * Removes all columns from this Grid.
  2499. *
  2500. * @since 8.0.2
  2501. */
  2502. public void removeAllColumns() {
  2503. for (Column<T, ?> column : getColumns()) {
  2504. removeColumn(column);
  2505. }
  2506. }
  2507. /**
  2508. * Requests that the column widths should be recalculated.
  2509. * <p>
  2510. * In most cases Grid will know when column widths need to be recalculated
  2511. * but this method can be used to force recalculation in situations when
  2512. * grid does not recalculate automatically.
  2513. *
  2514. * @since 8.1.1
  2515. */
  2516. public void recalculateColumnWidths() {
  2517. getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
  2518. }
  2519. /**
  2520. * Sets the details component generator.
  2521. *
  2522. * @param generator
  2523. * the generator for details components
  2524. */
  2525. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  2526. this.detailsManager.setDetailsGenerator(generator);
  2527. }
  2528. /**
  2529. * Sets the visibility of details component for given item.
  2530. *
  2531. * @param item
  2532. * the item to show details for
  2533. * @param visible
  2534. * {@code true} if details component should be visible;
  2535. * {@code false} if it should be hidden
  2536. */
  2537. public void setDetailsVisible(T item, boolean visible) {
  2538. detailsManager.setDetailsVisible(item, visible);
  2539. }
  2540. /**
  2541. * Returns the visibility of details component for given item.
  2542. *
  2543. * @param item
  2544. * the item to show details for
  2545. *
  2546. * @return {@code true} if details component should be visible;
  2547. * {@code false} if it should be hidden
  2548. */
  2549. public boolean isDetailsVisible(T item) {
  2550. return detailsManager.isDetailsVisible(item);
  2551. }
  2552. /**
  2553. * Gets an unmodifiable collection of all columns currently in this
  2554. * {@link Grid}.
  2555. *
  2556. * @return unmodifiable collection of columns
  2557. */
  2558. public List<Column<T, ?>> getColumns() {
  2559. return Collections.unmodifiableList(getState(false).columnOrder.stream()
  2560. .map(columnKeys::get).collect(Collectors.toList()));
  2561. }
  2562. /**
  2563. * Gets a {@link Column} of this grid by its identifying string.
  2564. *
  2565. * @see Column#setId(String)
  2566. *
  2567. * @param columnId
  2568. * the identifier of the column to get
  2569. * @return the column corresponding to the given column identifier, or
  2570. * <code>null</code> if there is no such column
  2571. */
  2572. public Column<T, ?> getColumn(String columnId) {
  2573. return columnIds.get(columnId);
  2574. }
  2575. private Column<T, ?> getColumnOrThrow(String columnId) {
  2576. Objects.requireNonNull(columnId, "Column id cannot be null");
  2577. Column<T, ?> column = getColumn(columnId);
  2578. if (column == null) {
  2579. throw new IllegalStateException(
  2580. "There is no column with the id " + columnId);
  2581. }
  2582. return column;
  2583. }
  2584. /**
  2585. * {@inheritDoc}
  2586. * <p>
  2587. * Note that the order of the returned components it not specified.
  2588. */
  2589. @Override
  2590. public Iterator<Component> iterator() {
  2591. Set<Component> componentSet = new LinkedHashSet<>(extensionComponents);
  2592. Header header = getHeader();
  2593. for (int i = 0; i < header.getRowCount(); ++i) {
  2594. HeaderRow row = header.getRow(i);
  2595. componentSet.addAll(row.getComponents());
  2596. }
  2597. Footer footer = getFooter();
  2598. for (int i = 0; i < footer.getRowCount(); ++i) {
  2599. FooterRow row = footer.getRow(i);
  2600. componentSet.addAll(row.getComponents());
  2601. }
  2602. return Collections.unmodifiableSet(componentSet).iterator();
  2603. }
  2604. /**
  2605. * Sets the number of frozen columns in this grid. Setting the count to 0
  2606. * means that no data columns will be frozen, but the built-in selection
  2607. * checkbox column will still be frozen if it's in use. Setting the count to
  2608. * -1 will also disable the selection column.
  2609. * <p>
  2610. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2611. * columns} in the count.
  2612. * <p>
  2613. * The default value is 0.
  2614. *
  2615. * @param numberOfColumns
  2616. * the number of columns that should be frozen
  2617. *
  2618. * @throws IllegalArgumentException
  2619. * if the column count is less than -1 or greater than the
  2620. * number of visible columns
  2621. */
  2622. public void setFrozenColumnCount(int numberOfColumns) {
  2623. if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
  2624. throw new IllegalArgumentException(
  2625. "count must be between -1 and the current number of columns ("
  2626. + columnSet.size() + "): " + numberOfColumns);
  2627. }
  2628. getState().frozenColumnCount = numberOfColumns;
  2629. }
  2630. /**
  2631. * Gets the number of frozen columns in this grid. 0 means that no data
  2632. * columns will be frozen, but the built-in selection checkbox column will
  2633. * still be frozen if it's in use. -1 means that not even the selection
  2634. * column is frozen.
  2635. * <p>
  2636. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2637. * columns} in the count.
  2638. *
  2639. * @see #setFrozenColumnCount(int)
  2640. *
  2641. * @return the number of frozen columns
  2642. */
  2643. public int getFrozenColumnCount() {
  2644. return getState(false).frozenColumnCount;
  2645. }
  2646. /**
  2647. * Sets the number of rows that should be visible in Grid's body. This
  2648. * method will set the height mode to be {@link HeightMode#ROW}.
  2649. *
  2650. * @param rows
  2651. * The height in terms of number of rows displayed in Grid's
  2652. * body. If Grid doesn't contain enough rows, white space is
  2653. * displayed instead. If <code>null</code> is given, then Grid's
  2654. * height is undefined
  2655. * @throws IllegalArgumentException
  2656. * if {@code rows} is zero or less
  2657. * @throws IllegalArgumentException
  2658. * if {@code rows} is {@link Double#isInfinite(double) infinite}
  2659. * @throws IllegalArgumentException
  2660. * if {@code rows} is {@link Double#isNaN(double) NaN}
  2661. */
  2662. public void setHeightByRows(double rows) {
  2663. if (rows <= 0.0d) {
  2664. throw new IllegalArgumentException(
  2665. "More than zero rows must be shown.");
  2666. } else if (Double.isInfinite(rows)) {
  2667. throw new IllegalArgumentException(
  2668. "Grid doesn't support infinite heights");
  2669. } else if (Double.isNaN(rows)) {
  2670. throw new IllegalArgumentException("NaN is not a valid row count");
  2671. }
  2672. getState().heightMode = HeightMode.ROW;
  2673. getState().heightByRows = rows;
  2674. }
  2675. /**
  2676. * Gets the amount of rows in Grid's body that are shown, while
  2677. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  2678. *
  2679. * @return the amount of rows that are being shown in Grid's body
  2680. * @see #setHeightByRows(double)
  2681. */
  2682. public double getHeightByRows() {
  2683. return getState(false).heightByRows;
  2684. }
  2685. /**
  2686. * {@inheritDoc}
  2687. * <p>
  2688. * <em>Note:</em> This method will set the height mode to be
  2689. * {@link HeightMode#CSS}.
  2690. *
  2691. * @see #setHeightMode(HeightMode)
  2692. */
  2693. @Override
  2694. public void setHeight(float height, Unit unit) {
  2695. getState().heightMode = HeightMode.CSS;
  2696. super.setHeight(height, unit);
  2697. }
  2698. /**
  2699. * Defines the mode in which the Grid widget's height is calculated.
  2700. * <p>
  2701. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  2702. * via a {@code setHeight}-method, and behave as a traditional Component.
  2703. * <p>
  2704. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  2705. * will display as many rows as {@link #getHeightByRows()} defines.
  2706. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  2707. * will resize itself to still display the required amount of rows in its
  2708. * body. It also takes the horizontal scrollbar into account.
  2709. *
  2710. * @param heightMode
  2711. * the mode in to which Grid should be set
  2712. */
  2713. public void setHeightMode(HeightMode heightMode) {
  2714. /*
  2715. * This method is a workaround for the fact that Vaadin re-applies
  2716. * widget dimensions (height/width) on each state change event. The
  2717. * original design was to have setHeight and setHeightByRow be equals,
  2718. * and whichever was called the latest was considered in effect.
  2719. *
  2720. * But, because of Vaadin always calling setHeight on the widget, this
  2721. * approach doesn't work.
  2722. */
  2723. getState().heightMode = heightMode;
  2724. }
  2725. /**
  2726. * Returns the current {@link HeightMode} the Grid is in.
  2727. * <p>
  2728. * Defaults to {@link HeightMode#CSS}.
  2729. *
  2730. * @return the current HeightMode
  2731. */
  2732. public HeightMode getHeightMode() {
  2733. return getState(false).heightMode;
  2734. }
  2735. /**
  2736. * Sets the height of body, header and footer rows. If -1 (default), the row
  2737. * height is calculated based on the theme for an empty row before the Grid
  2738. * is displayed.
  2739. * <p>
  2740. * Note that all header, body and footer rows get the same height if
  2741. * explicitly set. In automatic mode, each section is calculated separately
  2742. * based on an empty row of that type.
  2743. *
  2744. * @see #setBodyRowHeight(double)
  2745. * @see #setHeaderRowHeight(double)
  2746. * @see #setFooterRowHeight(double)
  2747. *
  2748. * @param rowHeight
  2749. * The height of a row in pixels or -1 for automatic calculation
  2750. */
  2751. public void setRowHeight(double rowHeight) {
  2752. setBodyRowHeight(rowHeight);
  2753. setHeaderRowHeight(rowHeight);
  2754. setFooterRowHeight(rowHeight);
  2755. }
  2756. /**
  2757. * Sets the height of a body row. If -1 (default), the row height is
  2758. * calculated based on the theme for an empty row before the Grid is
  2759. * displayed.
  2760. *
  2761. * @param rowHeight
  2762. * The height of a row in pixels or -1 for automatic calculation
  2763. * @since 8.2
  2764. */
  2765. public void setBodyRowHeight(double rowHeight) {
  2766. getState().bodyRowHeight = rowHeight;
  2767. }
  2768. /**
  2769. * Sets the height of a header row. If -1 (default), the row height is
  2770. * calculated based on the theme for an empty row before the Grid is
  2771. * displayed.
  2772. *
  2773. * @param rowHeight
  2774. * The height of a row in pixels or -1 for automatic calculation
  2775. * @since 8.2
  2776. */
  2777. public void setHeaderRowHeight(double rowHeight) {
  2778. getState().headerRowHeight = rowHeight;
  2779. }
  2780. /**
  2781. * Sets the height of a footer row. If -1 (default), the row height is
  2782. * calculated based on the theme for an empty row before the Grid is
  2783. * displayed.
  2784. *
  2785. * @param rowHeight
  2786. * The height of a row in pixels or -1 for automatic calculation
  2787. * @since 8.2
  2788. */
  2789. public void setFooterRowHeight(double rowHeight) {
  2790. getState().footerRowHeight = rowHeight;
  2791. }
  2792. /**
  2793. * Returns the current body row height.-1 if row height is in automatic
  2794. * calculation mode.
  2795. *
  2796. * @see #getBodyRowHeight()
  2797. * @see #getHeaderRowHeight()
  2798. * @see #getFooterRowHeight()
  2799. *
  2800. * @return body row height
  2801. * @deprecated replaced by three separate row height controls
  2802. */
  2803. @Deprecated
  2804. public double getRowHeight() {
  2805. return getBodyRowHeight();
  2806. }
  2807. /**
  2808. * Returns the current body row height. -1 if row height is in automatic
  2809. * calculation mode.
  2810. *
  2811. * @return body row height
  2812. * @since 8.2
  2813. */
  2814. public double getBodyRowHeight() {
  2815. return getState(false).bodyRowHeight;
  2816. }
  2817. /**
  2818. * Returns the current header row height. -1 if row height is in automatic
  2819. * calculation mode.
  2820. *
  2821. * @return header row height
  2822. * @since 8.2
  2823. */
  2824. public double getHeaderRowHeight() {
  2825. return getState(false).headerRowHeight;
  2826. }
  2827. /**
  2828. * Returns the current footer row height. -1 if row height is in automatic
  2829. * calculation mode.
  2830. *
  2831. * @return footer row height
  2832. * @since 8.2
  2833. */
  2834. public double getFooterRowHeight() {
  2835. return getState(false).footerRowHeight;
  2836. }
  2837. /**
  2838. * Sets the style generator that is used for generating class names for rows
  2839. * in this grid. Returning null from the generator results in no custom
  2840. * style name being set.
  2841. *
  2842. * @see StyleGenerator
  2843. *
  2844. * @param styleGenerator
  2845. * the row style generator to set, not null
  2846. * @throws NullPointerException
  2847. * if {@code styleGenerator} is {@code null}
  2848. */
  2849. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  2850. Objects.requireNonNull(styleGenerator,
  2851. "Style generator must not be null");
  2852. this.styleGenerator = styleGenerator;
  2853. getDataCommunicator().reset();
  2854. }
  2855. /**
  2856. * Gets the style generator that is used for generating class names for
  2857. * rows.
  2858. *
  2859. * @see StyleGenerator
  2860. *
  2861. * @return the row style generator
  2862. */
  2863. public StyleGenerator<T> getStyleGenerator() {
  2864. return styleGenerator;
  2865. }
  2866. /**
  2867. * Sets the description generator that is used for generating descriptions
  2868. * for rows.
  2869. *
  2870. * @param descriptionGenerator
  2871. * the row description generator to set, or <code>null</code> to
  2872. * remove a previously set generator
  2873. */
  2874. public void setDescriptionGenerator(
  2875. DescriptionGenerator<T> descriptionGenerator) {
  2876. this.descriptionGenerator = descriptionGenerator;
  2877. getDataCommunicator().reset();
  2878. }
  2879. /**
  2880. * Gets the description generator that is used for generating descriptions
  2881. * for rows.
  2882. *
  2883. * @return the row description generator, or <code>null</code> if no
  2884. * generator is set
  2885. */
  2886. public DescriptionGenerator<T> getDescriptionGenerator() {
  2887. return descriptionGenerator;
  2888. }
  2889. //
  2890. // HEADER AND FOOTER
  2891. //
  2892. /**
  2893. * Returns the header row at the given index.
  2894. *
  2895. * @param index
  2896. * the index of the row, where the topmost row has index zero
  2897. * @return the header row at the index
  2898. * @throws IndexOutOfBoundsException
  2899. * if {@code rowIndex < 0 || rowIndex >= getHeaderRowCount()}
  2900. */
  2901. public HeaderRow getHeaderRow(int index) {
  2902. return getHeader().getRow(index);
  2903. }
  2904. /**
  2905. * Gets the number of rows in the header section.
  2906. *
  2907. * @return the number of header rows
  2908. */
  2909. public int getHeaderRowCount() {
  2910. return header.getRowCount();
  2911. }
  2912. /**
  2913. * Inserts a new row at the given position to the header section. Shifts the
  2914. * row currently at that position and any subsequent rows down (adds one to
  2915. * their indices). Inserting at {@link #getHeaderRowCount()} appends the row
  2916. * at the bottom of the header.
  2917. *
  2918. * @param index
  2919. * the index at which to insert the row, where the topmost row
  2920. * has index zero
  2921. * @return the inserted header row
  2922. *
  2923. * @throws IndexOutOfBoundsException
  2924. * if {@code rowIndex < 0 || rowIndex > getHeaderRowCount()}
  2925. *
  2926. * @see #appendHeaderRow()
  2927. * @see #prependHeaderRow()
  2928. * @see #removeHeaderRow(HeaderRow)
  2929. * @see #removeHeaderRow(int)
  2930. */
  2931. public HeaderRow addHeaderRowAt(int index) {
  2932. return getHeader().addRowAt(index);
  2933. }
  2934. /**
  2935. * Adds a new row at the bottom of the header section.
  2936. *
  2937. * @return the appended header row
  2938. *
  2939. * @see #prependHeaderRow()
  2940. * @see #addHeaderRowAt(int)
  2941. * @see #removeHeaderRow(HeaderRow)
  2942. * @see #removeHeaderRow(int)
  2943. */
  2944. public HeaderRow appendHeaderRow() {
  2945. return addHeaderRowAt(getHeaderRowCount());
  2946. }
  2947. /**
  2948. * Adds a new row at the top of the header section.
  2949. *
  2950. * @return the prepended header row
  2951. *
  2952. * @see #appendHeaderRow()
  2953. * @see #addHeaderRowAt(int)
  2954. * @see #removeHeaderRow(HeaderRow)
  2955. * @see #removeHeaderRow(int)
  2956. */
  2957. public HeaderRow prependHeaderRow() {
  2958. return addHeaderRowAt(0);
  2959. }
  2960. /**
  2961. * Removes the given row from the header section. Removing a default row
  2962. * sets the Grid to have no default row.
  2963. *
  2964. * @param row
  2965. * the header row to be removed, not null
  2966. *
  2967. * @throws IllegalArgumentException
  2968. * if the header does not contain the row
  2969. *
  2970. * @see #removeHeaderRow(int)
  2971. * @see #addHeaderRowAt(int)
  2972. * @see #appendHeaderRow()
  2973. * @see #prependHeaderRow()
  2974. */
  2975. public void removeHeaderRow(HeaderRow row) {
  2976. getHeader().removeRow(row);
  2977. }
  2978. /**
  2979. * Removes the row at the given position from the header section.
  2980. *
  2981. * @param index
  2982. * the index of the row to remove, where the topmost row has
  2983. * index zero
  2984. *
  2985. * @throws IndexOutOfBoundsException
  2986. * if {@code index < 0 || index >= getHeaderRowCount()}
  2987. *
  2988. * @see #removeHeaderRow(HeaderRow)
  2989. * @see #addHeaderRowAt(int)
  2990. * @see #appendHeaderRow()
  2991. * @see #prependHeaderRow()
  2992. */
  2993. public void removeHeaderRow(int index) {
  2994. getHeader().removeRow(index);
  2995. }
  2996. /**
  2997. * Sets the visibility of the Header in this Grid.
  2998. *
  2999. * @param headerVisible
  3000. * {@code true} if visible; {@code false} if not
  3001. *
  3002. * @since 8.1.1
  3003. */
  3004. public void setHeaderVisible(boolean headerVisible) {
  3005. getHeader().setVisible(headerVisible);
  3006. }
  3007. /**
  3008. * Gets the visibility of the Header in this Grid.
  3009. *
  3010. * @return {@code true} if visible; {@code false} if not
  3011. *
  3012. * @since 8.1.1
  3013. */
  3014. public boolean isHeaderVisible() {
  3015. return getHeader().isVisible();
  3016. }
  3017. /**
  3018. * Returns the current default row of the header.
  3019. *
  3020. * @return the default row or null if no default row set
  3021. *
  3022. * @see #setDefaultHeaderRow(HeaderRow)
  3023. */
  3024. public HeaderRow getDefaultHeaderRow() {
  3025. return header.getDefaultRow();
  3026. }
  3027. /**
  3028. * Sets the default row of the header. The default row is a special header
  3029. * row that displays column captions and sort indicators. By default Grid
  3030. * has a single row which is also the default row. When a header row is set
  3031. * as the default row, any existing cell content is replaced by the column
  3032. * captions.
  3033. *
  3034. * @param row
  3035. * the new default row, or null for no default row
  3036. *
  3037. * @throws IllegalArgumentException
  3038. * if the header does not contain the row
  3039. */
  3040. public void setDefaultHeaderRow(HeaderRow row) {
  3041. header.setDefaultRow((Row) row);
  3042. }
  3043. /**
  3044. * Returns the header section of this grid. The default header contains a
  3045. * single row, set as the {@linkplain #setDefaultHeaderRow(HeaderRow)
  3046. * default row}.
  3047. *
  3048. * @return the header section
  3049. */
  3050. protected Header getHeader() {
  3051. return header;
  3052. }
  3053. /**
  3054. * Returns the footer row at the given index.
  3055. *
  3056. * @param index
  3057. * the index of the row, where the topmost row has index zero
  3058. * @return the footer row at the index
  3059. * @throws IndexOutOfBoundsException
  3060. * if {@code rowIndex < 0 || rowIndex >= getFooterRowCount()}
  3061. */
  3062. public FooterRow getFooterRow(int index) {
  3063. return getFooter().getRow(index);
  3064. }
  3065. /**
  3066. * Gets the number of rows in the footer section.
  3067. *
  3068. * @return the number of footer rows
  3069. */
  3070. public int getFooterRowCount() {
  3071. return getFooter().getRowCount();
  3072. }
  3073. /**
  3074. * Inserts a new row at the given position to the footer section. Shifts the
  3075. * row currently at that position and any subsequent rows down (adds one to
  3076. * their indices). Inserting at {@link #getFooterRowCount()} appends the row
  3077. * at the bottom of the footer.
  3078. *
  3079. * @param index
  3080. * the index at which to insert the row, where the topmost row
  3081. * has index zero
  3082. * @return the inserted footer row
  3083. *
  3084. * @throws IndexOutOfBoundsException
  3085. * if {@code rowIndex < 0 || rowIndex > getFooterRowCount()}
  3086. *
  3087. * @see #appendFooterRow()
  3088. * @see #prependFooterRow()
  3089. * @see #removeFooterRow(FooterRow)
  3090. * @see #removeFooterRow(int)
  3091. */
  3092. public FooterRow addFooterRowAt(int index) {
  3093. return getFooter().addRowAt(index);
  3094. }
  3095. /**
  3096. * Adds a new row at the bottom of the footer section.
  3097. *
  3098. * @return the appended footer row
  3099. *
  3100. * @see #prependFooterRow()
  3101. * @see #addFooterRowAt(int)
  3102. * @see #removeFooterRow(FooterRow)
  3103. * @see #removeFooterRow(int)
  3104. */
  3105. public FooterRow appendFooterRow() {
  3106. return addFooterRowAt(getFooterRowCount());
  3107. }
  3108. /**
  3109. * Adds a new row at the top of the footer section.
  3110. *
  3111. * @return the prepended footer row
  3112. *
  3113. * @see #appendFooterRow()
  3114. * @see #addFooterRowAt(int)
  3115. * @see #removeFooterRow(FooterRow)
  3116. * @see #removeFooterRow(int)
  3117. */
  3118. public FooterRow prependFooterRow() {
  3119. return addFooterRowAt(0);
  3120. }
  3121. /**
  3122. * Removes the given row from the footer section. Removing a default row
  3123. * sets the Grid to have no default row.
  3124. *
  3125. * @param row
  3126. * the footer row to be removed, not null
  3127. *
  3128. * @throws IllegalArgumentException
  3129. * if the footer does not contain the row
  3130. *
  3131. * @see #removeFooterRow(int)
  3132. * @see #addFooterRowAt(int)
  3133. * @see #appendFooterRow()
  3134. * @see #prependFooterRow()
  3135. */
  3136. public void removeFooterRow(FooterRow row) {
  3137. getFooter().removeRow(row);
  3138. }
  3139. /**
  3140. * Removes the row at the given position from the footer section.
  3141. *
  3142. * @param index
  3143. * the index of the row to remove, where the topmost row has
  3144. * index zero
  3145. *
  3146. * @throws IndexOutOfBoundsException
  3147. * if {@code index < 0 || index >= getFooterRowCount()}
  3148. *
  3149. * @see #removeFooterRow(FooterRow)
  3150. * @see #addFooterRowAt(int)
  3151. * @see #appendFooterRow()
  3152. * @see #prependFooterRow()
  3153. */
  3154. public void removeFooterRow(int index) {
  3155. getFooter().removeRow(index);
  3156. }
  3157. /**
  3158. * Sets the visibility of the Footer in this Grid.
  3159. *
  3160. * @param footerVisible
  3161. * {@code true} if visible; {@code false} if not
  3162. *
  3163. * @since 8.1.1
  3164. */
  3165. public void setFooterVisible(boolean footerVisible) {
  3166. getFooter().setVisible(footerVisible);
  3167. }
  3168. /**
  3169. * Gets the visibility of the Footer in this Grid.
  3170. *
  3171. * @return {@code true} if visible; {@code false} if not
  3172. *
  3173. * @since 8.1.1
  3174. */
  3175. public boolean isFooterVisible() {
  3176. return getFooter().isVisible();
  3177. }
  3178. /**
  3179. * Returns the footer section of this grid.
  3180. *
  3181. * @return the footer section
  3182. */
  3183. protected Footer getFooter() {
  3184. return footer;
  3185. }
  3186. /**
  3187. * Registers a new column reorder listener.
  3188. *
  3189. * @param listener
  3190. * the listener to register, not null
  3191. * @return a registration for the listener
  3192. */
  3193. public Registration addColumnReorderListener(
  3194. ColumnReorderListener listener) {
  3195. return addListener(ColumnReorderEvent.class, listener,
  3196. COLUMN_REORDER_METHOD);
  3197. }
  3198. /**
  3199. * Registers a new column resize listener.
  3200. *
  3201. * @param listener
  3202. * the listener to register, not null
  3203. * @return a registration for the listener
  3204. */
  3205. public Registration addColumnResizeListener(ColumnResizeListener listener) {
  3206. return addListener(ColumnResizeEvent.class, listener,
  3207. COLUMN_RESIZE_METHOD);
  3208. }
  3209. /**
  3210. * Adds an item click listener. The listener is called when an item of this
  3211. * {@code Grid} is clicked.
  3212. *
  3213. * @param listener
  3214. * the item click listener, not null
  3215. * @return a registration for the listener
  3216. * @see #addContextClickListener
  3217. */
  3218. public Registration addItemClickListener(
  3219. ItemClickListener<? super T> listener) {
  3220. return addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
  3221. listener, ITEM_CLICK_METHOD);
  3222. }
  3223. /**
  3224. * Adds a context click listener that gets notified when a context click
  3225. * happens.
  3226. *
  3227. * @param listener
  3228. * the context click listener to add, not null actual event
  3229. * provided to the listener is {@link GridContextClickEvent}
  3230. * @return a registration object for removing the listener
  3231. *
  3232. * @since 8.1
  3233. * @see #addItemClickListener
  3234. * @see Registration
  3235. */
  3236. @Override
  3237. public Registration addContextClickListener(
  3238. ContextClickEvent.ContextClickListener listener) {
  3239. return super.addContextClickListener(listener);
  3240. }
  3241. /**
  3242. * Registers a new column visibility change listener.
  3243. *
  3244. * @param listener
  3245. * the listener to register, not null
  3246. * @return a registration for the listener
  3247. */
  3248. public Registration addColumnVisibilityChangeListener(
  3249. ColumnVisibilityChangeListener listener) {
  3250. return addListener(ColumnVisibilityChangeEvent.class, listener,
  3251. COLUMN_VISIBILITY_METHOD);
  3252. }
  3253. /**
  3254. * Returns whether column reordering is allowed. Default value is
  3255. * <code>false</code>.
  3256. *
  3257. * @return true if reordering is allowed
  3258. */
  3259. public boolean isColumnReorderingAllowed() {
  3260. return getState(false).columnReorderingAllowed;
  3261. }
  3262. /**
  3263. * Sets whether or not column reordering is allowed. Default value is
  3264. * <code>false</code>.
  3265. *
  3266. * @param columnReorderingAllowed
  3267. * specifies whether column reordering is allowed
  3268. */
  3269. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  3270. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  3271. getState().columnReorderingAllowed = columnReorderingAllowed;
  3272. }
  3273. }
  3274. /**
  3275. * Sets the columns and their order based on their column ids. Columns
  3276. * currently in this grid that are not present in the list of column ids are
  3277. * removed. This includes any column that has no id. Similarly, any new
  3278. * column in columns will be added to this grid. New columns can only be
  3279. * added for a <code>Grid</code> created using {@link Grid#Grid(Class)} or
  3280. * {@link #withPropertySet(PropertySet)}.
  3281. *
  3282. *
  3283. * @param columnIds
  3284. * the column ids to set
  3285. *
  3286. * @see Column#setId(String)
  3287. */
  3288. public void setColumns(String... columnIds) {
  3289. // Must extract to an explicitly typed variable because otherwise javac
  3290. // cannot determine which overload of setColumnOrder to use
  3291. Column<T, ?>[] newColumnOrder = Stream.of(columnIds)
  3292. .map((Function<String, Column<T, ?>>) id -> {
  3293. Column<T, ?> column = getColumn(id);
  3294. if (column == null) {
  3295. column = addColumn(id);
  3296. }
  3297. return column;
  3298. }).toArray(Column[]::new);
  3299. setColumnOrder(newColumnOrder);
  3300. // The columns to remove are now at the end of the column list
  3301. getColumns().stream().skip(columnIds.length)
  3302. .forEach(this::removeColumn);
  3303. }
  3304. private String getGeneratedIdentifier() {
  3305. String columnId = "" + counter;
  3306. counter++;
  3307. return columnId;
  3308. }
  3309. /**
  3310. * Sets a new column order for the grid. All columns which are not ordered
  3311. * here will remain in the order they were before as the last columns of
  3312. * grid.
  3313. *
  3314. * @param columns
  3315. * the columns in the order they should be
  3316. */
  3317. public void setColumnOrder(Column<T, ?>... columns) {
  3318. setColumnOrder(Stream.of(columns));
  3319. }
  3320. private void setColumnOrder(Stream<Column<T, ?>> columns) {
  3321. List<String> columnOrder = new ArrayList<>();
  3322. columns.forEach(column -> {
  3323. if (columnSet.contains(column)) {
  3324. columnOrder.add(column.getInternalId());
  3325. } else {
  3326. throw new IllegalStateException(
  3327. "setColumnOrder should not be called "
  3328. + "with columns that are not in the grid.");
  3329. }
  3330. });
  3331. List<String> stateColumnOrder = getState().columnOrder;
  3332. if (stateColumnOrder.size() != columnOrder.size()) {
  3333. stateColumnOrder.removeAll(columnOrder);
  3334. columnOrder.addAll(stateColumnOrder);
  3335. }
  3336. getState().columnOrder = columnOrder;
  3337. fireColumnReorderEvent(false);
  3338. }
  3339. /**
  3340. * Sets a new column order for the grid based on their column ids. All
  3341. * columns which are not ordered here will remain in the order they were
  3342. * before as the last columns of grid.
  3343. *
  3344. * @param columnIds
  3345. * the column ids in the order they should be
  3346. *
  3347. * @see Column#setId(String)
  3348. */
  3349. public void setColumnOrder(String... columnIds) {
  3350. setColumnOrder(Stream.of(columnIds).map(this::getColumnOrThrow));
  3351. }
  3352. /**
  3353. * Returns the selection model for this grid.
  3354. *
  3355. * @return the selection model, not null
  3356. */
  3357. public GridSelectionModel<T> getSelectionModel() {
  3358. assert selectionModel != null : "No selection model set by "
  3359. + getClass().getName() + " constructor";
  3360. return selectionModel;
  3361. }
  3362. /**
  3363. * Use this grid as a single select in {@link Binder}.
  3364. * <p>
  3365. * Throws {@link IllegalStateException} if the grid is not using a
  3366. * {@link SingleSelectionModel}.
  3367. *
  3368. * @return the single select wrapper that can be used in binder
  3369. * @throws IllegalStateException
  3370. * if not using a single selection model
  3371. */
  3372. public SingleSelect<T> asSingleSelect() {
  3373. GridSelectionModel<T> model = getSelectionModel();
  3374. if (!(model instanceof SingleSelectionModel)) {
  3375. throw new IllegalStateException(
  3376. "Grid is not in single select mode, it needs to be explicitly set to such with setSelectionModel(SingleSelectionModel) before being able to use single selection features.");
  3377. }
  3378. return ((SingleSelectionModel<T>) model).asSingleSelect();
  3379. }
  3380. public Editor<T> getEditor() {
  3381. return editor;
  3382. }
  3383. /**
  3384. * User this grid as a multiselect in {@link Binder}.
  3385. * <p>
  3386. * Throws {@link IllegalStateException} if the grid is not using a
  3387. * {@link MultiSelectionModel}.
  3388. *
  3389. * @return the multiselect wrapper that can be used in binder
  3390. * @throws IllegalStateException
  3391. * if not using a multiselection model
  3392. */
  3393. public MultiSelect<T> asMultiSelect() {
  3394. GridSelectionModel<T> model = getSelectionModel();
  3395. if (!(model instanceof MultiSelectionModel)) {
  3396. throw new IllegalStateException(
  3397. "Grid is not in multiselect mode, it needs to be explicitly set to such with setSelectionModel(MultiSelectionModel) before being able to use multiselection features.");
  3398. }
  3399. return ((MultiSelectionModel<T>) model).asMultiSelect();
  3400. }
  3401. /**
  3402. * Sets the selection model for the grid.
  3403. * <p>
  3404. * This method is for setting a custom selection model, and is
  3405. * {@code protected} because {@link #setSelectionMode(SelectionMode)} should
  3406. * be used for easy switching between built-in selection models.
  3407. * <p>
  3408. * The default selection model is {@link SingleSelectionModelImpl}.
  3409. * <p>
  3410. * To use a custom selection model, you can e.g. extend the grid call this
  3411. * method with your custom selection model.
  3412. *
  3413. * @param model
  3414. * the selection model to use, not {@code null}
  3415. *
  3416. * @see #setSelectionMode(SelectionMode)
  3417. */
  3418. @SuppressWarnings("unchecked")
  3419. protected void setSelectionModel(GridSelectionModel<T> model) {
  3420. Objects.requireNonNull(model, "selection model cannot be null");
  3421. if (selectionModel != null) { // null when called from constructor
  3422. selectionModel.remove();
  3423. }
  3424. selectionModel = model;
  3425. if (selectionModel instanceof AbstractListingExtension) {
  3426. ((AbstractListingExtension<T>) selectionModel).extend(this);
  3427. } else {
  3428. addExtension(selectionModel);
  3429. }
  3430. }
  3431. /**
  3432. * Sets the grid's selection mode.
  3433. * <p>
  3434. * The built-in selection models are:
  3435. * <ul>
  3436. * <li>{@link SelectionMode#SINGLE} -> {@link SingleSelectionModelImpl},
  3437. * <b>the default model</b></li>
  3438. * <li>{@link SelectionMode#MULTI} -> {@link MultiSelectionModelImpl}, with
  3439. * checkboxes in the first column for selection</li>
  3440. * <li>{@link SelectionMode#NONE} -> {@link NoSelectionModel}, preventing
  3441. * selection</li>
  3442. * </ul>
  3443. * <p>
  3444. * To use your custom selection model, you can use
  3445. * {@link #setSelectionModel(GridSelectionModel)}, see existing selection
  3446. * model implementations for example.
  3447. *
  3448. * @param selectionMode
  3449. * the selection mode to switch to, not {@code null}
  3450. * @return the used selection model
  3451. *
  3452. * @see SelectionMode
  3453. * @see GridSelectionModel
  3454. * @see #setSelectionModel(GridSelectionModel)
  3455. */
  3456. public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  3457. Objects.requireNonNull(selectionMode, "Selection mode cannot be null.");
  3458. GridSelectionModel<T> model = selectionMode.createModel();
  3459. setSelectionModel(model);
  3460. return model;
  3461. }
  3462. /**
  3463. * This method is a shorthand that delegates to the currently set selection
  3464. * model.
  3465. *
  3466. * @see #getSelectionModel()
  3467. * @see GridSelectionModel
  3468. */
  3469. public Set<T> getSelectedItems() {
  3470. return getSelectionModel().getSelectedItems();
  3471. }
  3472. /**
  3473. * This method is a shorthand that delegates to the currently set selection
  3474. * model.
  3475. *
  3476. * @see #getSelectionModel()
  3477. * @see GridSelectionModel
  3478. */
  3479. public void select(T item) {
  3480. getSelectionModel().select(item);
  3481. }
  3482. /**
  3483. * This method is a shorthand that delegates to the currently set selection
  3484. * model.
  3485. *
  3486. * @see #getSelectionModel()
  3487. * @see GridSelectionModel
  3488. */
  3489. public void deselect(T item) {
  3490. getSelectionModel().deselect(item);
  3491. }
  3492. /**
  3493. * This method is a shorthand that delegates to the currently set selection
  3494. * model.
  3495. *
  3496. * @see #getSelectionModel()
  3497. * @see GridSelectionModel
  3498. */
  3499. public void deselectAll() {
  3500. getSelectionModel().deselectAll();
  3501. }
  3502. /**
  3503. * Adds a selection listener to the current selection model.
  3504. * <p>
  3505. * <em>NOTE:</em> If selection mode is switched with
  3506. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  3507. * triggered anymore when selection changes!
  3508. * <p>
  3509. * This is a shorthand for
  3510. * {@code grid.getSelectionModel().addSelectionListener()}. To get more
  3511. * detailed selection events, use {@link #getSelectionModel()} and either
  3512. * {@link SingleSelectionModel#addSingleSelectionListener(SingleSelectionListener)}
  3513. * or
  3514. * {@link MultiSelectionModel#addMultiSelectionListener(MultiSelectionListener)}
  3515. * depending on the used selection mode.
  3516. *
  3517. * @param listener
  3518. * the listener to add
  3519. * @return a registration handle to remove the listener
  3520. * @throws UnsupportedOperationException
  3521. * if selection has been disabled with
  3522. * {@link SelectionMode#NONE}
  3523. */
  3524. public Registration addSelectionListener(SelectionListener<T> listener)
  3525. throws UnsupportedOperationException {
  3526. return getSelectionModel().addSelectionListener(listener);
  3527. }
  3528. /**
  3529. * Sort this Grid in ascending order by a specified column.
  3530. *
  3531. * @param column
  3532. * a column to sort against
  3533. *
  3534. */
  3535. public void sort(Column<T, ?> column) {
  3536. sort(column, SortDirection.ASCENDING);
  3537. }
  3538. /**
  3539. * Sort this Grid in user-specified direction by a column.
  3540. *
  3541. * @param column
  3542. * a column to sort against
  3543. * @param direction
  3544. * a sort order value (ascending/descending)
  3545. *
  3546. */
  3547. public void sort(Column<T, ?> column, SortDirection direction) {
  3548. setSortOrder(Collections
  3549. .singletonList(new GridSortOrder<>(column, direction)));
  3550. }
  3551. /**
  3552. * Sort this Grid in ascending order by a specified column defined by id.
  3553. *
  3554. * @param columnId
  3555. * the id of the column to sort against
  3556. *
  3557. * @see Column#setId(String)
  3558. */
  3559. public void sort(String columnId) {
  3560. sort(columnId, SortDirection.ASCENDING);
  3561. }
  3562. /**
  3563. * Sort this Grid in a user-specified direction by a column defined by id.
  3564. *
  3565. * @param columnId
  3566. * the id of the column to sort against
  3567. * @param direction
  3568. * a sort order value (ascending/descending)
  3569. *
  3570. * @see Column#setId(String)
  3571. */
  3572. public void sort(String columnId, SortDirection direction) {
  3573. sort(getColumnOrThrow(columnId), direction);
  3574. }
  3575. /**
  3576. * Clear the current sort order, and re-sort the grid.
  3577. */
  3578. public void clearSortOrder() {
  3579. sortOrder.clear();
  3580. sort(false);
  3581. }
  3582. /**
  3583. * Sets the sort order to use.
  3584. *
  3585. * @param order
  3586. * a sort order list.
  3587. *
  3588. * @throws IllegalArgumentException
  3589. * if order is null
  3590. */
  3591. public void setSortOrder(List<GridSortOrder<T>> order) {
  3592. setSortOrder(order, false);
  3593. }
  3594. /**
  3595. * Sets the sort order to use, given a {@link GridSortOrderBuilder}.
  3596. * Shorthand for {@code setSortOrder(builder.build())}.
  3597. *
  3598. * @see GridSortOrderBuilder
  3599. *
  3600. * @param builder
  3601. * the sort builder to retrieve the sort order from
  3602. * @throws NullPointerException
  3603. * if builder is null
  3604. */
  3605. public void setSortOrder(GridSortOrderBuilder<T> builder) {
  3606. Objects.requireNonNull(builder, "Sort builder cannot be null");
  3607. setSortOrder(builder.build());
  3608. }
  3609. /**
  3610. * Adds a sort order change listener that gets notified when the sort order
  3611. * changes.
  3612. *
  3613. * @param listener
  3614. * the sort order change listener to add
  3615. */
  3616. @Override
  3617. public Registration addSortListener(
  3618. SortListener<GridSortOrder<T>> listener) {
  3619. return addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  3620. }
  3621. /**
  3622. * Get the current sort order list.
  3623. *
  3624. * @return a sort order list
  3625. */
  3626. public List<GridSortOrder<T>> getSortOrder() {
  3627. return Collections.unmodifiableList(sortOrder);
  3628. }
  3629. /**
  3630. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  3631. * <p>
  3632. * If the item has an open details row, its size will also be taken into
  3633. * account.
  3634. *
  3635. * @param row
  3636. * zero based index of the item to scroll to in the current view.
  3637. * @throws IllegalArgumentException
  3638. * if the provided row is outside the item range
  3639. */
  3640. public void scrollTo(int row) throws IllegalArgumentException {
  3641. scrollTo(row, ScrollDestination.ANY);
  3642. }
  3643. /**
  3644. * Scrolls to a certain item, using user-specified scroll destination.
  3645. * <p>
  3646. * If the item has an open details row, its size will also be taken into
  3647. * account.
  3648. *
  3649. * @param row
  3650. * zero based index of the item to scroll to in the current view.
  3651. * @param destination
  3652. * value specifying desired position of scrolled-to row, not
  3653. * {@code null}
  3654. * @throws IllegalArgumentException
  3655. * if the provided row is outside the item range
  3656. */
  3657. public void scrollTo(int row, ScrollDestination destination) {
  3658. Objects.requireNonNull(destination,
  3659. "ScrollDestination can not be null");
  3660. if (row > getDataCommunicator().getDataProviderSize()) {
  3661. throw new IllegalArgumentException("Row outside dataProvider size");
  3662. }
  3663. getRpcProxy(GridClientRpc.class).scrollToRow(row, destination);
  3664. }
  3665. /**
  3666. * Scrolls to the beginning of the first data row.
  3667. */
  3668. public void scrollToStart() {
  3669. getRpcProxy(GridClientRpc.class).scrollToStart();
  3670. }
  3671. /**
  3672. * Scrolls to the end of the last data row.
  3673. */
  3674. public void scrollToEnd() {
  3675. getRpcProxy(GridClientRpc.class).scrollToEnd();
  3676. }
  3677. @Override
  3678. protected GridState getState() {
  3679. return getState(true);
  3680. }
  3681. @Override
  3682. protected GridState getState(boolean markAsDirty) {
  3683. return (GridState) super.getState(markAsDirty);
  3684. }
  3685. /**
  3686. * Sets the column resize mode to use. The default mode is
  3687. * {@link ColumnResizeMode#ANIMATED}.
  3688. *
  3689. * @param mode
  3690. * a ColumnResizeMode value
  3691. * @since 7.7.5
  3692. */
  3693. public void setColumnResizeMode(ColumnResizeMode mode) {
  3694. getState().columnResizeMode = mode;
  3695. }
  3696. /**
  3697. * Returns the current column resize mode. The default mode is
  3698. * {@link ColumnResizeMode#ANIMATED}.
  3699. *
  3700. * @return a ColumnResizeMode value
  3701. * @since 7.7.5
  3702. */
  3703. public ColumnResizeMode getColumnResizeMode() {
  3704. return getState(false).columnResizeMode;
  3705. }
  3706. /**
  3707. * Creates a new Editor instance. Can be overridden to create a custom
  3708. * Editor. If the Editor is a {@link AbstractGridExtension}, it will be
  3709. * automatically added to {@link DataCommunicator}.
  3710. *
  3711. * @return editor
  3712. */
  3713. protected Editor<T> createEditor() {
  3714. return new EditorImpl<>(propertySet);
  3715. }
  3716. private void addExtensionComponent(Component c) {
  3717. if (extensionComponents.add(c)) {
  3718. c.setParent(this);
  3719. markAsDirty();
  3720. }
  3721. }
  3722. private void removeExtensionComponent(Component c) {
  3723. if (extensionComponents.remove(c)) {
  3724. c.setParent(null);
  3725. markAsDirty();
  3726. }
  3727. }
  3728. private void fireColumnReorderEvent(boolean userOriginated) {
  3729. fireEvent(new ColumnReorderEvent(this, userOriginated));
  3730. }
  3731. private void fireColumnResizeEvent(Column<?, ?> column,
  3732. boolean userOriginated) {
  3733. fireEvent(new ColumnResizeEvent(this, column, userOriginated));
  3734. }
  3735. @Override
  3736. protected void readItems(Element design, DesignContext context) {
  3737. // Grid handles reading of items in Grid#readData
  3738. }
  3739. @Override
  3740. public DataProvider<T, ?> getDataProvider() {
  3741. return internalGetDataProvider();
  3742. }
  3743. @Override
  3744. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  3745. internalSetDataProvider(dataProvider);
  3746. }
  3747. /**
  3748. * Sets a CallbackDataProvider using the given fetch items callback and a
  3749. * size callback.
  3750. * <p>
  3751. * This method is a shorthand for making a {@link CallbackDataProvider} that
  3752. * handles a partial {@link Query} object.
  3753. *
  3754. * @param fetchItems
  3755. * a callback for fetching items
  3756. * @param sizeCallback
  3757. * a callback for getting the count of items
  3758. *
  3759. * @see CallbackDataProvider
  3760. * @see #setDataProvider(DataProvider)
  3761. */
  3762. public void setDataProvider(FetchItemsCallback<T> fetchItems,
  3763. SerializableSupplier<Integer> sizeCallback) {
  3764. internalSetDataProvider(
  3765. new CallbackDataProvider<>(
  3766. q -> fetchItems.fetchItems(q.getSortOrders(),
  3767. q.getOffset(), q.getLimit()),
  3768. q -> sizeCallback.get()));
  3769. }
  3770. @Override
  3771. protected void doReadDesign(Element design, DesignContext context) {
  3772. Attributes attrs = design.attributes();
  3773. if (design.hasAttr(DECLARATIVE_DATA_ITEM_TYPE)) {
  3774. String itemType = design.attr(DECLARATIVE_DATA_ITEM_TYPE);
  3775. setBeanType(itemType);
  3776. }
  3777. if (attrs.hasKey("selection-mode")) {
  3778. setSelectionMode(DesignAttributeHandler.readAttribute(
  3779. "selection-mode", attrs, SelectionMode.class));
  3780. }
  3781. Attributes attr = design.attributes();
  3782. if (attr.hasKey("selection-allowed")) {
  3783. setReadOnly(DesignAttributeHandler
  3784. .readAttribute("selection-allowed", attr, Boolean.class));
  3785. }
  3786. if (attrs.hasKey("rows")) {
  3787. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  3788. double.class));
  3789. }
  3790. readStructure(design, context);
  3791. // Read frozen columns after columns are read.
  3792. if (attrs.hasKey("frozen-columns")) {
  3793. setFrozenColumnCount(DesignAttributeHandler
  3794. .readAttribute("frozen-columns", attrs, int.class));
  3795. }
  3796. }
  3797. /**
  3798. * Sets the bean type to use for property mapping.
  3799. * <p>
  3800. * This method is responsible also for setting or updating the property set
  3801. * so that it matches the given bean type.
  3802. * <p>
  3803. * Protected mostly for Designer needs, typically should not be overridden
  3804. * or even called.
  3805. *
  3806. * @param beanTypeClassName
  3807. * the fully qualified class name of the bean type
  3808. *
  3809. * @since 8.0.3
  3810. */
  3811. @SuppressWarnings("unchecked")
  3812. protected void setBeanType(String beanTypeClassName) {
  3813. setBeanType((Class<T>) resolveClass(beanTypeClassName));
  3814. }
  3815. /**
  3816. * Sets the bean type to use for property mapping.
  3817. * <p>
  3818. * This method is responsible also for setting or updating the property set
  3819. * so that it matches the given bean type.
  3820. * <p>
  3821. * Protected mostly for Designer needs, typically should not be overridden
  3822. * or even called.
  3823. *
  3824. * @param beanType
  3825. * the bean type class
  3826. *
  3827. * @since 8.0.3
  3828. */
  3829. protected void setBeanType(Class<T> beanType) {
  3830. this.beanType = beanType;
  3831. setPropertySet(BeanPropertySet.get(beanType));
  3832. }
  3833. private Class<?> resolveClass(String qualifiedClassName) {
  3834. try {
  3835. Class<?> resolvedClass = Class.forName(qualifiedClassName, true,
  3836. VaadinServiceClassLoaderUtil.findDefaultClassLoader());
  3837. return resolvedClass;
  3838. } catch (ClassNotFoundException | SecurityException e) {
  3839. throw new IllegalArgumentException(
  3840. "Unable to find class " + qualifiedClassName, e);
  3841. }
  3842. }
  3843. @Override
  3844. protected void doWriteDesign(Element design, DesignContext designContext) {
  3845. Attributes attr = design.attributes();
  3846. if (this.beanType != null) {
  3847. design.attr(DECLARATIVE_DATA_ITEM_TYPE,
  3848. this.beanType.getCanonicalName());
  3849. }
  3850. DesignAttributeHandler.writeAttribute("selection-allowed", attr,
  3851. isReadOnly(), false, Boolean.class, designContext);
  3852. Attributes attrs = design.attributes();
  3853. Grid<?> defaultInstance = designContext.getDefaultInstance(this);
  3854. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  3855. getFrozenColumnCount(), defaultInstance.getFrozenColumnCount(),
  3856. int.class, designContext);
  3857. if (HeightMode.ROW.equals(getHeightMode())) {
  3858. DesignAttributeHandler.writeAttribute("rows", attrs,
  3859. getHeightByRows(), defaultInstance.getHeightByRows(),
  3860. double.class, designContext);
  3861. }
  3862. SelectionMode mode = getSelectionMode();
  3863. if (mode != null) {
  3864. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  3865. SelectionMode.SINGLE, SelectionMode.class, designContext);
  3866. }
  3867. writeStructure(design, designContext);
  3868. }
  3869. @Override
  3870. protected T deserializeDeclarativeRepresentation(String item) {
  3871. if (item == null) {
  3872. return super.deserializeDeclarativeRepresentation(
  3873. UUID.randomUUID().toString());
  3874. }
  3875. return super.deserializeDeclarativeRepresentation(new String(item));
  3876. }
  3877. @Override
  3878. protected boolean isReadOnly() {
  3879. SelectionMode selectionMode = getSelectionMode();
  3880. if (SelectionMode.SINGLE.equals(selectionMode)) {
  3881. return asSingleSelect().isReadOnly();
  3882. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  3883. return asMultiSelect().isReadOnly();
  3884. }
  3885. return false;
  3886. }
  3887. @Override
  3888. protected void setReadOnly(boolean readOnly) {
  3889. SelectionMode selectionMode = getSelectionMode();
  3890. if (SelectionMode.SINGLE.equals(selectionMode)) {
  3891. asSingleSelect().setReadOnly(readOnly);
  3892. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  3893. asMultiSelect().setReadOnly(readOnly);
  3894. }
  3895. }
  3896. private void readStructure(Element design, DesignContext context) {
  3897. if (design.children().isEmpty()) {
  3898. return;
  3899. }
  3900. if (design.children().size() > 1
  3901. || !design.child(0).tagName().equals("table")) {
  3902. throw new DesignException(
  3903. "Grid needs to have a table element as its only child");
  3904. }
  3905. Element table = design.child(0);
  3906. Elements colgroups = table.getElementsByTag("colgroup");
  3907. if (colgroups.size() != 1) {
  3908. throw new DesignException(
  3909. "Table element in declarative Grid needs to have a"
  3910. + " colgroup defining the columns used in Grid");
  3911. }
  3912. List<DeclarativeValueProvider<T>> providers = new ArrayList<>();
  3913. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  3914. String id = DesignAttributeHandler.readAttribute("column-id",
  3915. col.attributes(), null, String.class);
  3916. // If there is a property with a matching name available,
  3917. // map to that
  3918. Optional<PropertyDefinition<T, ?>> property = propertySet
  3919. .getProperties().filter(p -> p.getName().equals(id))
  3920. .findFirst();
  3921. Column<T, ?> column;
  3922. if (property.isPresent()) {
  3923. column = addColumn(id);
  3924. } else {
  3925. DeclarativeValueProvider<T> provider = new DeclarativeValueProvider<>();
  3926. column = createColumn(provider, ValueProvider.identity(),
  3927. new HtmlRenderer());
  3928. addColumn(getGeneratedIdentifier(), column);
  3929. if (id != null) {
  3930. column.setId(id);
  3931. }
  3932. providers.add(provider);
  3933. }
  3934. column.readDesign(col, context);
  3935. }
  3936. for (Element child : table.children()) {
  3937. if (child.tagName().equals("thead")) {
  3938. getHeader().readDesign(child, context);
  3939. } else if (child.tagName().equals("tbody")) {
  3940. readData(child, providers);
  3941. } else if (child.tagName().equals("tfoot")) {
  3942. getFooter().readDesign(child, context);
  3943. }
  3944. }
  3945. // Sync default header captions to column captions
  3946. if (getDefaultHeaderRow() != null) {
  3947. for (Column<T, ?> c : getColumns()) {
  3948. HeaderCell headerCell = getDefaultHeaderRow().getCell(c);
  3949. if (headerCell.getCellType() == GridStaticCellType.TEXT) {
  3950. c.setCaption(headerCell.getText());
  3951. }
  3952. }
  3953. }
  3954. }
  3955. /**
  3956. * Reads the declarative representation of a grid's data from the given
  3957. * element and stores it in the given {@link DeclarativeValueProvider}s.
  3958. * Each member in the list of value providers corresponds to a column in the
  3959. * grid.
  3960. *
  3961. * @since 8.1
  3962. *
  3963. * @param body
  3964. * the element to read data from
  3965. * @param providers
  3966. * list of {@link DeclarativeValueProvider}s to store the data of
  3967. * each column to
  3968. */
  3969. protected void readData(Element body,
  3970. List<DeclarativeValueProvider<T>> providers) {
  3971. getSelectionModel().deselectAll();
  3972. List<T> items = new ArrayList<>();
  3973. List<T> selectedItems = new ArrayList<>();
  3974. for (Element row : body.children()) {
  3975. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  3976. items.add(item);
  3977. if (row.hasAttr("selected")) {
  3978. selectedItems.add(item);
  3979. }
  3980. Elements cells = row.children();
  3981. int i = 0;
  3982. for (Element cell : cells) {
  3983. providers.get(i).addValue(item, cell.html());
  3984. i++;
  3985. }
  3986. }
  3987. setItems(items);
  3988. selectedItems.forEach(getSelectionModel()::select);
  3989. }
  3990. private void writeStructure(Element design, DesignContext designContext) {
  3991. if (getColumns().isEmpty()) {
  3992. return;
  3993. }
  3994. Element tableElement = design.appendElement("table");
  3995. Element colGroup = tableElement.appendElement("colgroup");
  3996. getColumns().forEach(column -> column
  3997. .writeDesign(colGroup.appendElement("col"), designContext));
  3998. // Always write thead. Reads correctly when there no header rows
  3999. getHeader().writeDesign(tableElement.appendElement("thead"),
  4000. designContext);
  4001. if (designContext.shouldWriteData(this)) {
  4002. Element bodyElement = tableElement.appendElement("tbody");
  4003. writeData(bodyElement, designContext);
  4004. }
  4005. if (getFooter().getRowCount() > 0) {
  4006. getFooter().writeDesign(tableElement.appendElement("tfoot"),
  4007. designContext);
  4008. }
  4009. }
  4010. /**
  4011. * Writes the data contained in this grid. Used when serializing a grid to
  4012. * its declarative representation, if
  4013. * {@link DesignContext#shouldWriteData(Component)} returns {@code true} for
  4014. * the grid that is being written.
  4015. *
  4016. * @since 8.1
  4017. *
  4018. * @param body
  4019. * the body element to write the declarative representation of
  4020. * data to
  4021. * @param designContext
  4022. * the design context
  4023. *
  4024. * @since 8.1
  4025. */
  4026. protected void writeData(Element body, DesignContext designContext) {
  4027. getDataProvider().fetch(new Query<>())
  4028. .forEach(item -> writeRow(body, item, designContext));
  4029. }
  4030. private void writeRow(Element container, T item, DesignContext context) {
  4031. Element tableRow = container.appendElement("tr");
  4032. tableRow.attr("item", serializeDeclarativeRepresentation(item));
  4033. if (getSelectionModel().isSelected(item)) {
  4034. tableRow.attr("selected", "");
  4035. }
  4036. for (Column<T, ?> column : getColumns()) {
  4037. Object value = column.valueProvider.apply(item);
  4038. tableRow.appendElement("td")
  4039. .append(Optional.ofNullable(value).map(Object::toString)
  4040. .map(DesignFormatter::encodeForTextNode)
  4041. .orElse(""));
  4042. }
  4043. }
  4044. private SelectionMode getSelectionMode() {
  4045. GridSelectionModel<T> selectionModel = getSelectionModel();
  4046. SelectionMode mode = null;
  4047. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  4048. mode = SelectionMode.SINGLE;
  4049. } else if (selectionModel.getClass()
  4050. .equals(MultiSelectionModelImpl.class)) {
  4051. mode = SelectionMode.MULTI;
  4052. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  4053. mode = SelectionMode.NONE;
  4054. }
  4055. return mode;
  4056. }
  4057. /**
  4058. * Sets a user-defined identifier for given column.
  4059. *
  4060. * @see Column#setId(String)
  4061. *
  4062. * @param column
  4063. * the column
  4064. * @param id
  4065. * the user-defined identifier
  4066. */
  4067. protected void setColumnId(String id, Column<T, ?> column) {
  4068. if (columnIds.containsKey(id)) {
  4069. throw new IllegalArgumentException("Duplicate ID for columns");
  4070. }
  4071. columnIds.put(id, column);
  4072. }
  4073. @Override
  4074. protected Collection<String> getCustomAttributes() {
  4075. Collection<String> result = super.getCustomAttributes();
  4076. // "rename" for frozen column count
  4077. result.add("frozen-column-count");
  4078. result.add("frozen-columns");
  4079. // "rename" for height-mode
  4080. result.add("height-by-rows");
  4081. result.add("rows");
  4082. // add a selection-mode attribute
  4083. result.add("selection-mode");
  4084. return result;
  4085. }
  4086. /**
  4087. * Returns a column identified by its internal id. This id should not be
  4088. * confused with the user-defined identifier.
  4089. *
  4090. * @param columnId
  4091. * the internal id of column
  4092. * @return column identified by internal id
  4093. */
  4094. protected Column<T, ?> getColumnByInternalId(String columnId) {
  4095. return columnKeys.get(columnId);
  4096. }
  4097. /**
  4098. * Returns the internal id for given column. This id should not be confused
  4099. * with the user-defined identifier.
  4100. *
  4101. * @param column
  4102. * the column
  4103. * @return internal id of given column
  4104. */
  4105. protected String getInternalIdForColumn(Column<T, ?> column) {
  4106. return column.getInternalId();
  4107. }
  4108. private void setSortOrder(List<GridSortOrder<T>> order,
  4109. boolean userOriginated) {
  4110. Objects.requireNonNull(order, "Sort order list cannot be null");
  4111. // Update client state to display sort order.
  4112. List<String> sortColumns = new ArrayList<>();
  4113. List<SortDirection> directions = new ArrayList<>();
  4114. order.stream().forEach(sortOrder -> {
  4115. sortColumns.add(sortOrder.getSorted().getInternalId());
  4116. directions.add(sortOrder.getDirection());
  4117. });
  4118. getState().sortColumns = sortColumns.toArray(new String[0]);
  4119. getState().sortDirs = directions.toArray(new SortDirection[0]);
  4120. sortOrder.clear();
  4121. if (order.isEmpty()) {
  4122. // Grid is not sorted anymore.
  4123. getDataCommunicator().setBackEndSorting(Collections.emptyList());
  4124. getDataCommunicator().setInMemorySorting(null);
  4125. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  4126. userOriginated));
  4127. return;
  4128. }
  4129. sortOrder.addAll(order);
  4130. sort(userOriginated);
  4131. }
  4132. private void sort(boolean userOriginated) {
  4133. // Set sort orders
  4134. // In-memory comparator
  4135. getDataCommunicator().setInMemorySorting(createSortingComparator());
  4136. // Back-end sort properties
  4137. List<QuerySortOrder> sortProperties = new ArrayList<>();
  4138. sortOrder.stream().map(
  4139. order -> order.getSorted().getSortOrder(order.getDirection()))
  4140. .forEach(s -> s.forEach(sortProperties::add));
  4141. getDataCommunicator().setBackEndSorting(sortProperties);
  4142. // Close grid editor if it's open.
  4143. if (getEditor().isOpen()) {
  4144. getEditor().cancel();
  4145. }
  4146. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  4147. userOriginated));
  4148. }
  4149. /**
  4150. * Creates a comparator for grid to sort rows.
  4151. *
  4152. * @return the comparator based on column sorting information.
  4153. */
  4154. protected SerializableComparator<T> createSortingComparator() {
  4155. BinaryOperator<SerializableComparator<T>> operator = (comparator1,
  4156. comparator2) -> {
  4157. /*
  4158. * thenComparing is defined to return a serializable comparator as
  4159. * long as both original comparators are also serializable
  4160. */
  4161. return comparator1.thenComparing(comparator2)::compare;
  4162. };
  4163. return sortOrder.stream().map(
  4164. order -> order.getSorted().getComparator(order.getDirection()))
  4165. .reduce((x, y) -> 0, operator);
  4166. }
  4167. }