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 169KB

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