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

Grid.java 120KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502
  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.stream.Collectors;
  37. import java.util.stream.Stream;
  38. import org.jsoup.nodes.Attributes;
  39. import org.jsoup.nodes.Element;
  40. import org.jsoup.select.Elements;
  41. import com.vaadin.data.BeanPropertySet;
  42. import com.vaadin.data.Binder;
  43. import com.vaadin.data.Binder.Binding;
  44. import com.vaadin.data.HasDataProvider;
  45. import com.vaadin.data.HasValue;
  46. import com.vaadin.data.PropertyDefinition;
  47. import com.vaadin.data.PropertySet;
  48. import com.vaadin.data.ValueProvider;
  49. import com.vaadin.data.provider.DataCommunicator;
  50. import com.vaadin.data.provider.DataProvider;
  51. import com.vaadin.data.provider.GridSortOrder;
  52. import com.vaadin.data.provider.GridSortOrderBuilder;
  53. import com.vaadin.data.provider.Query;
  54. import com.vaadin.data.provider.QuerySortOrder;
  55. import com.vaadin.event.ConnectorEvent;
  56. import com.vaadin.event.ContextClickEvent;
  57. import com.vaadin.event.SortEvent;
  58. import com.vaadin.event.SortEvent.SortListener;
  59. import com.vaadin.event.SortEvent.SortNotifier;
  60. import com.vaadin.event.selection.MultiSelectionListener;
  61. import com.vaadin.event.selection.SelectionListener;
  62. import com.vaadin.event.selection.SingleSelectionListener;
  63. import com.vaadin.server.EncodeResult;
  64. import com.vaadin.server.Extension;
  65. import com.vaadin.server.JsonCodec;
  66. import com.vaadin.server.SerializableComparator;
  67. import com.vaadin.server.SerializableFunction;
  68. import com.vaadin.server.Setter;
  69. import com.vaadin.shared.MouseEventDetails;
  70. import com.vaadin.shared.Registration;
  71. import com.vaadin.shared.data.DataCommunicatorConstants;
  72. import com.vaadin.shared.data.sort.SortDirection;
  73. import com.vaadin.shared.ui.grid.AbstractGridExtensionState;
  74. import com.vaadin.shared.ui.grid.ColumnResizeMode;
  75. import com.vaadin.shared.ui.grid.ColumnState;
  76. import com.vaadin.shared.ui.grid.DetailsManagerState;
  77. import com.vaadin.shared.ui.grid.GridConstants;
  78. import com.vaadin.shared.ui.grid.GridConstants.Section;
  79. import com.vaadin.shared.ui.grid.GridServerRpc;
  80. import com.vaadin.shared.ui.grid.GridState;
  81. import com.vaadin.shared.ui.grid.GridStaticCellType;
  82. import com.vaadin.shared.ui.grid.HeightMode;
  83. import com.vaadin.shared.ui.grid.SectionState;
  84. import com.vaadin.ui.components.grid.ColumnReorderListener;
  85. import com.vaadin.ui.components.grid.ColumnResizeListener;
  86. import com.vaadin.ui.components.grid.ColumnVisibilityChangeListener;
  87. import com.vaadin.ui.components.grid.DescriptionGenerator;
  88. import com.vaadin.ui.components.grid.DetailsGenerator;
  89. import com.vaadin.ui.components.grid.Editor;
  90. import com.vaadin.ui.components.grid.EditorImpl;
  91. import com.vaadin.ui.components.grid.Footer;
  92. import com.vaadin.ui.components.grid.FooterCell;
  93. import com.vaadin.ui.components.grid.FooterRow;
  94. import com.vaadin.ui.components.grid.GridSelectionModel;
  95. import com.vaadin.ui.components.grid.Header;
  96. import com.vaadin.ui.components.grid.Header.Row;
  97. import com.vaadin.ui.components.grid.HeaderCell;
  98. import com.vaadin.ui.components.grid.HeaderRow;
  99. import com.vaadin.ui.components.grid.ItemClickListener;
  100. import com.vaadin.ui.components.grid.MultiSelectionModel;
  101. import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
  102. import com.vaadin.ui.components.grid.NoSelectionModel;
  103. import com.vaadin.ui.components.grid.SingleSelectionModel;
  104. import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
  105. import com.vaadin.ui.components.grid.SortOrderProvider;
  106. import com.vaadin.ui.declarative.DesignAttributeHandler;
  107. import com.vaadin.ui.declarative.DesignContext;
  108. import com.vaadin.ui.declarative.DesignException;
  109. import com.vaadin.ui.declarative.DesignFormatter;
  110. import com.vaadin.ui.renderers.AbstractRenderer;
  111. import com.vaadin.ui.renderers.HtmlRenderer;
  112. import com.vaadin.ui.renderers.Renderer;
  113. import com.vaadin.ui.renderers.TextRenderer;
  114. import com.vaadin.util.ReflectTools;
  115. import elemental.json.Json;
  116. import elemental.json.JsonObject;
  117. import elemental.json.JsonValue;
  118. /**
  119. * A grid component for displaying tabular data.
  120. *
  121. * @author Vaadin Ltd
  122. * @since 8.0
  123. *
  124. * @param <T>
  125. * the grid bean type
  126. */
  127. public class Grid<T> extends AbstractListing<T> implements HasComponents,
  128. HasDataProvider<T>, SortNotifier<GridSortOrder<T>> {
  129. @Deprecated
  130. private static final Method COLUMN_REORDER_METHOD = ReflectTools.findMethod(
  131. ColumnReorderListener.class, "columnReorder",
  132. ColumnReorderEvent.class);
  133. private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
  134. .findMethod(SortListener.class, "sort", SortEvent.class);
  135. @Deprecated
  136. private static final Method COLUMN_RESIZE_METHOD = ReflectTools.findMethod(
  137. ColumnResizeListener.class, "columnResize",
  138. ColumnResizeEvent.class);
  139. @Deprecated
  140. private static final Method ITEM_CLICK_METHOD = ReflectTools
  141. .findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
  142. @Deprecated
  143. private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
  144. .findMethod(ColumnVisibilityChangeListener.class,
  145. "columnVisibilityChanged",
  146. ColumnVisibilityChangeEvent.class);
  147. /**
  148. * Selection mode representing the built-in selection models in grid.
  149. * <p>
  150. * These enums can be used in {@link Grid#setSelectionMode(SelectionMode)}
  151. * to easily switch between the build-in selection models.
  152. *
  153. * @see Grid#setSelectionMode(SelectionMode)
  154. * @see Grid#setSelectionModel(GridSelectionModel)
  155. */
  156. public enum SelectionMode {
  157. /**
  158. * Single selection mode that maps to build-in
  159. * {@link SingleSelectionModel}.
  160. *
  161. * @see SingleSelectionModelImpl
  162. */
  163. SINGLE {
  164. @Override
  165. protected <T> GridSelectionModel<T> createModel() {
  166. return new SingleSelectionModelImpl<>();
  167. }
  168. },
  169. /**
  170. * Multiselection mode that maps to build-in {@link MultiSelectionModel}
  171. * .
  172. *
  173. * @see MultiSelectionModelImpl
  174. */
  175. MULTI {
  176. @Override
  177. protected <T> GridSelectionModel<T> createModel() {
  178. return new MultiSelectionModelImpl<>();
  179. }
  180. },
  181. /**
  182. * Selection model that doesn't allow selection.
  183. *
  184. * @see NoSelectionModel
  185. */
  186. NONE {
  187. @Override
  188. protected <T> GridSelectionModel<T> createModel() {
  189. return new NoSelectionModel<>();
  190. }
  191. };
  192. /**
  193. * Creates the selection model to use with this enum.
  194. *
  195. * @param <T>
  196. * the type of items in the grid
  197. * @return the selection model
  198. */
  199. protected abstract <T> GridSelectionModel<T> createModel();
  200. }
  201. /**
  202. * An event that is fired when the columns are reordered.
  203. */
  204. public static class ColumnReorderEvent extends Component.Event {
  205. private final boolean userOriginated;
  206. /**
  207. *
  208. * @param source
  209. * the grid where the event originated from
  210. * @param userOriginated
  211. * <code>true</code> if event is a result of user
  212. * interaction, <code>false</code> if from API call
  213. */
  214. public ColumnReorderEvent(Grid source, boolean userOriginated) {
  215. super(source);
  216. this.userOriginated = userOriginated;
  217. }
  218. /**
  219. * Returns <code>true</code> if the column reorder was done by the user,
  220. * <code>false</code> if not and it was triggered by server side code.
  221. *
  222. * @return <code>true</code> if event is a result of user interaction
  223. */
  224. public boolean isUserOriginated() {
  225. return userOriginated;
  226. }
  227. }
  228. /**
  229. * An event that is fired when a column is resized, either programmatically
  230. * or by the user.
  231. */
  232. public static class ColumnResizeEvent extends Component.Event {
  233. private final Column<?, ?> column;
  234. private final boolean userOriginated;
  235. /**
  236. *
  237. * @param source
  238. * the grid where the event originated from
  239. * @param userOriginated
  240. * <code>true</code> if event is a result of user
  241. * interaction, <code>false</code> if from API call
  242. */
  243. public ColumnResizeEvent(Grid<?> source, Column<?, ?> column,
  244. boolean userOriginated) {
  245. super(source);
  246. this.column = column;
  247. this.userOriginated = userOriginated;
  248. }
  249. /**
  250. * Returns the column that was resized.
  251. *
  252. * @return the resized column.
  253. */
  254. public Column<?, ?> getColumn() {
  255. return column;
  256. }
  257. /**
  258. * Returns <code>true</code> if the column resize 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. public boolean isUserOriginated() {
  264. return userOriginated;
  265. }
  266. }
  267. /**
  268. * An event fired when an item in the Grid has been clicked.
  269. *
  270. * @param <T>
  271. * the grid bean type
  272. */
  273. public static class ItemClick<T> extends ConnectorEvent {
  274. private final T item;
  275. private final Column<T, ?> column;
  276. private final MouseEventDetails mouseEventDetails;
  277. /**
  278. * Creates a new {@code ItemClick} event containing the given item and
  279. * Column originating from the given Grid.
  280. *
  281. */
  282. public ItemClick(Grid<T> source, Column<T, ?> column, T item,
  283. MouseEventDetails mouseEventDetails) {
  284. super(source);
  285. this.column = column;
  286. this.item = item;
  287. this.mouseEventDetails = mouseEventDetails;
  288. }
  289. /**
  290. * Returns the clicked item.
  291. *
  292. * @return the clicked item
  293. */
  294. public T getItem() {
  295. return item;
  296. }
  297. /**
  298. * Returns the clicked column.
  299. *
  300. * @return the clicked column
  301. */
  302. public Column<T, ?> getColumn() {
  303. return column;
  304. }
  305. /**
  306. * Returns the source Grid.
  307. *
  308. * @return the grid
  309. */
  310. @Override
  311. public Grid<T> getSource() {
  312. return (Grid<T>) super.getSource();
  313. }
  314. /**
  315. * Returns the mouse event details.
  316. *
  317. * @return the mouse event details
  318. */
  319. public MouseEventDetails getMouseEventDetails() {
  320. return mouseEventDetails;
  321. }
  322. }
  323. /**
  324. * ContextClickEvent for the Grid Component.
  325. *
  326. * @param <T>
  327. * the grid bean type
  328. */
  329. public static class GridContextClickEvent<T> extends ContextClickEvent {
  330. private final T item;
  331. private final int rowIndex;
  332. private final Column<?, ?> column;
  333. private final Section section;
  334. /**
  335. * Creates a new context click event.
  336. *
  337. * @param source
  338. * the grid where the context click occurred
  339. * @param mouseEventDetails
  340. * details about mouse position
  341. * @param section
  342. * the section of the grid which was clicked
  343. * @param rowIndex
  344. * the index of the row which was clicked
  345. * @param item
  346. * the item which was clicked
  347. * @param column
  348. * the column which was clicked
  349. */
  350. public GridContextClickEvent(Grid<T> source,
  351. MouseEventDetails mouseEventDetails, Section section,
  352. int rowIndex, T item, Column<?, ?> column) {
  353. super(source, mouseEventDetails);
  354. this.item = item;
  355. this.section = section;
  356. this.column = column;
  357. this.rowIndex = rowIndex;
  358. }
  359. /**
  360. * Returns the item of context clicked row.
  361. *
  362. * @return item of clicked row; <code>null</code> if header or footer
  363. */
  364. public T getItem() {
  365. return item;
  366. }
  367. /**
  368. * Returns the clicked column.
  369. *
  370. * @return the clicked column
  371. */
  372. public Column<?, ?> getColumn() {
  373. return column;
  374. }
  375. /**
  376. * Return the clicked section of Grid.
  377. *
  378. * @return section of grid
  379. */
  380. public Section getSection() {
  381. return section;
  382. }
  383. /**
  384. * Returns the clicked row index.
  385. * <p>
  386. * Header and Footer rows for index can be fetched with
  387. * {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
  388. *
  389. * @return row index in section
  390. */
  391. public int getRowIndex() {
  392. return rowIndex;
  393. }
  394. @Override
  395. public Grid<T> getComponent() {
  396. return (Grid<T>) super.getComponent();
  397. }
  398. }
  399. /**
  400. * An event that is fired when a column's visibility changes.
  401. *
  402. * @since 7.5.0
  403. */
  404. public static class ColumnVisibilityChangeEvent extends Component.Event {
  405. private final Column<?, ?> column;
  406. private final boolean userOriginated;
  407. private final boolean hidden;
  408. /**
  409. * Constructor for a column visibility change event.
  410. *
  411. * @param source
  412. * the grid from which this event originates
  413. * @param column
  414. * the column that changed its visibility
  415. * @param hidden
  416. * <code>true</code> if the column was hidden,
  417. * <code>false</code> if it became visible
  418. * @param isUserOriginated
  419. * <code>true</code> iff the event was triggered by an UI
  420. * interaction
  421. */
  422. public ColumnVisibilityChangeEvent(Grid<?> source, Column<?, ?> column,
  423. boolean hidden, boolean isUserOriginated) {
  424. super(source);
  425. this.column = column;
  426. this.hidden = hidden;
  427. userOriginated = isUserOriginated;
  428. }
  429. /**
  430. * Gets the column that became hidden or visible.
  431. *
  432. * @return the column that became hidden or visible.
  433. * @see Column#isHidden()
  434. */
  435. public Column<?, ?> getColumn() {
  436. return column;
  437. }
  438. /**
  439. * Was the column set hidden or visible.
  440. *
  441. * @return <code>true</code> if the column was hidden <code>false</code>
  442. * if it was set visible
  443. */
  444. public boolean isHidden() {
  445. return hidden;
  446. }
  447. /**
  448. * Returns <code>true</code> if the column reorder was done by the user,
  449. * <code>false</code> if not and it was triggered by server side code.
  450. *
  451. * @return <code>true</code> if event is a result of user interaction
  452. */
  453. public boolean isUserOriginated() {
  454. return userOriginated;
  455. }
  456. }
  457. /**
  458. * A helper base class for creating extensions for the Grid component.
  459. *
  460. * @param <T>
  461. */
  462. public abstract static class AbstractGridExtension<T>
  463. extends AbstractListingExtension<T> {
  464. @Override
  465. public void extend(AbstractListing<T> grid) {
  466. if (!(grid instanceof Grid)) {
  467. throw new IllegalArgumentException(
  468. getClass().getSimpleName() + " can only extend Grid");
  469. }
  470. super.extend(grid);
  471. }
  472. /**
  473. * Adds given component to the connector hierarchy of Grid.
  474. *
  475. * @param c
  476. * the component to add
  477. */
  478. protected void addComponentToGrid(Component c) {
  479. getParent().addExtensionComponent(c);
  480. }
  481. /**
  482. * Removes given component from the connector hierarchy of Grid.
  483. *
  484. * @param c
  485. * the component to remove
  486. */
  487. protected void removeComponentFromGrid(Component c) {
  488. getParent().removeExtensionComponent(c);
  489. }
  490. @Override
  491. public Grid<T> getParent() {
  492. return (Grid<T>) super.getParent();
  493. }
  494. @Override
  495. protected AbstractGridExtensionState getState() {
  496. return (AbstractGridExtensionState) super.getState();
  497. }
  498. @Override
  499. protected AbstractGridExtensionState getState(boolean markAsDirty) {
  500. return (AbstractGridExtensionState) super.getState(markAsDirty);
  501. }
  502. protected String getInternalIdForColumn(Column<T, ?> column) {
  503. return getParent().getInternalIdForColumn(column);
  504. }
  505. }
  506. private final class GridServerRpcImpl implements GridServerRpc {
  507. @Override
  508. public void sort(String[] columnInternalIds, SortDirection[] directions,
  509. boolean isUserOriginated) {
  510. assert columnInternalIds.length == directions.length : "Column and sort direction counts don't match.";
  511. List<GridSortOrder<T>> list = new ArrayList<>(directions.length);
  512. for (int i = 0; i < columnInternalIds.length; ++i) {
  513. Column<T, ?> column = columnKeys.get(columnInternalIds[i]);
  514. list.add(new GridSortOrder<>(column, directions[i]));
  515. }
  516. setSortOrder(list, isUserOriginated);
  517. }
  518. @Override
  519. public void itemClick(String rowKey, String columnInternalId,
  520. MouseEventDetails details) {
  521. Column<T, ?> column = getColumnByInternalId(columnInternalId);
  522. T item = getDataCommunicator().getKeyMapper().get(rowKey);
  523. fireEvent(new ItemClick<>(Grid.this, column, item, details));
  524. }
  525. @Override
  526. public void contextClick(int rowIndex, String rowKey,
  527. String columnInternalId, Section section,
  528. MouseEventDetails details) {
  529. T item = null;
  530. if (rowKey != null) {
  531. item = getDataCommunicator().getKeyMapper().get(rowKey);
  532. }
  533. fireEvent(new GridContextClickEvent<>(Grid.this, details, section,
  534. rowIndex, item, getColumnByInternalId(columnInternalId)));
  535. }
  536. @Override
  537. public void columnsReordered(List<String> newColumnOrder,
  538. List<String> oldColumnOrder) {
  539. final String diffStateKey = "columnOrder";
  540. ConnectorTracker connectorTracker = getUI().getConnectorTracker();
  541. JsonObject diffState = connectorTracker.getDiffState(Grid.this);
  542. // discard the change if the columns have been reordered from
  543. // the server side, as the server side is always right
  544. if (getState(false).columnOrder.equals(oldColumnOrder)) {
  545. // Don't mark as dirty since client has the state already
  546. getState(false).columnOrder = newColumnOrder;
  547. // write changes to diffState so that possible reverting the
  548. // column order is sent to client
  549. assert diffState
  550. .hasKey(diffStateKey) : "Field name has changed";
  551. Type type = null;
  552. try {
  553. type = getState(false).getClass()
  554. .getDeclaredField(diffStateKey).getGenericType();
  555. } catch (NoSuchFieldException | SecurityException e) {
  556. e.printStackTrace();
  557. }
  558. EncodeResult encodeResult = JsonCodec.encode(
  559. getState(false).columnOrder, diffState, type,
  560. connectorTracker);
  561. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  562. fireColumnReorderEvent(true);
  563. } else {
  564. // make sure the client is reverted to the order that the
  565. // server thinks it is
  566. diffState.remove(diffStateKey);
  567. markAsDirty();
  568. }
  569. }
  570. @Override
  571. public void columnVisibilityChanged(String internalId, boolean hidden) {
  572. Column<T, ?> column = getColumnByInternalId(internalId);
  573. ColumnState columnState = column.getState(false);
  574. if (columnState.hidden != hidden) {
  575. columnState.hidden = hidden;
  576. fireColumnVisibilityChangeEvent(column, hidden, true);
  577. }
  578. }
  579. @Override
  580. public void columnResized(String internalId, double pixels) {
  581. final Column<T, ?> column = getColumnByInternalId(internalId);
  582. if (column != null && column.isResizable()) {
  583. column.getState().width = pixels;
  584. fireColumnResizeEvent(column, true);
  585. }
  586. }
  587. }
  588. /**
  589. * Class for managing visible details rows.
  590. *
  591. * @param <T>
  592. * the grid bean type
  593. */
  594. public static class DetailsManager<T> extends AbstractGridExtension<T> {
  595. private final Set<T> visibleDetails = new HashSet<>();
  596. private final Map<T, Component> components = new HashMap<>();
  597. private DetailsGenerator<T> generator;
  598. /**
  599. * Sets the details component generator.
  600. *
  601. * @param generator
  602. * the generator for details components
  603. */
  604. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  605. if (this.generator != generator) {
  606. removeAllComponents();
  607. }
  608. this.generator = generator;
  609. visibleDetails.forEach(this::refresh);
  610. }
  611. @Override
  612. public void remove() {
  613. removeAllComponents();
  614. super.remove();
  615. }
  616. private void removeAllComponents() {
  617. // Clean up old components
  618. components.values().forEach(this::removeComponentFromGrid);
  619. components.clear();
  620. }
  621. @Override
  622. public void generateData(T data, JsonObject jsonObject) {
  623. if (generator == null || !visibleDetails.contains(data)) {
  624. return;
  625. }
  626. if (!components.containsKey(data)) {
  627. Component detailsComponent = generator.apply(data);
  628. Objects.requireNonNull(detailsComponent,
  629. "Details generator can't create null components");
  630. if (detailsComponent.getParent() != null) {
  631. throw new IllegalStateException(
  632. "Details component was already attached");
  633. }
  634. addComponentToGrid(detailsComponent);
  635. components.put(data, detailsComponent);
  636. }
  637. jsonObject.put(GridState.JSONKEY_DETAILS_VISIBLE,
  638. components.get(data).getConnectorId());
  639. }
  640. @Override
  641. public void destroyData(T data) {
  642. // No clean up needed. Components are removed when hiding details
  643. // and/or changing details generator
  644. }
  645. /**
  646. * Sets the visibility of details component for given item.
  647. *
  648. * @param data
  649. * the item to show details for
  650. * @param visible
  651. * {@code true} if details component should be visible;
  652. * {@code false} if it should be hidden
  653. */
  654. public void setDetailsVisible(T data, boolean visible) {
  655. boolean refresh = false;
  656. if (!visible) {
  657. refresh = visibleDetails.remove(data);
  658. if (components.containsKey(data)) {
  659. removeComponentFromGrid(components.remove(data));
  660. }
  661. } else {
  662. refresh = visibleDetails.add(data);
  663. }
  664. if (refresh) {
  665. refresh(data);
  666. }
  667. }
  668. /**
  669. * Returns the visibility of details component for given item.
  670. *
  671. * @param data
  672. * the item to show details for
  673. *
  674. * @return {@code true} if details component should be visible;
  675. * {@code false} if it should be hidden
  676. */
  677. public boolean isDetailsVisible(T data) {
  678. return visibleDetails.contains(data);
  679. }
  680. @Override
  681. public Grid<T> getParent() {
  682. return super.getParent();
  683. }
  684. @Override
  685. protected DetailsManagerState getState() {
  686. return (DetailsManagerState) super.getState();
  687. }
  688. @Override
  689. protected DetailsManagerState getState(boolean markAsDirty) {
  690. return (DetailsManagerState) super.getState(markAsDirty);
  691. }
  692. }
  693. /**
  694. * This extension manages the configuration and data communication for a
  695. * Column inside of a Grid component.
  696. *
  697. * @param <T>
  698. * the grid bean type
  699. * @param <V>
  700. * the column value type
  701. */
  702. public static class Column<T, V> extends AbstractGridExtension<T> {
  703. private final SerializableFunction<T, ? extends V> valueProvider;
  704. private SortOrderProvider sortOrderProvider;
  705. private SerializableComparator<T> comparator;
  706. private StyleGenerator<T> styleGenerator = item -> null;
  707. private DescriptionGenerator<T> descriptionGenerator;
  708. private Binding<T, ?> editorBinding;
  709. private String userId;
  710. /**
  711. * Constructs a new Column configuration with given renderer and value
  712. * provider.
  713. *
  714. * @param valueProvider
  715. * the function to get values from items, not
  716. * <code>null</code>
  717. * @param renderer
  718. * the type of value, not <code>null</code>
  719. */
  720. protected Column(ValueProvider<T, ? extends V> valueProvider,
  721. Renderer<V> renderer) {
  722. Objects.requireNonNull(valueProvider,
  723. "Value provider can't be null");
  724. Objects.requireNonNull(renderer, "Renderer can't be null");
  725. ColumnState state = getState();
  726. this.valueProvider = valueProvider;
  727. state.renderer = renderer;
  728. state.caption = "";
  729. sortOrderProvider = d -> Stream.of();
  730. // Add the renderer as a child extension of this extension, thus
  731. // ensuring the renderer will be unregistered when this column is
  732. // removed
  733. addExtension(renderer);
  734. Class<V> valueType = renderer.getPresentationType();
  735. if (Comparable.class.isAssignableFrom(valueType)) {
  736. comparator = (a, b) -> compareComparables(
  737. valueProvider.apply(a), valueProvider.apply(b));
  738. state.sortable = true;
  739. } else if (Number.class.isAssignableFrom(valueType)) {
  740. /*
  741. * Value type will be Number whenever using NumberRenderer.
  742. * Provide explicit comparison support in this case even though
  743. * Number itself isn't Comparable.
  744. */
  745. comparator = (a, b) -> compareNumbers(
  746. (Number) valueProvider.apply(a),
  747. (Number) valueProvider.apply(b));
  748. state.sortable = true;
  749. } else {
  750. state.sortable = false;
  751. }
  752. }
  753. @SuppressWarnings("unchecked")
  754. private static int compareComparables(Object a, Object b) {
  755. return ((Comparator) Comparator
  756. .nullsLast(Comparator.naturalOrder())).compare(a, b);
  757. }
  758. @SuppressWarnings("unchecked")
  759. private static int compareNumbers(Number a, Number b) {
  760. Number valueA = a != null ? a : Double.POSITIVE_INFINITY;
  761. Number valueB = b != null ? b : Double.POSITIVE_INFINITY;
  762. // Most Number implementations are Comparable
  763. if (valueA instanceof Comparable
  764. && valueA.getClass().isInstance(valueB)) {
  765. return ((Comparable<Number>) valueA).compareTo(valueB);
  766. } else if (valueA.equals(valueB)) {
  767. return 0;
  768. } else {
  769. // Fall back to comparing based on potentially truncated values
  770. int compare = Long.compare(valueA.longValue(),
  771. valueB.longValue());
  772. if (compare == 0) {
  773. // This might still produce 0 even though the values are not
  774. // equals, but there's nothing more we can do about that
  775. compare = Double.compare(valueA.doubleValue(),
  776. valueB.doubleValue());
  777. }
  778. return compare;
  779. }
  780. }
  781. @Override
  782. public void generateData(T data, JsonObject jsonObject) {
  783. ColumnState state = getState(false);
  784. String communicationId = getConnectorId();
  785. assert communicationId != null : "No communication ID set for column "
  786. + state.caption;
  787. @SuppressWarnings("unchecked")
  788. Renderer<V> renderer = (Renderer<V>) state.renderer;
  789. JsonObject obj = getDataObject(jsonObject,
  790. DataCommunicatorConstants.DATA);
  791. V providerValue = valueProvider.apply(data);
  792. JsonValue rendererValue = renderer.encode(providerValue);
  793. obj.put(communicationId, rendererValue);
  794. String style = styleGenerator.apply(data);
  795. if (style != null && !style.isEmpty()) {
  796. JsonObject styleObj = getDataObject(jsonObject,
  797. GridState.JSONKEY_CELLSTYLES);
  798. styleObj.put(communicationId, style);
  799. }
  800. if (descriptionGenerator != null) {
  801. String description = descriptionGenerator.apply(data);
  802. if (description != null && !description.isEmpty()) {
  803. JsonObject descriptionObj = getDataObject(jsonObject,
  804. GridState.JSONKEY_CELLDESCRIPTION);
  805. descriptionObj.put(communicationId, description);
  806. }
  807. }
  808. }
  809. /**
  810. * Gets a data object with the given key from the given JsonObject. If
  811. * there is no object with the key, this method creates a new
  812. * JsonObject.
  813. *
  814. * @param jsonObject
  815. * the json object
  816. * @param key
  817. * the key where the desired data object is stored
  818. * @return data object for the given key
  819. */
  820. private JsonObject getDataObject(JsonObject jsonObject, String key) {
  821. if (!jsonObject.hasKey(key)) {
  822. jsonObject.put(key, Json.createObject());
  823. }
  824. return jsonObject.getObject(key);
  825. }
  826. @Override
  827. protected ColumnState getState() {
  828. return getState(true);
  829. }
  830. @Override
  831. protected ColumnState getState(boolean markAsDirty) {
  832. return (ColumnState) super.getState(markAsDirty);
  833. }
  834. /**
  835. * This method extends the given Grid with this Column.
  836. *
  837. * @param grid
  838. * the grid to extend
  839. */
  840. private void extend(Grid<T> grid) {
  841. super.extend(grid);
  842. }
  843. /**
  844. * Returns the identifier used with this Column in communication.
  845. *
  846. * @return the identifier string
  847. */
  848. private String getInternalId() {
  849. return getState(false).internalId;
  850. }
  851. /**
  852. * Sets the identifier to use with this Column in communication.
  853. *
  854. * @param id
  855. * the identifier string
  856. */
  857. private void setInternalId(String id) {
  858. Objects.requireNonNull(id, "Communication ID can't be null");
  859. getState().internalId = id;
  860. }
  861. /**
  862. * Returns the user-defined identifier for this column.
  863. *
  864. * @return the identifier string
  865. */
  866. public String getId() {
  867. return userId;
  868. }
  869. /**
  870. * Sets the user-defined identifier to map this column. The identifier
  871. * can be used for example in {@link Grid#getColumn(String)}.
  872. *
  873. * @param id
  874. * the identifier string
  875. */
  876. public Column<T, V> setId(String id) {
  877. Objects.requireNonNull(id, "Column identifier cannot be null");
  878. if (this.userId != null) {
  879. throw new IllegalStateException(
  880. "Column identifier cannot be changed");
  881. }
  882. this.userId = id;
  883. getGrid().setColumnId(id, this);
  884. return this;
  885. }
  886. /**
  887. * Sets whether the user can sort this column or not.
  888. *
  889. * @param sortable
  890. * {@code true} if the column can be sorted by the user;
  891. * {@code false} if not
  892. * @return this column
  893. */
  894. public Column<T, V> setSortable(boolean sortable) {
  895. getState().sortable = sortable;
  896. return this;
  897. }
  898. /**
  899. * Gets whether the user can sort this column or not.
  900. *
  901. * @return {@code true} if the column can be sorted by the user;
  902. * {@code false} if not
  903. */
  904. public boolean isSortable() {
  905. return getState(false).sortable;
  906. }
  907. /**
  908. * Sets the header caption for this column.
  909. *
  910. * @param caption
  911. * the header caption, not null
  912. *
  913. * @return this column
  914. */
  915. public Column<T, V> setCaption(String caption) {
  916. Objects.requireNonNull(caption, "Header caption can't be null");
  917. getState().caption = caption;
  918. HeaderRow row = getGrid().getDefaultHeaderRow();
  919. if (row != null) {
  920. row.getCell(this).setText(caption);
  921. }
  922. return this;
  923. }
  924. /**
  925. * Gets the header caption for this column.
  926. *
  927. * @return header caption
  928. */
  929. public String getCaption() {
  930. return getState(false).caption;
  931. }
  932. /**
  933. * Sets a comparator to use with in-memory sorting with this column.
  934. * Sorting with a back-end is done using
  935. * {@link Column#setSortProperty(String...)}.
  936. *
  937. * @param comparator
  938. * the comparator to use when sorting data in this column
  939. * @return this column
  940. */
  941. public Column<T, V> setComparator(
  942. SerializableComparator<T> comparator) {
  943. Objects.requireNonNull(comparator, "Comparator can't be null");
  944. this.comparator = comparator;
  945. return this;
  946. }
  947. /**
  948. * Gets the comparator to use with in-memory sorting for this column
  949. * when sorting in the given direction.
  950. *
  951. * @param sortDirection
  952. * the direction this column is sorted by
  953. * @return comparator for this column
  954. */
  955. public SerializableComparator<T> getComparator(
  956. SortDirection sortDirection) {
  957. Objects.requireNonNull(comparator,
  958. "No comparator defined for sorted column.");
  959. boolean reverse = sortDirection != SortDirection.ASCENDING;
  960. return reverse ? (t1, t2) -> comparator.reversed().compare(t1, t2)
  961. : comparator;
  962. }
  963. /**
  964. * Sets strings describing back end properties to be used when sorting
  965. * this column.
  966. *
  967. * @param properties
  968. * the array of strings describing backend properties
  969. * @return this column
  970. */
  971. public Column<T, V> setSortProperty(String... properties) {
  972. Objects.requireNonNull(properties, "Sort properties can't be null");
  973. sortOrderProvider = dir -> Arrays.stream(properties)
  974. .map(s -> new QuerySortOrder(s, dir));
  975. return this;
  976. }
  977. /**
  978. * Sets the sort orders when sorting this column. The sort order
  979. * provider is a function which provides {@link QuerySortOrder} objects
  980. * to describe how to sort by this column.
  981. *
  982. * @param provider
  983. * the function to use when generating sort orders with the
  984. * given direction
  985. * @return this column
  986. */
  987. public Column<T, V> setSortOrderProvider(SortOrderProvider provider) {
  988. Objects.requireNonNull(provider,
  989. "Sort order provider can't be null");
  990. sortOrderProvider = provider;
  991. return this;
  992. }
  993. /**
  994. * Gets the sort orders to use with back-end sorting for this column
  995. * when sorting in the given direction.
  996. *
  997. * @param direction
  998. * the sorting direction
  999. * @return stream of sort orders
  1000. */
  1001. public Stream<QuerySortOrder> getSortOrder(SortDirection direction) {
  1002. return sortOrderProvider.apply(direction);
  1003. }
  1004. /**
  1005. * Sets the style generator that is used for generating class names for
  1006. * cells in this column. Returning null from the generator results in no
  1007. * custom style name being set.
  1008. *
  1009. * @param cellStyleGenerator
  1010. * the cell style generator to set, not null
  1011. * @return this column
  1012. * @throws NullPointerException
  1013. * if {@code cellStyleGenerator} is {@code null}
  1014. */
  1015. public Column<T, V> setStyleGenerator(
  1016. StyleGenerator<T> cellStyleGenerator) {
  1017. Objects.requireNonNull(cellStyleGenerator,
  1018. "Cell style generator must not be null");
  1019. this.styleGenerator = cellStyleGenerator;
  1020. getGrid().getDataCommunicator().reset();
  1021. return this;
  1022. }
  1023. /**
  1024. * Gets the style generator that is used for generating styles for
  1025. * cells.
  1026. *
  1027. * @return the cell style generator
  1028. */
  1029. public StyleGenerator<T> getStyleGenerator() {
  1030. return styleGenerator;
  1031. }
  1032. /**
  1033. * Sets the description generator that is used for generating
  1034. * descriptions for cells in this column.
  1035. *
  1036. * @param cellDescriptionGenerator
  1037. * the cell description generator to set, or
  1038. * <code>null</code> to remove a previously set generator
  1039. * @return this column
  1040. */
  1041. public Column<T, V> setDescriptionGenerator(
  1042. DescriptionGenerator<T> cellDescriptionGenerator) {
  1043. this.descriptionGenerator = cellDescriptionGenerator;
  1044. getGrid().getDataCommunicator().reset();
  1045. return this;
  1046. }
  1047. /**
  1048. * Gets the description generator that is used for generating
  1049. * descriptions for cells.
  1050. *
  1051. * @return the cell description generator, or <code>null</code> if no
  1052. * generator is set
  1053. */
  1054. public DescriptionGenerator<T> getDescriptionGenerator() {
  1055. return descriptionGenerator;
  1056. }
  1057. /**
  1058. * Sets the ratio with which the column expands.
  1059. * <p>
  1060. * By default, all columns expand equally (treated as if all of them had
  1061. * an expand ratio of 1). Once at least one column gets a defined expand
  1062. * ratio, the implicit expand ratio is removed, and only the defined
  1063. * expand ratios are taken into account.
  1064. * <p>
  1065. * If a column has a defined width ({@link #setWidth(double)}), it
  1066. * overrides this method's effects.
  1067. * <p>
  1068. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  1069. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  1070. * as wide as its contents requires</strong>. The column with a ratio of
  1071. * 1 is as wide as it needs, <strong>plus a third of any excess
  1072. * space</strong>, because we have 3 parts total, and this column
  1073. * reserves only one of those. The column with a ratio of 2, is as wide
  1074. * as it needs to be, <strong>plus two thirds</strong> of the excess
  1075. * width.
  1076. *
  1077. * @param expandRatio
  1078. * the expand ratio of this column. {@code 0} to not have it
  1079. * expand at all. A negative number to clear the expand
  1080. * value.
  1081. * @throws IllegalStateException
  1082. * if the column is no longer attached to any grid
  1083. * @see #setWidth(double)
  1084. */
  1085. public Column<T, V> setExpandRatio(int expandRatio)
  1086. throws IllegalStateException {
  1087. checkColumnIsAttached();
  1088. if (expandRatio != getExpandRatio()) {
  1089. getState().expandRatio = expandRatio;
  1090. getGrid().markAsDirty();
  1091. }
  1092. return this;
  1093. }
  1094. /**
  1095. * Returns the column's expand ratio.
  1096. *
  1097. * @return the column's expand ratio
  1098. * @see #setExpandRatio(int)
  1099. */
  1100. public int getExpandRatio() {
  1101. return getState(false).expandRatio;
  1102. }
  1103. /**
  1104. * Clears the expand ratio for this column.
  1105. * <p>
  1106. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  1107. *
  1108. * @throws IllegalStateException
  1109. * if the column is no longer attached to any grid
  1110. */
  1111. public Column<T, V> clearExpandRatio() throws IllegalStateException {
  1112. return setExpandRatio(-1);
  1113. }
  1114. /**
  1115. * Returns the width (in pixels). By default a column is 100px wide.
  1116. *
  1117. * @return the width in pixels of the column
  1118. * @throws IllegalStateException
  1119. * if the column is no longer attached to any grid
  1120. */
  1121. public double getWidth() throws IllegalStateException {
  1122. checkColumnIsAttached();
  1123. return getState(false).width;
  1124. }
  1125. /**
  1126. * Sets the width (in pixels).
  1127. * <p>
  1128. * This overrides any configuration set by any of
  1129. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  1130. * {@link #setMaximumWidth(double)}.
  1131. *
  1132. * @param pixelWidth
  1133. * the new pixel width of the column
  1134. * @return the column itself
  1135. *
  1136. * @throws IllegalStateException
  1137. * if the column is no longer attached to any grid
  1138. * @throws IllegalArgumentException
  1139. * thrown if pixel width is less than zero
  1140. */
  1141. public Column<T, V> setWidth(double pixelWidth)
  1142. throws IllegalStateException, IllegalArgumentException {
  1143. checkColumnIsAttached();
  1144. if (pixelWidth < 0) {
  1145. throw new IllegalArgumentException(
  1146. "Pixel width should be greated than 0 (in " + toString()
  1147. + ")");
  1148. }
  1149. if (pixelWidth != getWidth()) {
  1150. getState().width = pixelWidth;
  1151. getGrid().markAsDirty();
  1152. getGrid().fireColumnResizeEvent(this, false);
  1153. }
  1154. return this;
  1155. }
  1156. /**
  1157. * Returns whether this column has an undefined width.
  1158. *
  1159. * @since 7.6
  1160. * @return whether the width is undefined
  1161. * @throws IllegalStateException
  1162. * if the column is no longer attached to any grid
  1163. */
  1164. public boolean isWidthUndefined() {
  1165. checkColumnIsAttached();
  1166. return getState(false).width < 0;
  1167. }
  1168. /**
  1169. * Marks the column width as undefined. An undefined width means the
  1170. * grid is free to resize the column based on the cell contents and
  1171. * available space in the grid.
  1172. *
  1173. * @return the column itself
  1174. */
  1175. public Column<T, V> setWidthUndefined() {
  1176. checkColumnIsAttached();
  1177. if (!isWidthUndefined()) {
  1178. getState().width = -1;
  1179. getGrid().markAsDirty();
  1180. getGrid().fireColumnResizeEvent(this, false);
  1181. }
  1182. return this;
  1183. }
  1184. /**
  1185. * Sets the minimum width for this column.
  1186. * <p>
  1187. * This defines the minimum guaranteed pixel width of the column
  1188. * <em>when it is set to expand</em>.
  1189. *
  1190. * @throws IllegalStateException
  1191. * if the column is no longer attached to any grid
  1192. * @see #setExpandRatio(int)
  1193. */
  1194. public Column<T, V> setMinimumWidth(double pixels)
  1195. throws IllegalStateException {
  1196. checkColumnIsAttached();
  1197. final double maxwidth = getMaximumWidth();
  1198. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  1199. throw new IllegalArgumentException("New minimum width ("
  1200. + pixels + ") was greater than maximum width ("
  1201. + maxwidth + ")");
  1202. }
  1203. getState().minWidth = pixels;
  1204. getGrid().markAsDirty();
  1205. return this;
  1206. }
  1207. /**
  1208. * Return the minimum width for this column.
  1209. *
  1210. * @return the minimum width for this column
  1211. * @see #setMinimumWidth(double)
  1212. */
  1213. public double getMinimumWidth() {
  1214. return getState(false).minWidth;
  1215. }
  1216. /**
  1217. * Sets the maximum width for this column.
  1218. * <p>
  1219. * This defines the maximum allowed pixel width of the column <em>when
  1220. * it is set to expand</em>.
  1221. *
  1222. * @param pixels
  1223. * the maximum width
  1224. * @throws IllegalStateException
  1225. * if the column is no longer attached to any grid
  1226. * @see #setExpandRatio(int)
  1227. */
  1228. public Column<T, V> setMaximumWidth(double pixels) {
  1229. checkColumnIsAttached();
  1230. final double minwidth = getMinimumWidth();
  1231. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  1232. throw new IllegalArgumentException("New maximum width ("
  1233. + pixels + ") was less than minimum width (" + minwidth
  1234. + ")");
  1235. }
  1236. getState().maxWidth = pixels;
  1237. getGrid().markAsDirty();
  1238. return this;
  1239. }
  1240. /**
  1241. * Returns the maximum width for this column.
  1242. *
  1243. * @return the maximum width for this column
  1244. * @see #setMaximumWidth(double)
  1245. */
  1246. public double getMaximumWidth() {
  1247. return getState(false).maxWidth;
  1248. }
  1249. /**
  1250. * Sets whether this column can be resized by the user.
  1251. *
  1252. * @since 7.6
  1253. * @param resizable
  1254. * {@code true} if this column should be resizable,
  1255. * {@code false} otherwise
  1256. * @throws IllegalStateException
  1257. * if the column is no longer attached to any grid
  1258. */
  1259. public Column<T, V> setResizable(boolean resizable) {
  1260. checkColumnIsAttached();
  1261. if (resizable != isResizable()) {
  1262. getState().resizable = resizable;
  1263. getGrid().markAsDirty();
  1264. }
  1265. return this;
  1266. }
  1267. /**
  1268. * Gets the caption of the hiding toggle for this column.
  1269. *
  1270. * @since 7.5.0
  1271. * @see #setHidingToggleCaption(String)
  1272. * @return the caption for the hiding toggle for this column
  1273. */
  1274. public String getHidingToggleCaption() {
  1275. return getState(false).hidingToggleCaption;
  1276. }
  1277. /**
  1278. * Sets the caption of the hiding toggle for this column. Shown in the
  1279. * toggle for this column in the grid's sidebar when the column is
  1280. * {@link #isHidable() hidable}.
  1281. * <p>
  1282. * The default value is <code>null</code>, and in that case the column's
  1283. * {@link #getCaption() header caption} is used.
  1284. * <p>
  1285. * <em>NOTE:</em> setting this to empty string might cause the hiding
  1286. * toggle to not render correctly.
  1287. *
  1288. * @since 7.5.0
  1289. * @param hidingToggleCaption
  1290. * the text to show in the column hiding toggle
  1291. * @return the column itself
  1292. */
  1293. public Column<T, V> setHidingToggleCaption(String hidingToggleCaption) {
  1294. if (hidingToggleCaption != getHidingToggleCaption()) {
  1295. getState().hidingToggleCaption = hidingToggleCaption;
  1296. }
  1297. return this;
  1298. }
  1299. /**
  1300. * Hides or shows the column. By default columns are visible before
  1301. * explicitly hiding them.
  1302. *
  1303. * @since 7.5.0
  1304. * @param hidden
  1305. * <code>true</code> to hide the column, <code>false</code>
  1306. * to show
  1307. * @return this column
  1308. * @throws IllegalStateException
  1309. * if the column is no longer attached to any grid
  1310. */
  1311. public Column<T, V> setHidden(boolean hidden) {
  1312. checkColumnIsAttached();
  1313. if (hidden != isHidden()) {
  1314. getState().hidden = hidden;
  1315. getGrid().fireColumnVisibilityChangeEvent(this, hidden, false);
  1316. }
  1317. return this;
  1318. }
  1319. /**
  1320. * Returns whether this column is hidden. Default is {@code false}.
  1321. *
  1322. * @since 7.5.0
  1323. * @return <code>true</code> if the column is currently hidden,
  1324. * <code>false</code> otherwise
  1325. */
  1326. public boolean isHidden() {
  1327. return getState(false).hidden;
  1328. }
  1329. /**
  1330. * Sets whether this column can be hidden by the user. Hidable columns
  1331. * can be hidden and shown via the sidebar menu.
  1332. *
  1333. * @since 7.5.0
  1334. * @param hidable
  1335. * <code>true</code> iff the column may be hidable by the
  1336. * user via UI interaction
  1337. * @return this column
  1338. */
  1339. public Column<T, V> setHidable(boolean hidable) {
  1340. if (hidable != isHidable()) {
  1341. getState().hidable = hidable;
  1342. }
  1343. return this;
  1344. }
  1345. /**
  1346. * Returns whether this column can be hidden by the user. Default is
  1347. * {@code false}.
  1348. * <p>
  1349. * <em>Note:</em> the column can be programmatically hidden using
  1350. * {@link #setHidden(boolean)} regardless of the returned value.
  1351. *
  1352. * @since 7.5.0
  1353. * @return <code>true</code> if the user can hide the column,
  1354. * <code>false</code> if not
  1355. */
  1356. public boolean isHidable() {
  1357. return getState(false).hidable;
  1358. }
  1359. /**
  1360. * Returns whether this column can be resized by the user. Default is
  1361. * {@code true}.
  1362. * <p>
  1363. * <em>Note:</em> the column can be programmatically resized using
  1364. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  1365. * of the returned value.
  1366. *
  1367. * @since 7.6
  1368. * @return {@code true} if this column is resizable, {@code false}
  1369. * otherwise
  1370. */
  1371. public boolean isResizable() {
  1372. return getState(false).resizable;
  1373. }
  1374. /**
  1375. * Sets whether this Column has a component displayed in Editor or not.
  1376. * A column can only be editable if an editor component or binding has
  1377. * been set.
  1378. *
  1379. * @param editable
  1380. * {@code true} if column is editable; {@code false} if not
  1381. * @return this column
  1382. *
  1383. * @see #setEditorComponent(HasValue, Setter)
  1384. * @see #setEditorBinding(Binding)
  1385. */
  1386. public Column<T, V> setEditable(boolean editable) {
  1387. Objects.requireNonNull(editorBinding,
  1388. "Column has no editor binding or component defined");
  1389. getState().editable = editable;
  1390. return this;
  1391. }
  1392. /**
  1393. * Gets whether this Column has a component displayed in Editor or not.
  1394. *
  1395. * @return {@code true} if the column displays an editor component;
  1396. * {@code false} if not
  1397. */
  1398. public boolean isEditable() {
  1399. return getState(false).editable;
  1400. }
  1401. /**
  1402. * Sets an editor binding for this column. The {@link Binding} is used
  1403. * when a row is in editor mode to define how to populate an editor
  1404. * component based on the edited row and how to update an item based on
  1405. * the value in the editor component.
  1406. * <p>
  1407. * To create a binding to use with a column, define a binding for the
  1408. * editor binder (<code>grid.getEditor().getBinder()</code>) using e.g.
  1409. * {@link Binder#forField(HasValue)}. You can also use
  1410. * {@link #setEditorComponent(HasValue, Setter)} if no validator or
  1411. * converter is needed for the binding.
  1412. * <p>
  1413. * The {@link HasValue} that the binding is defined to use must be a
  1414. * {@link Component}.
  1415. *
  1416. * @param binding
  1417. * the binding to use for this column
  1418. * @return this column
  1419. *
  1420. * @see #setEditorComponent(HasValue, Setter)
  1421. * @see Binding
  1422. * @see Grid#getEditor()
  1423. * @see Editor#getBinder()
  1424. */
  1425. public Column<T, V> setEditorBinding(Binding<T, ?> binding) {
  1426. Objects.requireNonNull(binding, "null is not a valid editor field");
  1427. if (!(binding.getField() instanceof Component)) {
  1428. throw new IllegalArgumentException(
  1429. "Binding target must be a component.");
  1430. }
  1431. this.editorBinding = binding;
  1432. return setEditable(true);
  1433. }
  1434. /**
  1435. * Gets the binder binding that is currently used for this column.
  1436. *
  1437. * @return the used binder binding, or <code>null</code> if no binding
  1438. * is configured
  1439. *
  1440. * @see #setEditorBinding(Binding)
  1441. */
  1442. public Binding<T, ?> getEditorBinding() {
  1443. return editorBinding;
  1444. }
  1445. /**
  1446. * Sets a component and setter to use for editing values of this column
  1447. * in the editor row. This is a shorthand for use in simple cases where
  1448. * no validator or converter is needed. Use
  1449. * {@link #setEditorBinding(Binding)} to support more complex cases.
  1450. * <p>
  1451. * <strong>Note:</strong> The same component cannot be used for multiple
  1452. * columns.
  1453. *
  1454. * @param editorComponent
  1455. * the editor component
  1456. * @param setter
  1457. * a setter that stores the component value in the row item
  1458. * @return this column
  1459. *
  1460. * @see #setEditorBinding(Binding)
  1461. * @see Grid#getEditor()
  1462. * @see Binder#bind(HasValue, ValueProvider, Setter)
  1463. */
  1464. public <C extends HasValue<V> & Component> Column<T, V> setEditorComponent(
  1465. C editorComponent, Setter<T, V> setter) {
  1466. Objects.requireNonNull(editorComponent,
  1467. "Editor component cannot be null");
  1468. Objects.requireNonNull(setter, "Setter cannot be null");
  1469. Binding<T, V> binding = getGrid().getEditor().getBinder()
  1470. .bind(editorComponent, valueProvider::apply, setter);
  1471. return setEditorBinding(binding);
  1472. }
  1473. /**
  1474. * Sets a component to use for editing values of this columns in the
  1475. * editor row. This method can only be used if the column has an
  1476. * {@link #setId(String) id} and the {@link Grid} has been created using
  1477. * {@link Grid#Grid(Class)} or some other way that allows finding
  1478. * properties based on property names.
  1479. * <p>
  1480. * This is a shorthand for use in simple cases where no validator or
  1481. * converter is needed. Use {@link #setEditorBinding(Binding)} to
  1482. * support more complex cases.
  1483. * <p>
  1484. * <strong>Note:</strong> The same component cannot be used for multiple
  1485. * columns.
  1486. *
  1487. * @param editorComponent
  1488. * the editor component
  1489. * @return this column
  1490. *
  1491. * @see #setEditorBinding(Binding)
  1492. * @see Grid#getEditor()
  1493. * @see Binder#bind(HasValue, String)
  1494. * @see Grid#Grid(Class)
  1495. */
  1496. public <F, C extends HasValue<F> & Component> Column<T, V> setEditorComponent(
  1497. C editorComponent) {
  1498. Objects.requireNonNull(editorComponent,
  1499. "Editor component cannot be null");
  1500. String propertyName = getId();
  1501. if (propertyName == null) {
  1502. throw new IllegalStateException(
  1503. "setEditorComponent without a setter can only be used if the column has an id. "
  1504. + "Use another setEditorComponent(Component, Setter) or setEditorBinding(Binding) instead.");
  1505. }
  1506. Binding<T, F> binding = getGrid().getEditor().getBinder()
  1507. .bind(editorComponent, propertyName);
  1508. return setEditorBinding(binding);
  1509. }
  1510. /**
  1511. * Gets the grid that this column belongs to.
  1512. *
  1513. * @return the grid that this column belongs to, or <code>null</code> if
  1514. * this column has not yet been associated with any grid
  1515. */
  1516. protected Grid<T> getGrid() {
  1517. return getParent();
  1518. }
  1519. /**
  1520. * Checks if column is attached and throws an
  1521. * {@link IllegalStateException} if it is not.
  1522. *
  1523. * @throws IllegalStateException
  1524. * if the column is no longer attached to any grid
  1525. */
  1526. protected void checkColumnIsAttached() throws IllegalStateException {
  1527. if (getGrid() == null) {
  1528. throw new IllegalStateException(
  1529. "Column is no longer attached to a grid.");
  1530. }
  1531. }
  1532. /**
  1533. * Writes the design attributes for this column into given element.
  1534. *
  1535. * @since 7.5.0
  1536. *
  1537. * @param element
  1538. * Element to write attributes into
  1539. *
  1540. * @param designContext
  1541. * the design context
  1542. */
  1543. protected void writeDesign(Element element,
  1544. DesignContext designContext) {
  1545. Attributes attributes = element.attributes();
  1546. ColumnState defaultState = new ColumnState();
  1547. if (getId() == null) {
  1548. setId("column" + getGrid().getColumns().indexOf(this));
  1549. }
  1550. DesignAttributeHandler.writeAttribute("column-id", attributes,
  1551. getId(), null, String.class, designContext);
  1552. // Sortable is a special attribute that depends on the data
  1553. // provider.
  1554. DesignAttributeHandler.writeAttribute("sortable", attributes,
  1555. isSortable(), null, boolean.class, designContext);
  1556. DesignAttributeHandler.writeAttribute("editable", attributes,
  1557. isEditable(), defaultState.editable, boolean.class,
  1558. designContext);
  1559. DesignAttributeHandler.writeAttribute("resizable", attributes,
  1560. isResizable(), defaultState.resizable, boolean.class,
  1561. designContext);
  1562. DesignAttributeHandler.writeAttribute("hidable", attributes,
  1563. isHidable(), defaultState.hidable, boolean.class,
  1564. designContext);
  1565. DesignAttributeHandler.writeAttribute("hidden", attributes,
  1566. isHidden(), defaultState.hidden, boolean.class,
  1567. designContext);
  1568. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  1569. attributes, getHidingToggleCaption(),
  1570. defaultState.hidingToggleCaption, String.class,
  1571. designContext);
  1572. DesignAttributeHandler.writeAttribute("width", attributes,
  1573. getWidth(), defaultState.width, Double.class,
  1574. designContext);
  1575. DesignAttributeHandler.writeAttribute("min-width", attributes,
  1576. getMinimumWidth(), defaultState.minWidth, Double.class,
  1577. designContext);
  1578. DesignAttributeHandler.writeAttribute("max-width", attributes,
  1579. getMaximumWidth(), defaultState.maxWidth, Double.class,
  1580. designContext);
  1581. DesignAttributeHandler.writeAttribute("expand", attributes,
  1582. getExpandRatio(), defaultState.expandRatio, Integer.class,
  1583. designContext);
  1584. }
  1585. /**
  1586. * Reads the design attributes for this column from given element.
  1587. *
  1588. * @since 7.5.0
  1589. * @param design
  1590. * Element to read attributes from
  1591. * @param designContext
  1592. * the design context
  1593. */
  1594. @SuppressWarnings("unchecked")
  1595. protected void readDesign(Element design, DesignContext designContext) {
  1596. Attributes attributes = design.attributes();
  1597. if (design.hasAttr("sortable")) {
  1598. setSortable(DesignAttributeHandler.readAttribute("sortable",
  1599. attributes, boolean.class));
  1600. } else {
  1601. setSortable(false);
  1602. }
  1603. if (design.hasAttr("editable")) {
  1604. /*
  1605. * This is a fake editor just to have something (otherwise
  1606. * "setEditable" throws an exception.
  1607. *
  1608. * Let's use TextField here because we support only Strings as
  1609. * inline data type. It will work incorrectly for other types
  1610. * but we don't support them anyway.
  1611. */
  1612. setEditorComponent((HasValue<V> & Component) new TextField(),
  1613. (item, value) -> {
  1614. // Ignore user value since we don't know the setter
  1615. });
  1616. setEditable(DesignAttributeHandler.readAttribute("editable",
  1617. attributes, boolean.class));
  1618. }
  1619. if (design.hasAttr("resizable")) {
  1620. setResizable(DesignAttributeHandler.readAttribute("resizable",
  1621. attributes, boolean.class));
  1622. }
  1623. if (design.hasAttr("hidable")) {
  1624. setHidable(DesignAttributeHandler.readAttribute("hidable",
  1625. attributes, boolean.class));
  1626. }
  1627. if (design.hasAttr("hidden")) {
  1628. setHidden(DesignAttributeHandler.readAttribute("hidden",
  1629. attributes, boolean.class));
  1630. }
  1631. if (design.hasAttr("hiding-toggle-caption")) {
  1632. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  1633. "hiding-toggle-caption", attributes, String.class));
  1634. }
  1635. // Read size info where necessary.
  1636. if (design.hasAttr("width")) {
  1637. setWidth(DesignAttributeHandler.readAttribute("width",
  1638. attributes, Double.class));
  1639. }
  1640. if (design.hasAttr("min-width")) {
  1641. setMinimumWidth(DesignAttributeHandler
  1642. .readAttribute("min-width", attributes, Double.class));
  1643. }
  1644. if (design.hasAttr("max-width")) {
  1645. setMaximumWidth(DesignAttributeHandler
  1646. .readAttribute("max-width", attributes, Double.class));
  1647. }
  1648. if (design.hasAttr("expand")) {
  1649. if (design.attr("expand").isEmpty()) {
  1650. setExpandRatio(1);
  1651. } else {
  1652. setExpandRatio(DesignAttributeHandler.readAttribute(
  1653. "expand", attributes, Integer.class));
  1654. }
  1655. }
  1656. }
  1657. }
  1658. private class HeaderImpl extends Header {
  1659. @Override
  1660. protected Grid<T> getGrid() {
  1661. return Grid.this;
  1662. }
  1663. @Override
  1664. protected SectionState getState(boolean markAsDirty) {
  1665. return Grid.this.getState(markAsDirty).header;
  1666. }
  1667. @Override
  1668. protected Column<?, ?> getColumnByInternalId(String internalId) {
  1669. return getGrid().getColumnByInternalId(internalId);
  1670. }
  1671. @Override
  1672. @SuppressWarnings("unchecked")
  1673. protected String getInternalIdForColumn(Column<?, ?> column) {
  1674. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  1675. }
  1676. };
  1677. private class FooterImpl extends Footer {
  1678. @Override
  1679. protected Grid<T> getGrid() {
  1680. return Grid.this;
  1681. }
  1682. @Override
  1683. protected SectionState getState(boolean markAsDirty) {
  1684. return Grid.this.getState(markAsDirty).footer;
  1685. }
  1686. @Override
  1687. protected Column<?, ?> getColumnByInternalId(String internalId) {
  1688. return getGrid().getColumnByInternalId(internalId);
  1689. }
  1690. @Override
  1691. @SuppressWarnings("unchecked")
  1692. protected String getInternalIdForColumn(Column<?, ?> column) {
  1693. return getGrid().getInternalIdForColumn((Column<T, ?>) column);
  1694. }
  1695. };
  1696. private final Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
  1697. private final Map<String, Column<T, ?>> columnKeys = new HashMap<>();
  1698. private final Map<String, Column<T, ?>> columnIds = new HashMap<>();
  1699. private final List<GridSortOrder<T>> sortOrder = new ArrayList<>();
  1700. private final DetailsManager<T> detailsManager;
  1701. private final Set<Component> extensionComponents = new HashSet<>();
  1702. private StyleGenerator<T> styleGenerator = item -> null;
  1703. private DescriptionGenerator<T> descriptionGenerator;
  1704. private final Header header = new HeaderImpl();
  1705. private final Footer footer = new FooterImpl();
  1706. private int counter = 0;
  1707. private GridSelectionModel<T> selectionModel;
  1708. private Editor<T> editor;
  1709. private final PropertySet<T> propertySet;
  1710. /**
  1711. * Creates a new grid without support for creating columns based on property
  1712. * names. Use an alternative constructor, such as {@link Grid#Grid(Class)},
  1713. * to create a grid that automatically sets up columns based on the type of
  1714. * presented data.
  1715. *
  1716. * @see #Grid(Class)
  1717. * @see #withPropertySet(PropertySet)
  1718. */
  1719. public Grid() {
  1720. this(new PropertySet<T>() {
  1721. @Override
  1722. public Stream<PropertyDefinition<T, ?>> getProperties() {
  1723. // No columns configured by default
  1724. return Stream.empty();
  1725. }
  1726. @Override
  1727. public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
  1728. throw new IllegalStateException(
  1729. "A Grid created without a bean type class literal or a custom property set"
  1730. + " doesn't support finding properties by name.");
  1731. }
  1732. });
  1733. }
  1734. /**
  1735. * Creates a new grid that uses reflection based on the provided bean type
  1736. * to automatically set up an initial set of columns. All columns will be
  1737. * configured using the same {@link Object#toString()} renderer that is used
  1738. * by {@link #addColumn(ValueProvider)}.
  1739. *
  1740. * @param beanType
  1741. * the bean type to use, not <code>null</code>
  1742. * @see #Grid()
  1743. * @see #withPropertySet(PropertySet)
  1744. */
  1745. public Grid(Class<T> beanType) {
  1746. this(BeanPropertySet.get(beanType));
  1747. }
  1748. /**
  1749. * Creates a grid using a custom {@link PropertySet} implementation for
  1750. * configuring the initial columns and resolving property names for
  1751. * {@link #addColumn(String)} and
  1752. * {@link Column#setEditorComponent(HasValue)}.
  1753. *
  1754. * @see #withPropertySet(PropertySet)
  1755. *
  1756. * @param propertySet
  1757. * the property set implementation to use, not <code>null</code>.
  1758. */
  1759. protected Grid(PropertySet<T> propertySet) {
  1760. Objects.requireNonNull(propertySet, "propertySet cannot be null");
  1761. this.propertySet = propertySet;
  1762. registerRpc(new GridServerRpcImpl());
  1763. setDefaultHeaderRow(appendHeaderRow());
  1764. setSelectionModel(new SingleSelectionModelImpl<>());
  1765. detailsManager = new DetailsManager<>();
  1766. addExtension(detailsManager);
  1767. addDataGenerator(detailsManager);
  1768. editor = createEditor();
  1769. if (editor instanceof Extension) {
  1770. addExtension((Extension) editor);
  1771. }
  1772. addDataGenerator((item, json) -> {
  1773. String styleName = styleGenerator.apply(item);
  1774. if (styleName != null && !styleName.isEmpty()) {
  1775. json.put(GridState.JSONKEY_ROWSTYLE, styleName);
  1776. }
  1777. if (descriptionGenerator != null) {
  1778. String description = descriptionGenerator.apply(item);
  1779. if (description != null && !description.isEmpty()) {
  1780. json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
  1781. }
  1782. }
  1783. });
  1784. // Automatically add columns for all available properties
  1785. propertySet.getProperties().map(PropertyDefinition::getName)
  1786. .forEach(this::addColumn);
  1787. }
  1788. /**
  1789. * Creates a grid using a custom {@link PropertySet} implementation for
  1790. * creating a default set of columns and for resolving property names with
  1791. * {@link #addColumn(String)} and
  1792. * {@link Column#setEditorComponent(HasValue)}.
  1793. * <p>
  1794. * This functionality is provided as static method instead of as a public
  1795. * constructor in order to make it possible to use a custom property set
  1796. * without creating a subclass while still leaving the public constructors
  1797. * focused on the common use cases.
  1798. *
  1799. * @see Grid#Grid()
  1800. * @see Grid#Grid(Class)
  1801. *
  1802. * @param propertySet
  1803. * the property set implementation to use, not <code>null</code>.
  1804. * @return a new grid using the provided property set, not <code>null</code>
  1805. */
  1806. public static <BEAN> Grid<BEAN> withPropertySet(
  1807. PropertySet<BEAN> propertySet) {
  1808. return new Grid<>(propertySet);
  1809. }
  1810. /**
  1811. * Creates a new {@code Grid} using the given caption
  1812. *
  1813. * @param caption
  1814. * the caption of the grid
  1815. */
  1816. public Grid(String caption) {
  1817. this();
  1818. setCaption(caption);
  1819. }
  1820. /**
  1821. * Creates a new {@code Grid} using the given caption and
  1822. * {@code DataProvider}
  1823. *
  1824. * @param caption
  1825. * the caption of the grid
  1826. * @param dataProvider
  1827. * the data provider, not {@code null}
  1828. */
  1829. public Grid(String caption, DataProvider<T, ?> dataProvider) {
  1830. this(caption);
  1831. setDataProvider(dataProvider);
  1832. }
  1833. /**
  1834. * Creates a new {@code Grid} using the given {@code DataProvider}
  1835. *
  1836. * @param dataProvider
  1837. * the data provider, not {@code null}
  1838. */
  1839. public Grid(DataProvider<T, ?> dataProvider) {
  1840. this();
  1841. setDataProvider(dataProvider);
  1842. }
  1843. /**
  1844. * Creates a new {@code Grid} using the given caption and collection of
  1845. * items
  1846. *
  1847. * @param caption
  1848. * the caption of the grid
  1849. * @param items
  1850. * the data items to use, not {@çode null}
  1851. */
  1852. public Grid(String caption, Collection<T> items) {
  1853. this(caption, DataProvider.ofCollection(items));
  1854. }
  1855. public <V> void fireColumnVisibilityChangeEvent(Column<T, V> column,
  1856. boolean hidden, boolean userOriginated) {
  1857. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  1858. userOriginated));
  1859. }
  1860. /**
  1861. * Adds a new column with the given property name. The property name will be
  1862. * used as the {@link Column#getId() column id} and the
  1863. * {@link Column#getCaption() column caption} will be set based on the
  1864. * property definition.
  1865. * <p>
  1866. * This method can only be used for a <code>Grid</code> created using
  1867. * {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
  1868. *
  1869. * @param propertyName
  1870. * the property name of the new column, not <code>null</code>
  1871. * @return the newly added column, not <code>null</code>
  1872. */
  1873. public Column<T, ?> addColumn(String propertyName) {
  1874. Objects.requireNonNull(propertyName, "Property name cannot be null");
  1875. if (getColumn(propertyName) != null) {
  1876. throw new IllegalStateException(
  1877. "There is already a column for " + propertyName);
  1878. }
  1879. PropertyDefinition<T, ?> definition = propertySet
  1880. .getProperty(propertyName)
  1881. .orElseThrow(() -> new IllegalArgumentException(
  1882. "Could not resolve property name " + propertyName
  1883. + " from " + propertySet));
  1884. return addColumn(definition.getGetter()).setId(definition.getName())
  1885. .setCaption(definition.getCaption());
  1886. }
  1887. /**
  1888. * Adds a new text column to this {@link Grid} with a value provider. The
  1889. * column will use a {@link TextRenderer}. The value is converted to a
  1890. * String using {@link Object#toString()}. Sorting in memory is executed by
  1891. * comparing the String values.
  1892. *
  1893. * @param valueProvider
  1894. * the value provider
  1895. *
  1896. * @return the new column
  1897. */
  1898. public Column<T, String> addColumn(ValueProvider<T, ?> valueProvider) {
  1899. return addColumn(t -> String.valueOf(valueProvider.apply(t)),
  1900. new TextRenderer());
  1901. }
  1902. /**
  1903. * Adds a new column to this {@link Grid} with typed renderer and value
  1904. * provider.
  1905. *
  1906. * @param valueProvider
  1907. * the value provider
  1908. * @param renderer
  1909. * the column value class
  1910. * @param <V>
  1911. * the column value type
  1912. *
  1913. * @return the new column
  1914. *
  1915. * @see AbstractRenderer
  1916. */
  1917. public <V> Column<T, V> addColumn(
  1918. ValueProvider<T, ? extends V> valueProvider,
  1919. AbstractRenderer<? super T, V> renderer) {
  1920. String generatedIdentifier = getGeneratedIdentifier();
  1921. Column<T, V> column = new Column<>(valueProvider, renderer);
  1922. addColumn(generatedIdentifier, column);
  1923. return column;
  1924. }
  1925. private void addColumn(String identifier, Column<T, ?> column) {
  1926. if (getColumns().contains(column)) {
  1927. return;
  1928. }
  1929. column.extend(this);
  1930. columnSet.add(column);
  1931. columnKeys.put(identifier, column);
  1932. column.setInternalId(identifier);
  1933. addDataGenerator(column);
  1934. getState().columnOrder.add(identifier);
  1935. getHeader().addColumn(identifier);
  1936. if (getDefaultHeaderRow() != null) {
  1937. getDefaultHeaderRow().getCell(column).setText(column.getCaption());
  1938. }
  1939. }
  1940. /**
  1941. * Removes the given column from this {@link Grid}.
  1942. *
  1943. * @param column
  1944. * the column to remove
  1945. */
  1946. public void removeColumn(Column<T, ?> column) {
  1947. if (columnSet.remove(column)) {
  1948. String columnId = column.getInternalId();
  1949. columnKeys.remove(columnId);
  1950. columnIds.remove(column.getId());
  1951. column.remove();
  1952. getHeader().removeColumn(columnId);
  1953. getFooter().removeColumn(columnId);
  1954. getState(true).columnOrder.remove(columnId);
  1955. }
  1956. }
  1957. /**
  1958. * Sets the details component generator.
  1959. *
  1960. * @param generator
  1961. * the generator for details components
  1962. */
  1963. public void setDetailsGenerator(DetailsGenerator<T> generator) {
  1964. this.detailsManager.setDetailsGenerator(generator);
  1965. }
  1966. /**
  1967. * Sets the visibility of details component for given item.
  1968. *
  1969. * @param data
  1970. * the item to show details for
  1971. * @param visible
  1972. * {@code true} if details component should be visible;
  1973. * {@code false} if it should be hidden
  1974. */
  1975. public void setDetailsVisible(T data, boolean visible) {
  1976. detailsManager.setDetailsVisible(data, visible);
  1977. }
  1978. /**
  1979. * Returns the visibility of details component for given item.
  1980. *
  1981. * @param data
  1982. * the item to show details for
  1983. *
  1984. * @return {@code true} if details component should be visible;
  1985. * {@code false} if it should be hidden
  1986. */
  1987. public boolean isDetailsVisible(T data) {
  1988. return detailsManager.isDetailsVisible(data);
  1989. }
  1990. /**
  1991. * Gets an unmodifiable collection of all columns currently in this
  1992. * {@link Grid}.
  1993. *
  1994. * @return unmodifiable collection of columns
  1995. */
  1996. public List<Column<T, ?>> getColumns() {
  1997. return Collections.unmodifiableList(getState(false).columnOrder.stream()
  1998. .map(columnKeys::get).collect(Collectors.toList()));
  1999. }
  2000. /**
  2001. * Gets a {@link Column} of this grid by its identifying string.
  2002. *
  2003. * @see Column#setId(String)
  2004. *
  2005. * @param columnId
  2006. * the identifier of the column to get
  2007. * @return the column corresponding to the given column identifier, or
  2008. * <code>null</code> if there is no such column
  2009. */
  2010. public Column<T, ?> getColumn(String columnId) {
  2011. return columnIds.get(columnId);
  2012. }
  2013. @Override
  2014. public Iterator<Component> iterator() {
  2015. Set<Component> componentSet = new LinkedHashSet<>(extensionComponents);
  2016. Header header = getHeader();
  2017. for (int i = 0; i < header.getRowCount(); ++i) {
  2018. HeaderRow row = header.getRow(i);
  2019. getColumns().forEach(column -> {
  2020. HeaderCell cell = row.getCell(column);
  2021. if (cell.getCellType() == GridStaticCellType.WIDGET) {
  2022. componentSet.add(cell.getComponent());
  2023. }
  2024. });
  2025. }
  2026. Footer footer = getFooter();
  2027. for (int i = 0; i < footer.getRowCount(); ++i) {
  2028. FooterRow row = footer.getRow(i);
  2029. getColumns().forEach(column -> {
  2030. FooterCell cell = row.getCell(column);
  2031. if (cell.getCellType() == GridStaticCellType.WIDGET) {
  2032. componentSet.add(cell.getComponent());
  2033. }
  2034. });
  2035. }
  2036. return Collections.unmodifiableSet(componentSet).iterator();
  2037. }
  2038. /**
  2039. * Sets the number of frozen columns in this grid. Setting the count to 0
  2040. * means that no data columns will be frozen, but the built-in selection
  2041. * checkbox column will still be frozen if it's in use. Setting the count to
  2042. * -1 will also disable the selection column.
  2043. * <p>
  2044. * The default value is 0.
  2045. *
  2046. * @param numberOfColumns
  2047. * the number of columns that should be frozen
  2048. *
  2049. * @throws IllegalArgumentException
  2050. * if the column count is less than -1 or greater than the
  2051. * number of visible columns
  2052. */
  2053. public void setFrozenColumnCount(int numberOfColumns) {
  2054. if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
  2055. throw new IllegalArgumentException(
  2056. "count must be between -1 and the current number of columns ("
  2057. + columnSet.size() + "): " + numberOfColumns);
  2058. }
  2059. getState().frozenColumnCount = numberOfColumns;
  2060. }
  2061. /**
  2062. * Gets the number of frozen columns in this grid. 0 means that no data
  2063. * columns will be frozen, but the built-in selection checkbox column will
  2064. * still be frozen if it's in use. -1 means that not even the selection
  2065. * column is frozen.
  2066. * <p>
  2067. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  2068. * columns} in the count.
  2069. *
  2070. * @see #setFrozenColumnCount(int)
  2071. *
  2072. * @return the number of frozen columns
  2073. */
  2074. public int getFrozenColumnCount() {
  2075. return getState(false).frozenColumnCount;
  2076. }
  2077. /**
  2078. * Sets the number of rows that should be visible in Grid's body. This
  2079. * method will set the height mode to be {@link HeightMode#ROW}.
  2080. *
  2081. * @param rows
  2082. * The height in terms of number of rows displayed in Grid's
  2083. * body. If Grid doesn't contain enough rows, white space is
  2084. * displayed instead. If <code>null</code> is given, then Grid's
  2085. * height is undefined
  2086. * @throws IllegalArgumentException
  2087. * if {@code rows} is zero or less
  2088. * @throws IllegalArgumentException
  2089. * if {@code rows} is {@link Double#isInfinite(double) infinite}
  2090. * @throws IllegalArgumentException
  2091. * if {@code rows} is {@link Double#isNaN(double) NaN}
  2092. */
  2093. public void setHeightByRows(double rows) {
  2094. if (rows <= 0.0d) {
  2095. throw new IllegalArgumentException(
  2096. "More than zero rows must be shown.");
  2097. } else if (Double.isInfinite(rows)) {
  2098. throw new IllegalArgumentException(
  2099. "Grid doesn't support infinite heights");
  2100. } else if (Double.isNaN(rows)) {
  2101. throw new IllegalArgumentException("NaN is not a valid row count");
  2102. }
  2103. getState().heightMode = HeightMode.ROW;
  2104. getState().heightByRows = rows;
  2105. }
  2106. /**
  2107. * Gets the amount of rows in Grid's body that are shown, while
  2108. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  2109. *
  2110. * @return the amount of rows that are being shown in Grid's body
  2111. * @see #setHeightByRows(double)
  2112. */
  2113. public double getHeightByRows() {
  2114. return getState(false).heightByRows;
  2115. }
  2116. /**
  2117. * {@inheritDoc}
  2118. * <p>
  2119. * <em>Note:</em> This method will set the height mode to be
  2120. * {@link HeightMode#CSS}.
  2121. *
  2122. * @see #setHeightMode(HeightMode)
  2123. */
  2124. @Override
  2125. public void setHeight(float height, Unit unit) {
  2126. getState().heightMode = HeightMode.CSS;
  2127. super.setHeight(height, unit);
  2128. }
  2129. /**
  2130. * Defines the mode in which the Grid widget's height is calculated.
  2131. * <p>
  2132. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  2133. * via a {@code setHeight}-method, and behave as a traditional Component.
  2134. * <p>
  2135. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  2136. * will display as many rows as {@link #getHeightByRows()} defines.
  2137. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  2138. * will resize itself to still display the required amount of rows in its
  2139. * body. It also takes the horizontal scrollbar into account.
  2140. *
  2141. * @param heightMode
  2142. * the mode in to which Grid should be set
  2143. */
  2144. public void setHeightMode(HeightMode heightMode) {
  2145. /*
  2146. * This method is a workaround for the fact that Vaadin re-applies
  2147. * widget dimensions (height/width) on each state change event. The
  2148. * original design was to have setHeight and setHeightByRow be equals,
  2149. * and whichever was called the latest was considered in effect.
  2150. *
  2151. * But, because of Vaadin always calling setHeight on the widget, this
  2152. * approach doesn't work.
  2153. */
  2154. getState().heightMode = heightMode;
  2155. }
  2156. /**
  2157. * Returns the current {@link HeightMode} the Grid is in.
  2158. * <p>
  2159. * Defaults to {@link HeightMode#CSS}.
  2160. *
  2161. * @return the current HeightMode
  2162. */
  2163. public HeightMode getHeightMode() {
  2164. return getState(false).heightMode;
  2165. }
  2166. /**
  2167. * Sets the style generator that is used for generating class names for rows
  2168. * in this grid. Returning null from the generator results in no custom
  2169. * style name being set.
  2170. *
  2171. * @see StyleGenerator
  2172. *
  2173. * @param styleGenerator
  2174. * the row style generator to set, not null
  2175. * @throws NullPointerException
  2176. * if {@code styleGenerator} is {@code null}
  2177. */
  2178. public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
  2179. Objects.requireNonNull(styleGenerator,
  2180. "Style generator must not be null");
  2181. this.styleGenerator = styleGenerator;
  2182. getDataCommunicator().reset();
  2183. }
  2184. /**
  2185. * Gets the style generator that is used for generating class names for
  2186. * rows.
  2187. *
  2188. * @see StyleGenerator
  2189. *
  2190. * @return the row style generator
  2191. */
  2192. public StyleGenerator<T> getStyleGenerator() {
  2193. return styleGenerator;
  2194. }
  2195. /**
  2196. * Sets the description generator that is used for generating descriptions
  2197. * for rows.
  2198. *
  2199. * @param descriptionGenerator
  2200. * the row description generator to set, or <code>null</code> to
  2201. * remove a previously set generator
  2202. */
  2203. public void setDescriptionGenerator(
  2204. DescriptionGenerator<T> descriptionGenerator) {
  2205. this.descriptionGenerator = descriptionGenerator;
  2206. getDataCommunicator().reset();
  2207. }
  2208. /**
  2209. * Gets the description generator that is used for generating descriptions
  2210. * for rows.
  2211. *
  2212. * @return the row description generator, or <code>null</code> if no
  2213. * generator is set
  2214. */
  2215. public DescriptionGenerator<T> getDescriptionGenerator() {
  2216. return descriptionGenerator;
  2217. }
  2218. //
  2219. // HEADER AND FOOTER
  2220. //
  2221. /**
  2222. * Returns the header row at the given index.
  2223. *
  2224. * @param index
  2225. * the index of the row, where the topmost row has index zero
  2226. * @return the header row at the index
  2227. * @throws IndexOutOfBoundsException
  2228. * if {@code rowIndex < 0 || rowIndex >= getHeaderRowCount()}
  2229. */
  2230. public HeaderRow getHeaderRow(int index) {
  2231. return getHeader().getRow(index);
  2232. }
  2233. /**
  2234. * Gets the number of rows in the header section.
  2235. *
  2236. * @return the number of header rows
  2237. */
  2238. public int getHeaderRowCount() {
  2239. return header.getRowCount();
  2240. }
  2241. /**
  2242. * Inserts a new row at the given position to the header section. Shifts the
  2243. * row currently at that position and any subsequent rows down (adds one to
  2244. * their indices). Inserting at {@link #getHeaderRowCount()} appends the row
  2245. * at the bottom of the header.
  2246. *
  2247. * @param index
  2248. * the index at which to insert the row, where the topmost row
  2249. * has index zero
  2250. * @return the inserted header row
  2251. *
  2252. * @throws IndexOutOfBoundsException
  2253. * if {@code rowIndex < 0 || rowIndex > getHeaderRowCount()}
  2254. *
  2255. * @see #appendHeaderRow()
  2256. * @see #prependHeaderRow()
  2257. * @see #removeHeaderRow(HeaderRow)
  2258. * @see #removeHeaderRow(int)
  2259. */
  2260. public HeaderRow addHeaderRowAt(int index) {
  2261. return getHeader().addRowAt(index);
  2262. }
  2263. /**
  2264. * Adds a new row at the bottom of the header section.
  2265. *
  2266. * @return the appended header row
  2267. *
  2268. * @see #prependHeaderRow()
  2269. * @see #addHeaderRowAt(int)
  2270. * @see #removeHeaderRow(HeaderRow)
  2271. * @see #removeHeaderRow(int)
  2272. */
  2273. public HeaderRow appendHeaderRow() {
  2274. return addHeaderRowAt(getHeaderRowCount());
  2275. }
  2276. /**
  2277. * Adds a new row at the top of the header section.
  2278. *
  2279. * @return the prepended header row
  2280. *
  2281. * @see #appendHeaderRow()
  2282. * @see #addHeaderRowAt(int)
  2283. * @see #removeHeaderRow(HeaderRow)
  2284. * @see #removeHeaderRow(int)
  2285. */
  2286. public HeaderRow prependHeaderRow() {
  2287. return addHeaderRowAt(0);
  2288. }
  2289. /**
  2290. * Removes the given row from the header section. Removing a default row
  2291. * sets the Grid to have no default row.
  2292. *
  2293. * @param row
  2294. * the header row to be removed, not null
  2295. *
  2296. * @throws IllegalArgumentException
  2297. * if the header does not contain the row
  2298. *
  2299. * @see #removeHeaderRow(int)
  2300. * @see #addHeaderRowAt(int)
  2301. * @see #appendHeaderRow()
  2302. * @see #prependHeaderRow()
  2303. */
  2304. public void removeHeaderRow(HeaderRow row) {
  2305. getHeader().removeRow(row);
  2306. }
  2307. /**
  2308. * Removes the row at the given position from the header section.
  2309. *
  2310. * @param index
  2311. * the index of the row to remove, where the topmost row has
  2312. * index zero
  2313. *
  2314. * @throws IndexOutOfBoundsException
  2315. * if {@code index < 0 || index >= getHeaderRowCount()}
  2316. *
  2317. * @see #removeHeaderRow(HeaderRow)
  2318. * @see #addHeaderRowAt(int)
  2319. * @see #appendHeaderRow()
  2320. * @see #prependHeaderRow()
  2321. */
  2322. public void removeHeaderRow(int index) {
  2323. getHeader().removeRow(index);
  2324. }
  2325. /**
  2326. * Returns the current default row of the header.
  2327. *
  2328. * @return the default row or null if no default row set
  2329. *
  2330. * @see #setDefaultHeaderRow(HeaderRow)
  2331. */
  2332. public HeaderRow getDefaultHeaderRow() {
  2333. return header.getDefaultRow();
  2334. }
  2335. /**
  2336. * Sets the default row of the header. The default row is a special header
  2337. * row that displays column captions and sort indicators. By default Grid
  2338. * has a single row which is also the default row. When a header row is set
  2339. * as the default row, any existing cell content is replaced by the column
  2340. * captions.
  2341. *
  2342. * @param row
  2343. * the new default row, or null for no default row
  2344. *
  2345. * @throws IllegalArgumentException
  2346. * if the header does not contain the row
  2347. */
  2348. public void setDefaultHeaderRow(HeaderRow row) {
  2349. header.setDefaultRow((Row) row);
  2350. }
  2351. /**
  2352. * Returns the header section of this grid. The default header contains a
  2353. * single row, set as the {@linkplain #setDefaultHeaderRow(HeaderRow)
  2354. * default row}.
  2355. *
  2356. * @return the header section
  2357. */
  2358. protected Header getHeader() {
  2359. return header;
  2360. }
  2361. /**
  2362. * Returns the footer row at the given index.
  2363. *
  2364. * @param index
  2365. * the index of the row, where the topmost row has index zero
  2366. * @return the footer row at the index
  2367. * @throws IndexOutOfBoundsException
  2368. * if {@code rowIndex < 0 || rowIndex >= getFooterRowCount()}
  2369. */
  2370. public FooterRow getFooterRow(int index) {
  2371. return getFooter().getRow(index);
  2372. }
  2373. /**
  2374. * Gets the number of rows in the footer section.
  2375. *
  2376. * @return the number of footer rows
  2377. */
  2378. public int getFooterRowCount() {
  2379. return getFooter().getRowCount();
  2380. }
  2381. /**
  2382. * Inserts a new row at the given position to the footer section. Shifts the
  2383. * row currently at that position and any subsequent rows down (adds one to
  2384. * their indices). Inserting at {@link #getFooterRowCount()} appends the row
  2385. * at the bottom of the footer.
  2386. *
  2387. * @param index
  2388. * the index at which to insert the row, where the topmost row
  2389. * has index zero
  2390. * @return the inserted footer row
  2391. *
  2392. * @throws IndexOutOfBoundsException
  2393. * if {@code rowIndex < 0 || rowIndex > getFooterRowCount()}
  2394. *
  2395. * @see #appendFooterRow()
  2396. * @see #prependFooterRow()
  2397. * @see #removeFooterRow(FooterRow)
  2398. * @see #removeFooterRow(int)
  2399. */
  2400. public FooterRow addFooterRowAt(int index) {
  2401. return getFooter().addRowAt(index);
  2402. }
  2403. /**
  2404. * Adds a new row at the bottom of the footer section.
  2405. *
  2406. * @return the appended footer row
  2407. *
  2408. * @see #prependFooterRow()
  2409. * @see #addFooterRowAt(int)
  2410. * @see #removeFooterRow(FooterRow)
  2411. * @see #removeFooterRow(int)
  2412. */
  2413. public FooterRow appendFooterRow() {
  2414. return addFooterRowAt(getFooterRowCount());
  2415. }
  2416. /**
  2417. * Adds a new row at the top of the footer section.
  2418. *
  2419. * @return the prepended footer row
  2420. *
  2421. * @see #appendFooterRow()
  2422. * @see #addFooterRowAt(int)
  2423. * @see #removeFooterRow(FooterRow)
  2424. * @see #removeFooterRow(int)
  2425. */
  2426. public FooterRow prependFooterRow() {
  2427. return addFooterRowAt(0);
  2428. }
  2429. /**
  2430. * Removes the given row from the footer section. Removing a default row
  2431. * sets the Grid to have no default row.
  2432. *
  2433. * @param row
  2434. * the footer row to be removed, not null
  2435. *
  2436. * @throws IllegalArgumentException
  2437. * if the footer does not contain the row
  2438. *
  2439. * @see #removeFooterRow(int)
  2440. * @see #addFooterRowAt(int)
  2441. * @see #appendFooterRow()
  2442. * @see #prependFooterRow()
  2443. */
  2444. public void removeFooterRow(FooterRow row) {
  2445. getFooter().removeRow(row);
  2446. }
  2447. /**
  2448. * Removes the row at the given position from the footer section.
  2449. *
  2450. * @param index
  2451. * the index of the row to remove, where the topmost row has
  2452. * index zero
  2453. *
  2454. * @throws IndexOutOfBoundsException
  2455. * if {@code index < 0 || index >= getFooterRowCount()}
  2456. *
  2457. * @see #removeFooterRow(FooterRow)
  2458. * @see #addFooterRowAt(int)
  2459. * @see #appendFooterRow()
  2460. * @see #prependFooterRow()
  2461. */
  2462. public void removeFooterRow(int index) {
  2463. getFooter().removeRow(index);
  2464. }
  2465. /**
  2466. * Returns the footer section of this grid.
  2467. *
  2468. * @return the footer section
  2469. */
  2470. protected Footer getFooter() {
  2471. return footer;
  2472. }
  2473. /**
  2474. * Registers a new column reorder listener.
  2475. *
  2476. * @param listener
  2477. * the listener to register, not null
  2478. * @return a registration for the listener
  2479. */
  2480. public Registration addColumnReorderListener(
  2481. ColumnReorderListener listener) {
  2482. return addListener(ColumnReorderEvent.class, listener,
  2483. COLUMN_REORDER_METHOD);
  2484. }
  2485. /**
  2486. * Registers a new column resize listener.
  2487. *
  2488. * @param listener
  2489. * the listener to register, not null
  2490. * @return a registration for the listener
  2491. */
  2492. public Registration addColumnResizeListener(ColumnResizeListener listener) {
  2493. return addListener(ColumnResizeEvent.class, listener,
  2494. COLUMN_RESIZE_METHOD);
  2495. }
  2496. /**
  2497. * Adds an item click listener. The listener is called when an item of this
  2498. * {@code Grid} is clicked.
  2499. *
  2500. * @param listener
  2501. * the item click listener, not null
  2502. * @return a registration for the listener
  2503. */
  2504. public Registration addItemClickListener(
  2505. ItemClickListener<? super T> listener) {
  2506. return addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
  2507. listener, ITEM_CLICK_METHOD);
  2508. }
  2509. /**
  2510. * Registers a new column visibility change listener.
  2511. *
  2512. * @param listener
  2513. * the listener to register, not null
  2514. * @return a registration for the listener
  2515. */
  2516. public Registration addColumnVisibilityChangeListener(
  2517. ColumnVisibilityChangeListener listener) {
  2518. return addListener(ColumnVisibilityChangeEvent.class, listener,
  2519. COLUMN_VISIBILITY_METHOD);
  2520. }
  2521. /**
  2522. * Returns whether column reordering is allowed. Default value is
  2523. * <code>false</code>.
  2524. *
  2525. * @return true if reordering is allowed
  2526. */
  2527. public boolean isColumnReorderingAllowed() {
  2528. return getState(false).columnReorderingAllowed;
  2529. }
  2530. /**
  2531. * Sets whether or not column reordering is allowed. Default value is
  2532. * <code>false</code>.
  2533. *
  2534. * @param columnReorderingAllowed
  2535. * specifies whether column reordering is allowed
  2536. */
  2537. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  2538. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  2539. getState().columnReorderingAllowed = columnReorderingAllowed;
  2540. }
  2541. }
  2542. /**
  2543. * Sets the columns and their order for the grid. Columns currently in this
  2544. * grid that are not present in columns are removed. Similarly, any new
  2545. * column in columns will be added to this grid.
  2546. *
  2547. * @param columns
  2548. * the columns to set
  2549. */
  2550. public void setColumns(Column<T, ?>... columns) {
  2551. List<Column<T, ?>> currentColumns = getColumns();
  2552. Set<Column<T, ?>> removeColumns = new HashSet<>(currentColumns);
  2553. Set<Column<T, ?>> addColumns = Arrays.stream(columns)
  2554. .collect(Collectors.toSet());
  2555. removeColumns.removeAll(addColumns);
  2556. removeColumns.stream().forEach(this::removeColumn);
  2557. addColumns.removeAll(currentColumns);
  2558. addColumns.stream().forEach(c -> addColumn(getIdentifier(c), c));
  2559. setColumnOrder(columns);
  2560. }
  2561. private String getIdentifier(Column<T, ?> column) {
  2562. return columnKeys.entrySet().stream()
  2563. .filter(entry -> entry.getValue().equals(column))
  2564. .map(entry -> entry.getKey()).findFirst()
  2565. .orElse(getGeneratedIdentifier());
  2566. }
  2567. private String getGeneratedIdentifier() {
  2568. String columnId = "" + counter;
  2569. counter++;
  2570. return columnId;
  2571. }
  2572. /**
  2573. * Sets a new column order for the grid. All columns which are not ordered
  2574. * here will remain in the order they were before as the last columns of
  2575. * grid.
  2576. *
  2577. * @param columns
  2578. * the columns in the order they should be
  2579. */
  2580. public void setColumnOrder(Column<T, ?>... columns) {
  2581. List<String> columnOrder = new ArrayList<>();
  2582. for (Column<T, ?> column : columns) {
  2583. if (columnSet.contains(column)) {
  2584. columnOrder.add(column.getInternalId());
  2585. } else {
  2586. throw new IllegalArgumentException(
  2587. "setColumnOrder should not be called "
  2588. + "with columns that are not in the grid.");
  2589. }
  2590. }
  2591. List<String> stateColumnOrder = getState().columnOrder;
  2592. if (stateColumnOrder.size() != columnOrder.size()) {
  2593. stateColumnOrder.removeAll(columnOrder);
  2594. columnOrder.addAll(stateColumnOrder);
  2595. }
  2596. getState().columnOrder = columnOrder;
  2597. fireColumnReorderEvent(false);
  2598. }
  2599. /**
  2600. * Returns the selection model for this grid.
  2601. *
  2602. * @return the selection model, not null
  2603. */
  2604. public GridSelectionModel<T> getSelectionModel() {
  2605. assert selectionModel != null : "No selection model set by "
  2606. + getClass().getName() + " constructor";
  2607. return selectionModel;
  2608. }
  2609. /**
  2610. * Use this grid as a single select in {@link Binder}.
  2611. * <p>
  2612. * Throws {@link IllegalStateException} if the grid is not using a
  2613. * {@link SingleSelectionModel}.
  2614. *
  2615. * @return the single select wrapper that can be used in binder
  2616. * @throws IllegalStateException
  2617. * if not using a single selection model
  2618. */
  2619. public SingleSelect<T> asSingleSelect() {
  2620. GridSelectionModel<T> model = getSelectionModel();
  2621. if (!(model instanceof SingleSelectionModel)) {
  2622. throw new IllegalStateException(
  2623. "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.");
  2624. }
  2625. return ((SingleSelectionModel<T>) model).asSingleSelect();
  2626. }
  2627. public Editor<T> getEditor() {
  2628. return editor;
  2629. }
  2630. /**
  2631. * User this grid as a multiselect in {@link Binder}.
  2632. * <p>
  2633. * Throws {@link IllegalStateException} if the grid is not using a
  2634. * {@link MultiSelectionModel}.
  2635. *
  2636. * @return the multiselect wrapper that can be used in binder
  2637. * @throws IllegalStateException
  2638. * if not using a multiselection model
  2639. */
  2640. public MultiSelect<T> asMultiSelect() {
  2641. GridSelectionModel<T> model = getSelectionModel();
  2642. if (!(model instanceof MultiSelectionModel)) {
  2643. throw new IllegalStateException(
  2644. "Grid is not in multiselect mode, it needs to be explicitly set to such with setSelectionModel(MultiSelectionModel) before being able to use multiselection features.");
  2645. }
  2646. return ((MultiSelectionModel<T>) model).asMultiSelect();
  2647. }
  2648. /**
  2649. * Sets the selection model for the grid.
  2650. * <p>
  2651. * This method is for setting a custom selection model, and is
  2652. * {@code protected} because {@link #setSelectionMode(SelectionMode)} should
  2653. * be used for easy switching between built-in selection models.
  2654. * <p>
  2655. * The default selection model is {@link SingleSelectionModelImpl}.
  2656. * <p>
  2657. * To use a custom selection model, you can e.g. extend the grid call this
  2658. * method with your custom selection model.
  2659. *
  2660. * @param model
  2661. * the selection model to use, not {@code null}
  2662. *
  2663. * @see #setSelectionMode(SelectionMode)
  2664. */
  2665. @SuppressWarnings("unchecked")
  2666. protected void setSelectionModel(GridSelectionModel<T> model) {
  2667. Objects.requireNonNull(model, "selection model cannot be null");
  2668. if (selectionModel != null) { // null when called from constructor
  2669. selectionModel.remove();
  2670. }
  2671. selectionModel = model;
  2672. if (selectionModel instanceof AbstractListingExtension) {
  2673. ((AbstractListingExtension<T>) selectionModel).extend(this);
  2674. } else {
  2675. addExtension(selectionModel);
  2676. }
  2677. }
  2678. /**
  2679. * Sets the grid's selection mode.
  2680. * <p>
  2681. * The built-in selection models are:
  2682. * <ul>
  2683. * <li>{@link SelectionMode#SINGLE} -> {@link SingleSelectionModelImpl},
  2684. * <b>the default model</b></li>
  2685. * <li>{@link SelectionMode#MULTI} -> {@link MultiSelectionModelImpl}, with
  2686. * checkboxes in the first column for selection</li>
  2687. * <li>{@link SelectionMode#NONE} -> {@link NoSelectionModel}, preventing
  2688. * selection</li>
  2689. * </ul>
  2690. * <p>
  2691. * To use your custom selection model, you can use
  2692. * {@link #setSelectionModel(GridSelectionModel)}, see existing selection
  2693. * model implementations for example.
  2694. *
  2695. * @param selectionMode
  2696. * the selection mode to switch to, not {@code null}
  2697. * @return the used selection model
  2698. *
  2699. * @see SelectionMode
  2700. * @see GridSelectionModel
  2701. * @see #setSelectionModel(GridSelectionModel)
  2702. */
  2703. public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
  2704. Objects.requireNonNull(selectionMode, "Selection mode cannot be null.");
  2705. GridSelectionModel<T> model = selectionMode.createModel();
  2706. setSelectionModel(model);
  2707. return model;
  2708. }
  2709. /**
  2710. * Adds a selection listener to the current selection model.
  2711. * <p>
  2712. * <em>NOTE:</em> If selection mode is switched with
  2713. * {@link #setSelectionMode(SelectionMode)}, then this listener is not
  2714. * triggered anymore when selection changes!
  2715. * <p>
  2716. * This is a shorthand for
  2717. * {@code grid.getSelectionModel().addSelectionListener()}. To get more
  2718. * detailed selection events, use {@link #getSelectionModel()} and either
  2719. * {@link SingleSelectionModel#addSingleSelectionListener(SingleSelectionListener)}
  2720. * or
  2721. * {@link MultiSelectionModel#addMultiSelectionListener(MultiSelectionListener)}
  2722. * depending on the used selection mode.
  2723. *
  2724. * @param listener
  2725. * the listener to add
  2726. * @return a registration handle to remove the listener
  2727. * @throws UnsupportedOperationException
  2728. * if selection has been disabled with
  2729. * {@link SelectionMode#NONE}
  2730. */
  2731. public Registration addSelectionListener(SelectionListener<T> listener)
  2732. throws UnsupportedOperationException {
  2733. return getSelectionModel().addSelectionListener(listener);
  2734. }
  2735. /**
  2736. * Sort this Grid in ascending order by a specified column.
  2737. *
  2738. * @param column
  2739. * a column to sort against
  2740. *
  2741. */
  2742. public void sort(Column<T, ?> column) {
  2743. sort(column, SortDirection.ASCENDING);
  2744. }
  2745. /**
  2746. * Sort this Grid in user-specified {@link QuerySortOrder} by a column.
  2747. *
  2748. * @param column
  2749. * a column to sort against
  2750. * @param direction
  2751. * a sort order value (ascending/descending)
  2752. *
  2753. */
  2754. public void sort(Column<T, ?> column, SortDirection direction) {
  2755. setSortOrder(Collections
  2756. .singletonList(new GridSortOrder<>(column, direction)));
  2757. }
  2758. /**
  2759. * Clear the current sort order, and re-sort the grid.
  2760. */
  2761. public void clearSortOrder() {
  2762. sortOrder.clear();
  2763. sort(false);
  2764. }
  2765. /**
  2766. * Sets the sort order to use.
  2767. *
  2768. * @param order
  2769. * a sort order list.
  2770. *
  2771. * @throws IllegalArgumentException
  2772. * if order is null
  2773. */
  2774. public void setSortOrder(List<GridSortOrder<T>> order) {
  2775. setSortOrder(order, false);
  2776. }
  2777. /**
  2778. * Sets the sort order to use, given a {@link GridSortOrderBuilder}.
  2779. * Shorthand for {@code setSortOrder(builder.build())}.
  2780. *
  2781. * @see GridSortOrderBuilder
  2782. *
  2783. * @param builder
  2784. * the sort builder to retrieve the sort order from
  2785. * @throws NullPointerException
  2786. * if builder is null
  2787. */
  2788. public void setSortOrder(GridSortOrderBuilder<T> builder) {
  2789. Objects.requireNonNull(builder, "Sort builder cannot be null");
  2790. setSortOrder(builder.build());
  2791. }
  2792. /**
  2793. * Adds a sort order change listener that gets notified when the sort order
  2794. * changes.
  2795. *
  2796. * @param listener
  2797. * the sort order change listener to add
  2798. */
  2799. @Override
  2800. public Registration addSortListener(
  2801. SortListener<GridSortOrder<T>> listener) {
  2802. return addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  2803. }
  2804. /**
  2805. * Get the current sort order list.
  2806. *
  2807. * @return a sort order list
  2808. */
  2809. public List<GridSortOrder<T>> getSortOrder() {
  2810. return Collections.unmodifiableList(sortOrder);
  2811. }
  2812. @Override
  2813. protected GridState getState() {
  2814. return getState(true);
  2815. }
  2816. @Override
  2817. protected GridState getState(boolean markAsDirty) {
  2818. return (GridState) super.getState(markAsDirty);
  2819. }
  2820. /**
  2821. * Sets the column resize mode to use. The default mode is
  2822. * {@link ColumnResizeMode#ANIMATED}.
  2823. *
  2824. * @param mode
  2825. * a ColumnResizeMode value
  2826. * @since 7.7.5
  2827. */
  2828. public void setColumnResizeMode(ColumnResizeMode mode) {
  2829. getState().columnResizeMode = mode;
  2830. }
  2831. /**
  2832. * Returns the current column resize mode. The default mode is
  2833. * {@link ColumnResizeMode#ANIMATED}.
  2834. *
  2835. * @return a ColumnResizeMode value
  2836. * @since 7.7.5
  2837. */
  2838. public ColumnResizeMode getColumnResizeMode() {
  2839. return getState(false).columnResizeMode;
  2840. }
  2841. /**
  2842. * Creates a new Editor instance. Can be overridden to create a custom
  2843. * Editor. If the Editor is a {@link AbstractGridExtension}, it will be
  2844. * automatically added to {@link DataCommunicator}.
  2845. *
  2846. * @return editor
  2847. */
  2848. protected Editor<T> createEditor() {
  2849. return new EditorImpl<>(propertySet);
  2850. }
  2851. private void addExtensionComponent(Component c) {
  2852. if (extensionComponents.add(c)) {
  2853. c.setParent(this);
  2854. markAsDirty();
  2855. }
  2856. }
  2857. private void removeExtensionComponent(Component c) {
  2858. if (extensionComponents.remove(c)) {
  2859. c.setParent(null);
  2860. markAsDirty();
  2861. }
  2862. }
  2863. private void fireColumnReorderEvent(boolean userOriginated) {
  2864. fireEvent(new ColumnReorderEvent(this, userOriginated));
  2865. }
  2866. private void fireColumnResizeEvent(Column<?, ?> column,
  2867. boolean userOriginated) {
  2868. fireEvent(new ColumnResizeEvent(this, column, userOriginated));
  2869. }
  2870. @Override
  2871. protected void readItems(Element design, DesignContext context) {
  2872. // Grid handles reading of items in Grid#readData
  2873. }
  2874. @Override
  2875. public DataProvider<T, ?> getDataProvider() {
  2876. return internalGetDataProvider();
  2877. }
  2878. @Override
  2879. public void setDataProvider(DataProvider<T, ?> dataProvider) {
  2880. internalSetDataProvider(dataProvider);
  2881. }
  2882. @Override
  2883. protected void doReadDesign(Element design, DesignContext context) {
  2884. Attributes attrs = design.attributes();
  2885. if (attrs.hasKey("selection-mode")) {
  2886. setSelectionMode(DesignAttributeHandler.readAttribute(
  2887. "selection-mode", attrs, SelectionMode.class));
  2888. }
  2889. Attributes attr = design.attributes();
  2890. if (attr.hasKey("selection-allowed")) {
  2891. setReadOnly(DesignAttributeHandler
  2892. .readAttribute("selection-allowed", attr, Boolean.class));
  2893. }
  2894. if (attrs.hasKey("rows")) {
  2895. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  2896. double.class));
  2897. }
  2898. readStructure(design, context);
  2899. // Read frozen columns after columns are read.
  2900. if (attrs.hasKey("frozen-columns")) {
  2901. setFrozenColumnCount(DesignAttributeHandler
  2902. .readAttribute("frozen-columns", attrs, int.class));
  2903. }
  2904. }
  2905. @Override
  2906. protected void doWriteDesign(Element design, DesignContext designContext) {
  2907. Attributes attr = design.attributes();
  2908. DesignAttributeHandler.writeAttribute("selection-allowed", attr,
  2909. isReadOnly(), false, Boolean.class, designContext);
  2910. Attributes attrs = design.attributes();
  2911. Grid<?> defaultInstance = designContext.getDefaultInstance(this);
  2912. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  2913. getFrozenColumnCount(), defaultInstance.getFrozenColumnCount(),
  2914. int.class, designContext);
  2915. if (HeightMode.ROW.equals(getHeightMode())) {
  2916. DesignAttributeHandler.writeAttribute("rows", attrs,
  2917. getHeightByRows(), defaultInstance.getHeightByRows(),
  2918. double.class, designContext);
  2919. }
  2920. SelectionMode mode = getSelectionMode();
  2921. if (mode != null) {
  2922. DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
  2923. SelectionMode.SINGLE, SelectionMode.class, designContext);
  2924. }
  2925. writeStructure(design, designContext);
  2926. }
  2927. @Override
  2928. protected T deserializeDeclarativeRepresentation(String item) {
  2929. if (item == null) {
  2930. return super.deserializeDeclarativeRepresentation(
  2931. new String(UUID.randomUUID().toString()));
  2932. }
  2933. return super.deserializeDeclarativeRepresentation(new String(item));
  2934. }
  2935. @Override
  2936. protected boolean isReadOnly() {
  2937. SelectionMode selectionMode = getSelectionMode();
  2938. if (SelectionMode.SINGLE.equals(selectionMode)) {
  2939. return asSingleSelect().isReadOnly();
  2940. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  2941. return asMultiSelect().isReadOnly();
  2942. }
  2943. return false;
  2944. }
  2945. @Override
  2946. protected void setReadOnly(boolean readOnly) {
  2947. SelectionMode selectionMode = getSelectionMode();
  2948. if (SelectionMode.SINGLE.equals(selectionMode)) {
  2949. asSingleSelect().setReadOnly(readOnly);
  2950. } else if (SelectionMode.MULTI.equals(selectionMode)) {
  2951. asMultiSelect().setReadOnly(readOnly);
  2952. }
  2953. }
  2954. private void readStructure(Element design, DesignContext context) {
  2955. if (design.children().isEmpty()) {
  2956. return;
  2957. }
  2958. if (design.children().size() > 1
  2959. || !design.child(0).tagName().equals("table")) {
  2960. throw new DesignException(
  2961. "Grid needs to have a table element as its only child");
  2962. }
  2963. Element table = design.child(0);
  2964. Elements colgroups = table.getElementsByTag("colgroup");
  2965. if (colgroups.size() != 1) {
  2966. throw new DesignException(
  2967. "Table element in declarative Grid needs to have a"
  2968. + " colgroup defining the columns used in Grid");
  2969. }
  2970. List<DeclarativeValueProvider<T>> providers = new ArrayList<>();
  2971. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  2972. String id = DesignAttributeHandler.readAttribute("column-id",
  2973. col.attributes(), null, String.class);
  2974. DeclarativeValueProvider<T> provider = new DeclarativeValueProvider<>();
  2975. Column<T, String> column = new Column<>(provider,
  2976. new HtmlRenderer());
  2977. addColumn(getGeneratedIdentifier(), column);
  2978. if (id != null) {
  2979. column.setId(id);
  2980. }
  2981. providers.add(provider);
  2982. column.readDesign(col, context);
  2983. }
  2984. for (Element child : table.children()) {
  2985. if (child.tagName().equals("thead")) {
  2986. getHeader().readDesign(child, context);
  2987. } else if (child.tagName().equals("tbody")) {
  2988. readData(child, providers);
  2989. } else if (child.tagName().equals("tfoot")) {
  2990. getFooter().readDesign(child, context);
  2991. }
  2992. }
  2993. }
  2994. private void readData(Element body,
  2995. List<DeclarativeValueProvider<T>> providers) {
  2996. getSelectionModel().deselectAll();
  2997. List<T> items = new ArrayList<>();
  2998. List<T> selectedItems = new ArrayList<>();
  2999. for (Element row : body.children()) {
  3000. T item = deserializeDeclarativeRepresentation(row.attr("item"));
  3001. items.add(item);
  3002. if (row.hasAttr("selected")) {
  3003. selectedItems.add(item);
  3004. }
  3005. Elements cells = row.children();
  3006. int i = 0;
  3007. for (Element cell : cells) {
  3008. providers.get(i).addValue(item, cell.html());
  3009. i++;
  3010. }
  3011. }
  3012. setItems(items);
  3013. selectedItems.forEach(getSelectionModel()::select);
  3014. }
  3015. private void writeStructure(Element design, DesignContext designContext) {
  3016. if (getColumns().isEmpty()) {
  3017. return;
  3018. }
  3019. Element tableElement = design.appendElement("table");
  3020. Element colGroup = tableElement.appendElement("colgroup");
  3021. getColumns().forEach(column -> column
  3022. .writeDesign(colGroup.appendElement("col"), designContext));
  3023. // Always write thead. Reads correctly when there no header rows
  3024. getHeader().writeDesign(tableElement.appendElement("thead"),
  3025. designContext);
  3026. if (designContext.shouldWriteData(this)) {
  3027. Element bodyElement = tableElement.appendElement("tbody");
  3028. getDataProvider().fetch(new Query<>()).forEach(
  3029. item -> writeRow(bodyElement, item, designContext));
  3030. }
  3031. if (getFooter().getRowCount() > 0) {
  3032. getFooter().writeDesign(tableElement.appendElement("tfoot"),
  3033. designContext);
  3034. }
  3035. }
  3036. private void writeRow(Element container, T item, DesignContext context) {
  3037. Element tableRow = container.appendElement("tr");
  3038. tableRow.attr("item", serializeDeclarativeRepresentation(item));
  3039. if (getSelectionModel().isSelected(item)) {
  3040. tableRow.attr("selected", "");
  3041. }
  3042. for (Column<T, ?> column : getColumns()) {
  3043. Object value = column.valueProvider.apply(item);
  3044. tableRow.appendElement("td")
  3045. .append(Optional.ofNullable(value).map(Object::toString)
  3046. .map(DesignFormatter::encodeForTextNode)
  3047. .orElse(""));
  3048. }
  3049. }
  3050. private SelectionMode getSelectionMode() {
  3051. GridSelectionModel<T> selectionModel = getSelectionModel();
  3052. SelectionMode mode = null;
  3053. if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
  3054. mode = SelectionMode.SINGLE;
  3055. } else if (selectionModel.getClass()
  3056. .equals(MultiSelectionModelImpl.class)) {
  3057. mode = SelectionMode.MULTI;
  3058. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  3059. mode = SelectionMode.NONE;
  3060. }
  3061. return mode;
  3062. }
  3063. /**
  3064. * Sets a user-defined identifier for given column.
  3065. *
  3066. * @see Column#setId(String)
  3067. *
  3068. * @param column
  3069. * the column
  3070. * @param id
  3071. * the user-defined identifier
  3072. */
  3073. protected void setColumnId(String id, Column<T, ?> column) {
  3074. if (columnIds.containsKey(id)) {
  3075. throw new IllegalArgumentException("Duplicate ID for columns");
  3076. }
  3077. columnIds.put(id, column);
  3078. }
  3079. @Override
  3080. protected Collection<String> getCustomAttributes() {
  3081. Collection<String> result = super.getCustomAttributes();
  3082. // "rename" for frozen column count
  3083. result.add("frozen-column-count");
  3084. result.add("frozen-columns");
  3085. // "rename" for height-mode
  3086. result.add("height-by-rows");
  3087. result.add("rows");
  3088. // add a selection-mode attribute
  3089. result.add("selection-mode");
  3090. return result;
  3091. }
  3092. /**
  3093. * Returns a column identified by its internal id. This id should not be
  3094. * confused with the user-defined identifier.
  3095. *
  3096. * @param columnId
  3097. * the internal id of column
  3098. * @return column identified by internal id
  3099. */
  3100. protected Column<T, ?> getColumnByInternalId(String columnId) {
  3101. return columnKeys.get(columnId);
  3102. }
  3103. /**
  3104. * Returns the internal id for given column. This id should not be confused
  3105. * with the user-defined identifier.
  3106. *
  3107. * @param column
  3108. * the column
  3109. * @return internal id of given column
  3110. */
  3111. protected String getInternalIdForColumn(Column<T, ?> column) {
  3112. return column.getInternalId();
  3113. }
  3114. private void setSortOrder(List<GridSortOrder<T>> order,
  3115. boolean userOriginated) {
  3116. Objects.requireNonNull(order, "Sort order list cannot be null");
  3117. sortOrder.clear();
  3118. if (order.isEmpty()) {
  3119. // Grid is not sorted anymore.
  3120. getDataCommunicator().setBackEndSorting(Collections.emptyList());
  3121. getDataCommunicator().setInMemorySorting(null);
  3122. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  3123. userOriginated));
  3124. return;
  3125. }
  3126. sortOrder.addAll(order);
  3127. sort(userOriginated);
  3128. }
  3129. private void sort(boolean userOriginated) {
  3130. // Set sort orders
  3131. // In-memory comparator
  3132. getDataCommunicator().setInMemorySorting(createSortingComparator());
  3133. // Back-end sort properties
  3134. List<QuerySortOrder> sortProperties = new ArrayList<>();
  3135. sortOrder.stream().map(
  3136. order -> order.getSorted().getSortOrder(order.getDirection()))
  3137. .forEach(s -> s.forEach(sortProperties::add));
  3138. getDataCommunicator().setBackEndSorting(sortProperties);
  3139. // Close grid editor if it's open.
  3140. if (getEditor().isOpen()) {
  3141. getEditor().cancel();
  3142. }
  3143. fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
  3144. userOriginated));
  3145. }
  3146. /**
  3147. * Creates a comparator for grid to sort rows.
  3148. *
  3149. * @return the comparator based on column sorting information.
  3150. */
  3151. protected SerializableComparator<T> createSortingComparator() {
  3152. BinaryOperator<SerializableComparator<T>> operator = (comparator1,
  3153. comparator2) -> SerializableComparator
  3154. .asInstance((Comparator<T> & Serializable) comparator1
  3155. .thenComparing(comparator2));
  3156. return sortOrder.stream().map(
  3157. order -> order.getSorted().getComparator(order.getDirection()))
  3158. .reduce((x, y) -> 0, operator);
  3159. }
  3160. }