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

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