Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Grid.java 163KB

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