Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Grid.java 152KB

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