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

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