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

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