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

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