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

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