You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Grid.java 170KB

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