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

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