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

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