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

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