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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178
  1. /*
  2. * Copyright 2000-2014 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.EnumSet;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.LinkedHashMap;
  29. import java.util.LinkedHashSet;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Map.Entry;
  34. import java.util.Set;
  35. import java.util.logging.Level;
  36. import java.util.logging.Logger;
  37. import org.jsoup.nodes.Attributes;
  38. import org.jsoup.nodes.Element;
  39. import org.jsoup.select.Elements;
  40. import com.google.gwt.thirdparty.guava.common.collect.Sets;
  41. import com.google.gwt.thirdparty.guava.common.collect.Sets.SetView;
  42. import com.vaadin.data.Container;
  43. import com.vaadin.data.Container.Indexed;
  44. import com.vaadin.data.Container.PropertySetChangeEvent;
  45. import com.vaadin.data.Container.PropertySetChangeListener;
  46. import com.vaadin.data.Container.PropertySetChangeNotifier;
  47. import com.vaadin.data.Container.Sortable;
  48. import com.vaadin.data.Item;
  49. import com.vaadin.data.Property;
  50. import com.vaadin.data.RpcDataProviderExtension;
  51. import com.vaadin.data.RpcDataProviderExtension.DataProviderKeyMapper;
  52. import com.vaadin.data.RpcDataProviderExtension.DetailComponentManager;
  53. import com.vaadin.data.Validator.InvalidValueException;
  54. import com.vaadin.data.fieldgroup.DefaultFieldGroupFieldFactory;
  55. import com.vaadin.data.fieldgroup.FieldGroup;
  56. import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
  57. import com.vaadin.data.fieldgroup.FieldGroupFieldFactory;
  58. import com.vaadin.data.sort.Sort;
  59. import com.vaadin.data.sort.SortOrder;
  60. import com.vaadin.data.util.IndexedContainer;
  61. import com.vaadin.data.util.converter.Converter;
  62. import com.vaadin.data.util.converter.ConverterUtil;
  63. import com.vaadin.event.ItemClickEvent;
  64. import com.vaadin.event.ItemClickEvent.ItemClickListener;
  65. import com.vaadin.event.ItemClickEvent.ItemClickNotifier;
  66. import com.vaadin.event.SelectionEvent;
  67. import com.vaadin.event.SelectionEvent.SelectionListener;
  68. import com.vaadin.event.SelectionEvent.SelectionNotifier;
  69. import com.vaadin.event.SortEvent;
  70. import com.vaadin.event.SortEvent.SortListener;
  71. import com.vaadin.event.SortEvent.SortNotifier;
  72. import com.vaadin.server.AbstractClientConnector;
  73. import com.vaadin.server.AbstractExtension;
  74. import com.vaadin.server.EncodeResult;
  75. import com.vaadin.server.ErrorMessage;
  76. import com.vaadin.server.JsonCodec;
  77. import com.vaadin.server.KeyMapper;
  78. import com.vaadin.server.VaadinSession;
  79. import com.vaadin.shared.MouseEventDetails;
  80. import com.vaadin.shared.data.sort.SortDirection;
  81. import com.vaadin.shared.ui.grid.EditorClientRpc;
  82. import com.vaadin.shared.ui.grid.EditorServerRpc;
  83. import com.vaadin.shared.ui.grid.GridClientRpc;
  84. import com.vaadin.shared.ui.grid.GridColumnState;
  85. import com.vaadin.shared.ui.grid.GridConstants;
  86. import com.vaadin.shared.ui.grid.GridServerRpc;
  87. import com.vaadin.shared.ui.grid.GridState;
  88. import com.vaadin.shared.ui.grid.GridState.SharedSelectionMode;
  89. import com.vaadin.shared.ui.grid.GridStaticCellType;
  90. import com.vaadin.shared.ui.grid.GridStaticSectionState;
  91. import com.vaadin.shared.ui.grid.GridStaticSectionState.CellState;
  92. import com.vaadin.shared.ui.grid.GridStaticSectionState.RowState;
  93. import com.vaadin.shared.ui.grid.HeightMode;
  94. import com.vaadin.shared.ui.grid.ScrollDestination;
  95. import com.vaadin.shared.util.SharedUtil;
  96. import com.vaadin.ui.declarative.DesignAttributeHandler;
  97. import com.vaadin.ui.declarative.DesignContext;
  98. import com.vaadin.ui.declarative.DesignException;
  99. import com.vaadin.ui.renderers.HtmlRenderer;
  100. import com.vaadin.ui.renderers.Renderer;
  101. import com.vaadin.ui.renderers.TextRenderer;
  102. import com.vaadin.util.ReflectTools;
  103. import elemental.json.Json;
  104. import elemental.json.JsonArray;
  105. import elemental.json.JsonObject;
  106. import elemental.json.JsonValue;
  107. /**
  108. * A grid component for displaying tabular data.
  109. * <p>
  110. * Grid is always bound to a {@link Container.Indexed}, but is not a
  111. * {@code Container} of any kind in of itself. The contents of the given
  112. * Container is displayed with the help of {@link Renderer Renderers}.
  113. *
  114. * <h3 id="grid-headers-and-footers">Headers and Footers</h3>
  115. * <p>
  116. *
  117. *
  118. * <h3 id="grid-converters-and-renderers">Converters and Renderers</h3>
  119. * <p>
  120. * Each column has its own {@link Renderer} that displays data into something
  121. * that can be displayed in the browser. That data is first converted with a
  122. * {@link com.vaadin.data.util.converter.Converter Converter} into something
  123. * that the Renderer can process. This can also be an implicit step - if a
  124. * column has a simple data type, like a String, no explicit assignment is
  125. * needed.
  126. * <p>
  127. * Usually a renderer takes some kind of object, and converts it into a
  128. * HTML-formatted string.
  129. * <p>
  130. * <code><pre>
  131. * Grid grid = new Grid(myContainer);
  132. * Column column = grid.getColumn(STRING_DATE_PROPERTY);
  133. * column.setConverter(new StringToDateConverter());
  134. * column.setRenderer(new MyColorfulDateRenderer());
  135. * </pre></code>
  136. *
  137. * <h3 id="grid-lazyloading">Lazy Loading</h3>
  138. * <p>
  139. * The data is accessed as it is needed by Grid and not any sooner. In other
  140. * words, if the given Container is huge, but only the first few rows are
  141. * displayed to the user, only those (and a few more, for caching purposes) are
  142. * accessed.
  143. *
  144. * <h3 id="grid-selection-modes-and-models">Selection Modes and Models</h3>
  145. * <p>
  146. * Grid supports three selection <em>{@link SelectionMode modes}</em> (single,
  147. * multi, none), and comes bundled with one
  148. * <em>{@link SelectionModel model}</em> for each of the modes. The distinction
  149. * between a selection mode and selection model is as follows: a <em>mode</em>
  150. * essentially says whether you can have one, many or no rows selected. The
  151. * model, however, has the behavioral details of each. A single selection model
  152. * may require that the user deselects one row before selecting another one. A
  153. * variant of a multiselect might have a configurable maximum of rows that may
  154. * be selected. And so on.
  155. * <p>
  156. * <code><pre>
  157. * Grid grid = new Grid(myContainer);
  158. *
  159. * // uses the bundled SingleSelectionModel class
  160. * grid.setSelectionMode(SelectionMode.SINGLE);
  161. *
  162. * // changes the behavior to a custom selection model
  163. * grid.setSelectionModel(new MyTwoSelectionModel());
  164. * </pre></code>
  165. *
  166. * @since 7.4
  167. * @author Vaadin Ltd
  168. */
  169. public class Grid extends AbstractComponent implements SelectionNotifier,
  170. SortNotifier, SelectiveRenderer, ItemClickNotifier {
  171. /**
  172. * An event listener for column visibility change events in the Grid.
  173. *
  174. * @since 7.5.0
  175. */
  176. public interface ColumnVisibilityChangeListener extends Serializable {
  177. /**
  178. * Called when a column has become hidden or unhidden.
  179. *
  180. * @param event
  181. */
  182. void columnVisibilityChanged(ColumnVisibilityChangeEvent event);
  183. }
  184. /**
  185. * An event that is fired when a column's visibility changes.
  186. *
  187. * @since 7.5.0
  188. */
  189. public static class ColumnVisibilityChangeEvent extends Component.Event {
  190. private final Column column;
  191. private final boolean userOriginated;
  192. private final boolean hidden;
  193. /**
  194. * Constructor for a column visibility change event.
  195. *
  196. * @param source
  197. * the grid from which this event originates
  198. * @param column
  199. * the column that changed its visibility
  200. * @param hidden
  201. * <code>true</code> if the column was hidden,
  202. * <code>false</code> if it became visible
  203. * @param isUserOriginated
  204. * <code>true</code> iff the event was triggered by an UI
  205. * interaction
  206. */
  207. public ColumnVisibilityChangeEvent(Grid source, Column column,
  208. boolean hidden, boolean isUserOriginated) {
  209. super(source);
  210. this.column = column;
  211. this.hidden = hidden;
  212. userOriginated = isUserOriginated;
  213. }
  214. /**
  215. * Gets the column that became hidden or visible.
  216. *
  217. * @return the column that became hidden or visible.
  218. * @see Column#isHidden()
  219. */
  220. public Column getColumn() {
  221. return column;
  222. }
  223. /**
  224. * Was the column set hidden or visible.
  225. *
  226. * @return <code>true</code> if the column was hidden <code>false</code>
  227. * if it was set visible
  228. */
  229. public boolean isHidden() {
  230. return hidden;
  231. }
  232. /**
  233. * Returns <code>true</code> if the column reorder was done by the user,
  234. * <code>false</code> if not and it was triggered by server side code.
  235. *
  236. * @return <code>true</code> if event is a result of user interaction
  237. */
  238. public boolean isUserOriginated() {
  239. return userOriginated;
  240. }
  241. }
  242. /**
  243. * A callback interface for generating details for a particular row in Grid.
  244. *
  245. * @since 7.5.0
  246. * @author Vaadin Ltd
  247. * @see DetailsGenerator#NULL
  248. */
  249. public interface DetailsGenerator extends Serializable {
  250. /** A details generator that provides no details */
  251. public DetailsGenerator NULL = new DetailsGenerator() {
  252. @Override
  253. public Component getDetails(RowReference rowReference) {
  254. return null;
  255. }
  256. };
  257. /**
  258. * This method is called for whenever a new details row needs to be
  259. * generated.
  260. * <p>
  261. * <em>Note:</em> If a component gets generated, it may not be manually
  262. * attached anywhere, nor may it be a reused instance &ndash; each
  263. * invocation of this method should produce a unique and isolated
  264. * component instance. Essentially, this should mostly be a
  265. * self-contained fire-and-forget method, as external references to the
  266. * generated component might cause unexpected behavior.
  267. *
  268. * @param rowReference
  269. * the reference for the row for which to generate details
  270. * @return the details for the given row, or <code>null</code> to leave
  271. * the details empty.
  272. */
  273. Component getDetails(RowReference rowReference);
  274. }
  275. /**
  276. * Custom field group that allows finding property types before an item has
  277. * been bound.
  278. */
  279. private final class CustomFieldGroup extends FieldGroup {
  280. public CustomFieldGroup() {
  281. setFieldFactory(EditorFieldFactory.get());
  282. }
  283. @Override
  284. protected Class<?> getPropertyType(Object propertyId)
  285. throws BindException {
  286. if (getItemDataSource() == null) {
  287. return datasource.getType(propertyId);
  288. } else {
  289. return super.getPropertyType(propertyId);
  290. }
  291. }
  292. }
  293. /**
  294. * Field factory used by default in the editor.
  295. *
  296. * Aims to fields of suitable type and with suitable size for use in the
  297. * editor row.
  298. */
  299. public static class EditorFieldFactory extends
  300. DefaultFieldGroupFieldFactory {
  301. private static final EditorFieldFactory INSTANCE = new EditorFieldFactory();
  302. protected EditorFieldFactory() {
  303. }
  304. /**
  305. * Returns the singleton instance
  306. *
  307. * @return the singleton instance
  308. */
  309. public static EditorFieldFactory get() {
  310. return INSTANCE;
  311. }
  312. @Override
  313. public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {
  314. T f = super.createField(type, fieldType);
  315. if (f != null) {
  316. f.setWidth("100%");
  317. }
  318. return f;
  319. }
  320. @Override
  321. protected AbstractSelect createCompatibleSelect(
  322. Class<? extends AbstractSelect> fieldType) {
  323. if (anySelect(fieldType)) {
  324. return super.createCompatibleSelect(ComboBox.class);
  325. }
  326. return super.createCompatibleSelect(fieldType);
  327. }
  328. @Override
  329. protected void populateWithEnumData(AbstractSelect select,
  330. Class<? extends Enum> enumClass) {
  331. // Use enums directly and the EnumToStringConverter to be consistent
  332. // with what is shown in the Grid
  333. @SuppressWarnings("unchecked")
  334. EnumSet<?> enumSet = EnumSet.allOf(enumClass);
  335. for (Object r : enumSet) {
  336. select.addItem(r);
  337. }
  338. }
  339. }
  340. /**
  341. * Error handler for the editor
  342. */
  343. public interface EditorErrorHandler extends Serializable {
  344. /**
  345. * Called when an exception occurs while the editor row is being saved
  346. *
  347. * @param event
  348. * An event providing more information about the error
  349. */
  350. void commitError(CommitErrorEvent event);
  351. }
  352. /**
  353. * An event which is fired when saving the editor fails
  354. */
  355. public static class CommitErrorEvent extends Component.Event {
  356. private CommitException cause;
  357. private Set<Column> errorColumns = new HashSet<Column>();
  358. private String userErrorMessage;
  359. public CommitErrorEvent(Grid grid, CommitException cause) {
  360. super(grid);
  361. this.cause = cause;
  362. userErrorMessage = cause.getLocalizedMessage();
  363. }
  364. /**
  365. * Retrieves the cause of the failure
  366. *
  367. * @return the cause of the failure
  368. */
  369. public CommitException getCause() {
  370. return cause;
  371. }
  372. @Override
  373. public Grid getComponent() {
  374. return (Grid) super.getComponent();
  375. }
  376. /**
  377. * Checks if validation exceptions caused this error
  378. *
  379. * @return true if the problem was caused by a validation error
  380. */
  381. public boolean isValidationFailure() {
  382. return cause.getCause() instanceof InvalidValueException;
  383. }
  384. /**
  385. * Marks that an error indicator should be shown for the editor of a
  386. * column.
  387. *
  388. * @param column
  389. * the column to show an error for
  390. */
  391. public void addErrorColumn(Column column) {
  392. errorColumns.add(column);
  393. }
  394. /**
  395. * Gets all the columns that have been marked as erroneous.
  396. *
  397. * @return an umodifiable collection of erroneous columns
  398. */
  399. public Collection<Column> getErrorColumns() {
  400. return Collections.unmodifiableCollection(errorColumns);
  401. }
  402. /**
  403. * Gets the error message to show to the user.
  404. *
  405. * @return error message to show
  406. */
  407. public String getUserErrorMessage() {
  408. return userErrorMessage;
  409. }
  410. /**
  411. * Sets the error message to show to the user.
  412. *
  413. * @param userErrorMessage
  414. * the user error message to set
  415. */
  416. public void setUserErrorMessage(String userErrorMessage) {
  417. this.userErrorMessage = userErrorMessage;
  418. }
  419. }
  420. /**
  421. * An event listener for column reorder events in the Grid.
  422. *
  423. * @since 7.5.0
  424. */
  425. public interface ColumnReorderListener extends Serializable {
  426. /**
  427. * Called when the columns of the grid have been reordered.
  428. *
  429. * @param event
  430. * An event providing more information
  431. */
  432. void columnReorder(ColumnReorderEvent event);
  433. }
  434. /**
  435. * An event that is fired when the columns are reordered.
  436. *
  437. * @since 7.5.0
  438. */
  439. public static class ColumnReorderEvent extends Component.Event {
  440. /**
  441. * Is the column reorder related to this event initiated by the user
  442. */
  443. private final boolean userOriginated;
  444. /**
  445. *
  446. * @param source
  447. * the grid where the event originated from
  448. * @param userOriginated
  449. * <code>true</code> if event is a result of user
  450. * interaction, <code>false</code> if from API call
  451. */
  452. public ColumnReorderEvent(Grid source, boolean userOriginated) {
  453. super(source);
  454. this.userOriginated = userOriginated;
  455. }
  456. /**
  457. * Returns <code>true</code> if the column reorder was done by the user,
  458. * <code>false</code> if not and it was triggered by server side code.
  459. *
  460. * @return <code>true</code> if event is a result of user interaction
  461. */
  462. public boolean isUserOriginated() {
  463. return userOriginated;
  464. }
  465. }
  466. /**
  467. * Default error handler for the editor
  468. *
  469. */
  470. public class DefaultEditorErrorHandler implements EditorErrorHandler {
  471. @Override
  472. public void commitError(CommitErrorEvent event) {
  473. Map<Field<?>, InvalidValueException> invalidFields = event
  474. .getCause().getInvalidFields();
  475. if (!invalidFields.isEmpty()) {
  476. Object firstErrorPropertyId = null;
  477. Field<?> firstErrorField = null;
  478. FieldGroup fieldGroup = event.getCause().getFieldGroup();
  479. for (Column column : getColumns()) {
  480. Object propertyId = column.getPropertyId();
  481. Field<?> field = fieldGroup.getField(propertyId);
  482. if (invalidFields.keySet().contains(field)) {
  483. event.addErrorColumn(column);
  484. if (firstErrorPropertyId == null) {
  485. firstErrorPropertyId = propertyId;
  486. firstErrorField = field;
  487. }
  488. }
  489. }
  490. /*
  491. * Validation error, show first failure as
  492. * "<Column header>: <message>"
  493. */
  494. String caption = getColumn(firstErrorPropertyId)
  495. .getHeaderCaption();
  496. String message = invalidFields.get(firstErrorField)
  497. .getLocalizedMessage();
  498. event.setUserErrorMessage(caption + ": " + message);
  499. } else {
  500. com.vaadin.server.ErrorEvent.findErrorHandler(Grid.this).error(
  501. new ConnectorErrorEvent(Grid.this, event.getCause()));
  502. }
  503. }
  504. private Object getFirstPropertyId(FieldGroup fieldGroup,
  505. Set<Field<?>> keySet) {
  506. for (Column c : getColumns()) {
  507. Object propertyId = c.getPropertyId();
  508. Field<?> f = fieldGroup.getField(propertyId);
  509. if (keySet.contains(f)) {
  510. return propertyId;
  511. }
  512. }
  513. return null;
  514. }
  515. }
  516. /**
  517. * Selection modes representing built-in {@link SelectionModel
  518. * SelectionModels} that come bundled with {@link Grid}.
  519. * <p>
  520. * Passing one of these enums into
  521. * {@link Grid#setSelectionMode(SelectionMode)} is equivalent to calling
  522. * {@link Grid#setSelectionModel(SelectionModel)} with one of the built-in
  523. * implementations of {@link SelectionModel}.
  524. *
  525. * @see Grid#setSelectionMode(SelectionMode)
  526. * @see Grid#setSelectionModel(SelectionModel)
  527. */
  528. public enum SelectionMode {
  529. /** A SelectionMode that maps to {@link SingleSelectionModel} */
  530. SINGLE {
  531. @Override
  532. protected SelectionModel createModel() {
  533. return new SingleSelectionModel();
  534. }
  535. },
  536. /** A SelectionMode that maps to {@link MultiSelectionModel} */
  537. MULTI {
  538. @Override
  539. protected SelectionModel createModel() {
  540. return new MultiSelectionModel();
  541. }
  542. },
  543. /** A SelectionMode that maps to {@link NoSelectionModel} */
  544. NONE {
  545. @Override
  546. protected SelectionModel createModel() {
  547. return new NoSelectionModel();
  548. }
  549. };
  550. protected abstract SelectionModel createModel();
  551. }
  552. /**
  553. * The server-side interface that controls Grid's selection state.
  554. */
  555. public interface SelectionModel extends Serializable {
  556. /**
  557. * Checks whether an item is selected or not.
  558. *
  559. * @param itemId
  560. * the item id to check for
  561. * @return <code>true</code> iff the item is selected
  562. */
  563. boolean isSelected(Object itemId);
  564. /**
  565. * Returns a collection of all the currently selected itemIds.
  566. *
  567. * @return a collection of all the currently selected itemIds
  568. */
  569. Collection<Object> getSelectedRows();
  570. /**
  571. * Injects the current {@link Grid} instance into the SelectionModel.
  572. * <p>
  573. * <em>Note:</em> This method should not be called manually.
  574. *
  575. * @param grid
  576. * the Grid in which the SelectionModel currently is, or
  577. * <code>null</code> when a selection model is being detached
  578. * from a Grid.
  579. */
  580. void setGrid(Grid grid);
  581. /**
  582. * Resets the SelectiomModel to an initial state.
  583. * <p>
  584. * Most often this means that the selection state is cleared, but
  585. * implementations are free to interpret the "initial state" as they
  586. * wish. Some, for example, may want to keep the first selected item as
  587. * selected.
  588. */
  589. void reset();
  590. /**
  591. * A SelectionModel that supports multiple selections to be made.
  592. * <p>
  593. * This interface has a contract of having the same behavior, no matter
  594. * how the selection model is interacted with. In other words, if
  595. * something is forbidden to do in e.g. the user interface, it must also
  596. * be forbidden to do in the server-side and client-side APIs.
  597. */
  598. public interface Multi extends SelectionModel {
  599. /**
  600. * Marks items as selected.
  601. * <p>
  602. * This method does not clear any previous selection state, only
  603. * adds to it.
  604. *
  605. * @param itemIds
  606. * the itemId(s) to mark as selected
  607. * @return <code>true</code> if the selection state changed.
  608. * <code>false</code> if all the given itemIds already were
  609. * selected
  610. * @throws IllegalArgumentException
  611. * if the <code>itemIds</code> varargs array is
  612. * <code>null</code> or given itemIds don't exist in the
  613. * container of Grid
  614. * @see #deselect(Object...)
  615. */
  616. boolean select(Object... itemIds) throws IllegalArgumentException;
  617. /**
  618. * Marks items as selected.
  619. * <p>
  620. * This method does not clear any previous selection state, only
  621. * adds to it.
  622. *
  623. * @param itemIds
  624. * the itemIds to mark as selected
  625. * @return <code>true</code> if the selection state changed.
  626. * <code>false</code> if all the given itemIds already were
  627. * selected
  628. * @throws IllegalArgumentException
  629. * if <code>itemIds</code> is <code>null</code> or given
  630. * itemIds don't exist in the container of Grid
  631. * @see #deselect(Collection)
  632. */
  633. boolean select(Collection<?> itemIds)
  634. throws IllegalArgumentException;
  635. /**
  636. * Marks items as deselected.
  637. *
  638. * @param itemIds
  639. * the itemId(s) to remove from being selected
  640. * @return <code>true</code> if the selection state changed.
  641. * <code>false</code> if none the given itemIds were
  642. * selected previously
  643. * @throws IllegalArgumentException
  644. * if the <code>itemIds</code> varargs array is
  645. * <code>null</code>
  646. * @see #select(Object...)
  647. */
  648. boolean deselect(Object... itemIds) throws IllegalArgumentException;
  649. /**
  650. * Marks items as deselected.
  651. *
  652. * @param itemIds
  653. * the itemId(s) to remove from being selected
  654. * @return <code>true</code> if the selection state changed.
  655. * <code>false</code> if none the given itemIds were
  656. * selected previously
  657. * @throws IllegalArgumentException
  658. * if <code>itemIds</code> is <code>null</code>
  659. * @see #select(Collection)
  660. */
  661. boolean deselect(Collection<?> itemIds)
  662. throws IllegalArgumentException;
  663. /**
  664. * Marks all the items in the current Container as selected
  665. *
  666. * @return <code>true</code> iff some items were previously not
  667. * selected
  668. * @see #deselectAll()
  669. */
  670. boolean selectAll();
  671. /**
  672. * Marks all the items in the current Container as deselected
  673. *
  674. * @return <code>true</code> iff some items were previously selected
  675. * @see #selectAll()
  676. */
  677. boolean deselectAll();
  678. /**
  679. * Marks items as selected while deselecting all items not in the
  680. * given Collection.
  681. *
  682. * @param itemIds
  683. * the itemIds to mark as selected
  684. * @return <code>true</code> if the selection state changed.
  685. * <code>false</code> if all the given itemIds already were
  686. * selected
  687. * @throws IllegalArgumentException
  688. * if <code>itemIds</code> is <code>null</code> or given
  689. * itemIds don't exist in the container of Grid
  690. */
  691. boolean setSelected(Collection<?> itemIds)
  692. throws IllegalArgumentException;
  693. /**
  694. * Marks items as selected while deselecting all items not in the
  695. * varargs array.
  696. *
  697. * @param itemIds
  698. * the itemIds to mark as selected
  699. * @return <code>true</code> if the selection state changed.
  700. * <code>false</code> if all the given itemIds already were
  701. * selected
  702. * @throws IllegalArgumentException
  703. * if the <code>itemIds</code> varargs array is
  704. * <code>null</code> or given itemIds don't exist in the
  705. * container of Grid
  706. */
  707. boolean setSelected(Object... itemIds)
  708. throws IllegalArgumentException;
  709. }
  710. /**
  711. * A SelectionModel that supports for only single rows to be selected at
  712. * a time.
  713. * <p>
  714. * This interface has a contract of having the same behavior, no matter
  715. * how the selection model is interacted with. In other words, if
  716. * something is forbidden to do in e.g. the user interface, it must also
  717. * be forbidden to do in the server-side and client-side APIs.
  718. */
  719. public interface Single extends SelectionModel {
  720. /**
  721. * Marks an item as selected.
  722. *
  723. * @param itemIds
  724. * the itemId to mark as selected; <code>null</code> for
  725. * deselect
  726. * @return <code>true</code> if the selection state changed.
  727. * <code>false</code> if the itemId already was selected
  728. * @throws IllegalStateException
  729. * if the selection was illegal. One such reason might
  730. * be that the given id was null, indicating a deselect,
  731. * but implementation doesn't allow deselecting.
  732. * re-selecting something
  733. * @throws IllegalArgumentException
  734. * if given itemId does not exist in the container of
  735. * Grid
  736. */
  737. boolean select(Object itemId) throws IllegalStateException,
  738. IllegalArgumentException;
  739. /**
  740. * Gets the item id of the currently selected item.
  741. *
  742. * @return the item id of the currently selected item, or
  743. * <code>null</code> if nothing is selected
  744. */
  745. Object getSelectedRow();
  746. /**
  747. * Sets whether it's allowed to deselect the selected row through
  748. * the UI. Deselection is allowed by default.
  749. *
  750. * @param deselectAllowed
  751. * <code>true</code> if the selected row can be
  752. * deselected without selecting another row instead;
  753. * otherwise <code>false</code>.
  754. */
  755. public void setDeselectAllowed(boolean deselectAllowed);
  756. /**
  757. * Sets whether it's allowed to deselect the selected row through
  758. * the UI.
  759. *
  760. * @return <code>true</code> if deselection is allowed; otherwise
  761. * <code>false</code>
  762. */
  763. public boolean isDeselectAllowed();
  764. }
  765. /**
  766. * A SelectionModel that does not allow for rows to be selected.
  767. * <p>
  768. * This interface has a contract of having the same behavior, no matter
  769. * how the selection model is interacted with. In other words, if the
  770. * developer is unable to select something programmatically, it is not
  771. * allowed for the end-user to select anything, either.
  772. */
  773. public interface None extends SelectionModel {
  774. /**
  775. * {@inheritDoc}
  776. *
  777. * @return always <code>false</code>.
  778. */
  779. @Override
  780. public boolean isSelected(Object itemId);
  781. /**
  782. * {@inheritDoc}
  783. *
  784. * @return always an empty collection.
  785. */
  786. @Override
  787. public Collection<Object> getSelectedRows();
  788. }
  789. }
  790. /**
  791. * A base class for SelectionModels that contains some of the logic that is
  792. * reusable.
  793. */
  794. public static abstract class AbstractSelectionModel implements
  795. SelectionModel {
  796. protected final LinkedHashSet<Object> selection = new LinkedHashSet<Object>();
  797. protected Grid grid = null;
  798. @Override
  799. public boolean isSelected(final Object itemId) {
  800. return selection.contains(itemId);
  801. }
  802. @Override
  803. public Collection<Object> getSelectedRows() {
  804. return new ArrayList<Object>(selection);
  805. }
  806. @Override
  807. public void setGrid(final Grid grid) {
  808. this.grid = grid;
  809. }
  810. /**
  811. * Sanity check for existence of item id.
  812. *
  813. * @param itemId
  814. * item id to be selected / deselected
  815. *
  816. * @throws IllegalArgumentException
  817. * if item Id doesn't exist in the container of Grid
  818. */
  819. protected void checkItemIdExists(Object itemId)
  820. throws IllegalArgumentException {
  821. if (!grid.getContainerDataSource().containsId(itemId)) {
  822. throw new IllegalArgumentException("Given item id (" + itemId
  823. + ") does not exist in the container");
  824. }
  825. }
  826. /**
  827. * Sanity check for existence of item ids in given collection.
  828. *
  829. * @param itemIds
  830. * item id collection to be selected / deselected
  831. *
  832. * @throws IllegalArgumentException
  833. * if at least one item id doesn't exist in the container of
  834. * Grid
  835. */
  836. protected void checkItemIdsExist(Collection<?> itemIds)
  837. throws IllegalArgumentException {
  838. for (Object itemId : itemIds) {
  839. checkItemIdExists(itemId);
  840. }
  841. }
  842. /**
  843. * Fires a {@link SelectionEvent} to all the {@link SelectionListener
  844. * SelectionListeners} currently added to the Grid in which this
  845. * SelectionModel is.
  846. * <p>
  847. * Note that this is only a helper method, and routes the call all the
  848. * way to Grid. A {@link SelectionModel} is not a
  849. * {@link SelectionNotifier}
  850. *
  851. * @param oldSelection
  852. * the complete {@link Collection} of the itemIds that were
  853. * selected <em>before</em> this event happened
  854. * @param newSelection
  855. * the complete {@link Collection} of the itemIds that are
  856. * selected <em>after</em> this event happened
  857. */
  858. protected void fireSelectionEvent(
  859. final Collection<Object> oldSelection,
  860. final Collection<Object> newSelection) {
  861. grid.fireSelectionEvent(oldSelection, newSelection);
  862. }
  863. }
  864. /**
  865. * A default implementation of a {@link SelectionModel.Single}
  866. */
  867. public static class SingleSelectionModel extends AbstractSelectionModel
  868. implements SelectionModel.Single {
  869. @Override
  870. public boolean select(final Object itemId) {
  871. if (itemId == null) {
  872. return deselect(getSelectedRow());
  873. }
  874. checkItemIdExists(itemId);
  875. final Object selectedRow = getSelectedRow();
  876. final boolean modified = selection.add(itemId);
  877. if (modified) {
  878. final Collection<Object> deselected;
  879. if (selectedRow != null) {
  880. deselectInternal(selectedRow, false);
  881. deselected = Collections.singleton(selectedRow);
  882. } else {
  883. deselected = Collections.emptySet();
  884. }
  885. fireSelectionEvent(deselected, selection);
  886. }
  887. return modified;
  888. }
  889. private boolean deselect(final Object itemId) {
  890. return deselectInternal(itemId, true);
  891. }
  892. private boolean deselectInternal(final Object itemId,
  893. boolean fireEventIfNeeded) {
  894. final boolean modified = selection.remove(itemId);
  895. if (fireEventIfNeeded && modified) {
  896. fireSelectionEvent(Collections.singleton(itemId),
  897. Collections.emptySet());
  898. }
  899. return modified;
  900. }
  901. @Override
  902. public Object getSelectedRow() {
  903. if (selection.isEmpty()) {
  904. return null;
  905. } else {
  906. return selection.iterator().next();
  907. }
  908. }
  909. /**
  910. * Resets the selection state.
  911. * <p>
  912. * If an item is selected, it will become deselected.
  913. */
  914. @Override
  915. public void reset() {
  916. deselect(getSelectedRow());
  917. }
  918. @Override
  919. public void setDeselectAllowed(boolean deselectAllowed) {
  920. grid.getState().singleSelectDeselectAllowed = deselectAllowed;
  921. }
  922. @Override
  923. public boolean isDeselectAllowed() {
  924. return grid.getState(false).singleSelectDeselectAllowed;
  925. }
  926. }
  927. /**
  928. * A default implementation for a {@link SelectionModel.None}
  929. */
  930. public static class NoSelectionModel implements SelectionModel.None {
  931. @Override
  932. public void setGrid(final Grid grid) {
  933. // NOOP, not needed for anything
  934. }
  935. @Override
  936. public boolean isSelected(final Object itemId) {
  937. return false;
  938. }
  939. @Override
  940. public Collection<Object> getSelectedRows() {
  941. return Collections.emptyList();
  942. }
  943. /**
  944. * Semantically resets the selection model.
  945. * <p>
  946. * Effectively a no-op.
  947. */
  948. @Override
  949. public void reset() {
  950. // NOOP
  951. }
  952. }
  953. /**
  954. * A default implementation of a {@link SelectionModel.Multi}
  955. */
  956. public static class MultiSelectionModel extends AbstractSelectionModel
  957. implements SelectionModel.Multi {
  958. /**
  959. * The default selection size limit.
  960. *
  961. * @see #setSelectionLimit(int)
  962. */
  963. public static final int DEFAULT_MAX_SELECTIONS = 1000;
  964. private int selectionLimit = DEFAULT_MAX_SELECTIONS;
  965. @Override
  966. public boolean select(final Object... itemIds)
  967. throws IllegalArgumentException {
  968. if (itemIds != null) {
  969. // select will fire the event
  970. return select(Arrays.asList(itemIds));
  971. } else {
  972. throw new IllegalArgumentException(
  973. "Vararg array of itemIds may not be null");
  974. }
  975. }
  976. /**
  977. * {@inheritDoc}
  978. * <p>
  979. * All items might not be selected if the limit set using
  980. * {@link #setSelectionLimit(int)} is exceeded.
  981. */
  982. @Override
  983. public boolean select(final Collection<?> itemIds)
  984. throws IllegalArgumentException {
  985. if (itemIds == null) {
  986. throw new IllegalArgumentException("itemIds may not be null");
  987. }
  988. // Sanity check
  989. checkItemIdsExist(itemIds);
  990. final boolean selectionWillChange = !selection.containsAll(itemIds)
  991. && selection.size() < selectionLimit;
  992. if (selectionWillChange) {
  993. final HashSet<Object> oldSelection = new HashSet<Object>(
  994. selection);
  995. if (selection.size() + itemIds.size() >= selectionLimit) {
  996. // Add one at a time if there's a risk of overflow
  997. Iterator<?> iterator = itemIds.iterator();
  998. while (iterator.hasNext()
  999. && selection.size() < selectionLimit) {
  1000. selection.add(iterator.next());
  1001. }
  1002. } else {
  1003. selection.addAll(itemIds);
  1004. }
  1005. fireSelectionEvent(oldSelection, selection);
  1006. }
  1007. return selectionWillChange;
  1008. }
  1009. /**
  1010. * Sets the maximum number of rows that can be selected at once. This is
  1011. * a mechanism to prevent exhausting server memory in situations where
  1012. * users select lots of rows. If the limit is reached, newly selected
  1013. * rows will not become recorded.
  1014. * <p>
  1015. * Old selections are not discarded if the current number of selected
  1016. * row exceeds the new limit.
  1017. * <p>
  1018. * The default limit is {@value #DEFAULT_MAX_SELECTIONS} rows.
  1019. *
  1020. * @param selectionLimit
  1021. * the non-negative selection limit to set
  1022. * @throws IllegalArgumentException
  1023. * if the limit is negative
  1024. */
  1025. public void setSelectionLimit(int selectionLimit) {
  1026. if (selectionLimit < 0) {
  1027. throw new IllegalArgumentException(
  1028. "The selection limit must be non-negative");
  1029. }
  1030. this.selectionLimit = selectionLimit;
  1031. }
  1032. /**
  1033. * Gets the selection limit.
  1034. *
  1035. * @see #setSelectionLimit(int)
  1036. *
  1037. * @return the selection limit
  1038. */
  1039. public int getSelectionLimit() {
  1040. return selectionLimit;
  1041. }
  1042. @Override
  1043. public boolean deselect(final Object... itemIds)
  1044. throws IllegalArgumentException {
  1045. if (itemIds != null) {
  1046. // deselect will fire the event
  1047. return deselect(Arrays.asList(itemIds));
  1048. } else {
  1049. throw new IllegalArgumentException(
  1050. "Vararg array of itemIds may not be null");
  1051. }
  1052. }
  1053. @Override
  1054. public boolean deselect(final Collection<?> itemIds)
  1055. throws IllegalArgumentException {
  1056. if (itemIds == null) {
  1057. throw new IllegalArgumentException("itemIds may not be null");
  1058. }
  1059. final boolean hasCommonElements = !Collections.disjoint(itemIds,
  1060. selection);
  1061. if (hasCommonElements) {
  1062. final HashSet<Object> oldSelection = new HashSet<Object>(
  1063. selection);
  1064. selection.removeAll(itemIds);
  1065. fireSelectionEvent(oldSelection, selection);
  1066. }
  1067. return hasCommonElements;
  1068. }
  1069. @Override
  1070. public boolean selectAll() {
  1071. // select will fire the event
  1072. final Indexed container = grid.getContainerDataSource();
  1073. if (container != null) {
  1074. return select(container.getItemIds());
  1075. } else if (selection.isEmpty()) {
  1076. return false;
  1077. } else {
  1078. /*
  1079. * this should never happen (no container but has a selection),
  1080. * but I guess the only theoretically correct course of
  1081. * action...
  1082. */
  1083. return deselectAll();
  1084. }
  1085. }
  1086. @Override
  1087. public boolean deselectAll() {
  1088. // deselect will fire the event
  1089. return deselect(getSelectedRows());
  1090. }
  1091. /**
  1092. * {@inheritDoc}
  1093. * <p>
  1094. * The returned Collection is in <strong>order of selection</strong>
  1095. * &ndash; the item that was first selected will be first in the
  1096. * collection, and so on. Should an item have been selected twice
  1097. * without being deselected in between, it will have remained in its
  1098. * original position.
  1099. */
  1100. @Override
  1101. public Collection<Object> getSelectedRows() {
  1102. // overridden only for JavaDoc
  1103. return super.getSelectedRows();
  1104. }
  1105. /**
  1106. * Resets the selection model.
  1107. * <p>
  1108. * Equivalent to calling {@link #deselectAll()}
  1109. */
  1110. @Override
  1111. public void reset() {
  1112. deselectAll();
  1113. }
  1114. @Override
  1115. public boolean setSelected(Collection<?> itemIds)
  1116. throws IllegalArgumentException {
  1117. if (itemIds == null) {
  1118. throw new IllegalArgumentException("itemIds may not be null");
  1119. }
  1120. checkItemIdsExist(itemIds);
  1121. boolean changed = false;
  1122. Set<Object> selectedRows = new HashSet<Object>(itemIds);
  1123. final Collection<Object> oldSelection = getSelectedRows();
  1124. SetView<?> added = Sets.difference(selectedRows, selection);
  1125. if (!added.isEmpty()) {
  1126. changed = true;
  1127. selection.addAll(added.immutableCopy());
  1128. }
  1129. SetView<?> removed = Sets.difference(selection, selectedRows);
  1130. if (!removed.isEmpty()) {
  1131. changed = true;
  1132. selection.removeAll(removed.immutableCopy());
  1133. }
  1134. if (changed) {
  1135. fireSelectionEvent(oldSelection, selection);
  1136. }
  1137. return changed;
  1138. }
  1139. @Override
  1140. public boolean setSelected(Object... itemIds)
  1141. throws IllegalArgumentException {
  1142. if (itemIds != null) {
  1143. return setSelected(Arrays.asList(itemIds));
  1144. } else {
  1145. throw new IllegalArgumentException(
  1146. "Vararg array of itemIds may not be null");
  1147. }
  1148. }
  1149. }
  1150. /**
  1151. * A data class which contains information which identifies a row in a
  1152. * {@link Grid}.
  1153. * <p>
  1154. * Since this class follows the <code>Flyweight</code>-pattern any instance
  1155. * of this object is subject to change without the user knowing it and so
  1156. * should not be stored anywhere outside of the method providing these
  1157. * instances.
  1158. */
  1159. public static class RowReference implements Serializable {
  1160. private final Grid grid;
  1161. private Object itemId;
  1162. /**
  1163. * Creates a new row reference for the given grid.
  1164. *
  1165. * @param grid
  1166. * the grid that the row belongs to
  1167. */
  1168. public RowReference(Grid grid) {
  1169. this.grid = grid;
  1170. }
  1171. /**
  1172. * Sets the identifying information for this row
  1173. *
  1174. * @param itemId
  1175. * the item id of the row
  1176. */
  1177. public void set(Object itemId) {
  1178. this.itemId = itemId;
  1179. }
  1180. /**
  1181. * Gets the grid that contains the referenced row.
  1182. *
  1183. * @return the grid that contains referenced row
  1184. */
  1185. public Grid getGrid() {
  1186. return grid;
  1187. }
  1188. /**
  1189. * Gets the item id of the row.
  1190. *
  1191. * @return the item id of the row
  1192. */
  1193. public Object getItemId() {
  1194. return itemId;
  1195. }
  1196. /**
  1197. * Gets the item for the row.
  1198. *
  1199. * @return the item for the row
  1200. */
  1201. public Item getItem() {
  1202. return grid.getContainerDataSource().getItem(itemId);
  1203. }
  1204. }
  1205. /**
  1206. * A data class which contains information which identifies a cell in a
  1207. * {@link Grid}.
  1208. * <p>
  1209. * Since this class follows the <code>Flyweight</code>-pattern any instance
  1210. * of this object is subject to change without the user knowing it and so
  1211. * should not be stored anywhere outside of the method providing these
  1212. * instances.
  1213. */
  1214. public static class CellReference implements Serializable {
  1215. private final RowReference rowReference;
  1216. private Object propertyId;
  1217. public CellReference(RowReference rowReference) {
  1218. this.rowReference = rowReference;
  1219. }
  1220. /**
  1221. * Sets the identifying information for this cell
  1222. *
  1223. * @param propertyId
  1224. * the property id of the column
  1225. */
  1226. public void set(Object propertyId) {
  1227. this.propertyId = propertyId;
  1228. }
  1229. /**
  1230. * Gets the grid that contains the referenced cell.
  1231. *
  1232. * @return the grid that contains referenced cell
  1233. */
  1234. public Grid getGrid() {
  1235. return rowReference.getGrid();
  1236. }
  1237. /**
  1238. * @return the property id of the column
  1239. */
  1240. public Object getPropertyId() {
  1241. return propertyId;
  1242. }
  1243. /**
  1244. * @return the property for the cell
  1245. */
  1246. public Property<?> getProperty() {
  1247. return getItem().getItemProperty(propertyId);
  1248. }
  1249. /**
  1250. * Gets the item id of the row of the cell.
  1251. *
  1252. * @return the item id of the row
  1253. */
  1254. public Object getItemId() {
  1255. return rowReference.getItemId();
  1256. }
  1257. /**
  1258. * Gets the item for the row of the cell.
  1259. *
  1260. * @return the item for the row
  1261. */
  1262. public Item getItem() {
  1263. return rowReference.getItem();
  1264. }
  1265. /**
  1266. * Gets the value of the cell.
  1267. *
  1268. * @return the value of the cell
  1269. */
  1270. public Object getValue() {
  1271. return getProperty().getValue();
  1272. }
  1273. }
  1274. /**
  1275. * Callback interface for generating custom style names for data rows
  1276. *
  1277. * @see Grid#setRowStyleGenerator(RowStyleGenerator)
  1278. */
  1279. public interface RowStyleGenerator extends Serializable {
  1280. /**
  1281. * Called by Grid to generate a style name for a row
  1282. *
  1283. * @param rowReference
  1284. * The row to generate a style for
  1285. * @return the style name to add to this row, or {@code null} to not set
  1286. * any style
  1287. */
  1288. public String getStyle(RowReference rowReference);
  1289. }
  1290. /**
  1291. * Callback interface for generating custom style names for cells
  1292. *
  1293. * @see Grid#setCellStyleGenerator(CellStyleGenerator)
  1294. */
  1295. public interface CellStyleGenerator extends Serializable {
  1296. /**
  1297. * Called by Grid to generate a style name for a column
  1298. *
  1299. * @param cellReference
  1300. * The cell to generate a style for
  1301. * @return the style name to add to this cell, or {@code null} to not
  1302. * set any style
  1303. */
  1304. public String getStyle(CellReference cellReference);
  1305. }
  1306. /**
  1307. * Abstract base class for Grid header and footer sections.
  1308. *
  1309. * @param <ROWTYPE>
  1310. * the type of the rows in the section
  1311. */
  1312. abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>>
  1313. implements Serializable {
  1314. /**
  1315. * Abstract base class for Grid header and footer rows.
  1316. *
  1317. * @param <CELLTYPE>
  1318. * the type of the cells in the row
  1319. */
  1320. abstract static class StaticRow<CELLTYPE extends StaticCell> implements
  1321. Serializable {
  1322. private RowState rowState = new RowState();
  1323. protected StaticSection<?> section;
  1324. private Map<Object, CELLTYPE> cells = new LinkedHashMap<Object, CELLTYPE>();
  1325. private Map<Set<CELLTYPE>, CELLTYPE> cellGroups = new HashMap<Set<CELLTYPE>, CELLTYPE>();
  1326. protected StaticRow(StaticSection<?> section) {
  1327. this.section = section;
  1328. }
  1329. protected void addCell(Object propertyId) {
  1330. CELLTYPE cell = createCell();
  1331. cell.setColumnId(section.grid.getColumn(propertyId).getState().id);
  1332. cells.put(propertyId, cell);
  1333. rowState.cells.add(cell.getCellState());
  1334. }
  1335. protected void removeCell(Object propertyId) {
  1336. CELLTYPE cell = cells.remove(propertyId);
  1337. if (cell != null) {
  1338. Set<CELLTYPE> cellGroupForCell = getCellGroupForCell(cell);
  1339. if (cellGroupForCell != null) {
  1340. removeCellFromGroup(cell, cellGroupForCell);
  1341. }
  1342. rowState.cells.remove(cell.getCellState());
  1343. }
  1344. }
  1345. private void removeCellFromGroup(CELLTYPE cell,
  1346. Set<CELLTYPE> cellGroup) {
  1347. String columnId = cell.getColumnId();
  1348. for (Set<String> group : rowState.cellGroups.keySet()) {
  1349. if (group.contains(columnId)) {
  1350. if (group.size() > 2) {
  1351. // Update map key correctly
  1352. CELLTYPE mergedCell = cellGroups.remove(cellGroup);
  1353. cellGroup.remove(cell);
  1354. cellGroups.put(cellGroup, mergedCell);
  1355. group.remove(columnId);
  1356. } else {
  1357. rowState.cellGroups.remove(group);
  1358. cellGroups.remove(cellGroup);
  1359. }
  1360. return;
  1361. }
  1362. }
  1363. }
  1364. /**
  1365. * Creates and returns a new instance of the cell type.
  1366. *
  1367. * @return the created cell
  1368. */
  1369. protected abstract CELLTYPE createCell();
  1370. protected RowState getRowState() {
  1371. return rowState;
  1372. }
  1373. /**
  1374. * Returns the cell for the given property id on this row. If the
  1375. * column is merged returned cell is the cell for the whole group.
  1376. *
  1377. * @param propertyId
  1378. * the property id of the column
  1379. * @return the cell for the given property, merged cell for merged
  1380. * properties, null if not found
  1381. */
  1382. public CELLTYPE getCell(Object propertyId) {
  1383. CELLTYPE cell = cells.get(propertyId);
  1384. Set<CELLTYPE> cellGroup = getCellGroupForCell(cell);
  1385. if (cellGroup != null) {
  1386. cell = cellGroups.get(cellGroup);
  1387. }
  1388. return cell;
  1389. }
  1390. /**
  1391. * Merges columns cells in a row
  1392. *
  1393. * @param propertyIds
  1394. * The property ids of columns to merge
  1395. * @return The remaining visible cell after the merge
  1396. */
  1397. public CELLTYPE join(Object... propertyIds) {
  1398. assert propertyIds.length > 1 : "You need to merge at least 2 properties";
  1399. Set<CELLTYPE> cells = new HashSet<CELLTYPE>();
  1400. for (int i = 0; i < propertyIds.length; ++i) {
  1401. cells.add(getCell(propertyIds[i]));
  1402. }
  1403. return join(cells);
  1404. }
  1405. /**
  1406. * Merges columns cells in a row
  1407. *
  1408. * @param cells
  1409. * The cells to merge. Must be from the same row.
  1410. * @return The remaining visible cell after the merge
  1411. */
  1412. public CELLTYPE join(CELLTYPE... cells) {
  1413. assert cells.length > 1 : "You need to merge at least 2 cells";
  1414. return join(new HashSet<CELLTYPE>(Arrays.asList(cells)));
  1415. }
  1416. protected CELLTYPE join(Set<CELLTYPE> cells) {
  1417. for (CELLTYPE cell : cells) {
  1418. if (getCellGroupForCell(cell) != null) {
  1419. throw new IllegalArgumentException(
  1420. "Cell already merged");
  1421. } else if (!this.cells.containsValue(cell)) {
  1422. throw new IllegalArgumentException(
  1423. "Cell does not exist on this row");
  1424. }
  1425. }
  1426. // Create new cell data for the group
  1427. CELLTYPE newCell = createCell();
  1428. Set<String> columnGroup = new HashSet<String>();
  1429. for (CELLTYPE cell : cells) {
  1430. columnGroup.add(cell.getColumnId());
  1431. }
  1432. rowState.cellGroups.put(columnGroup, newCell.getCellState());
  1433. cellGroups.put(cells, newCell);
  1434. return newCell;
  1435. }
  1436. private Set<CELLTYPE> getCellGroupForCell(CELLTYPE cell) {
  1437. for (Set<CELLTYPE> group : cellGroups.keySet()) {
  1438. if (group.contains(cell)) {
  1439. return group;
  1440. }
  1441. }
  1442. return null;
  1443. }
  1444. /**
  1445. * Returns the custom style name for this row.
  1446. *
  1447. * @return the style name or null if no style name has been set
  1448. */
  1449. public String getStyleName() {
  1450. return getRowState().styleName;
  1451. }
  1452. /**
  1453. * Sets a custom style name for this row.
  1454. *
  1455. * @param styleName
  1456. * the style name to set or null to not use any style
  1457. * name
  1458. */
  1459. public void setStyleName(String styleName) {
  1460. getRowState().styleName = styleName;
  1461. }
  1462. /**
  1463. * Writes the declarative design to the given table row element.
  1464. *
  1465. * @since 7.5.0
  1466. * @param trElement
  1467. * Element to write design to
  1468. * @param designContext
  1469. * the design context
  1470. */
  1471. protected void writeDesign(Element trElement,
  1472. DesignContext designContext) {
  1473. Set<CELLTYPE> visited = new HashSet<CELLTYPE>();
  1474. for (Grid.Column column : section.grid.getColumns()) {
  1475. CELLTYPE cell = getCell(column.getPropertyId());
  1476. if (visited.contains(cell)) {
  1477. continue;
  1478. }
  1479. visited.add(cell);
  1480. Element cellElement = trElement
  1481. .appendElement(getCellTagName());
  1482. cell.writeDesign(cellElement, designContext);
  1483. for (Entry<Set<CELLTYPE>, CELLTYPE> entry : cellGroups
  1484. .entrySet()) {
  1485. if (entry.getValue() == cell) {
  1486. cellElement.attr("colspan", ""
  1487. + entry.getKey().size());
  1488. break;
  1489. }
  1490. }
  1491. }
  1492. }
  1493. /**
  1494. * Reads the declarative design from the given table row element.
  1495. *
  1496. * @since 7.5.0
  1497. * @param trElement
  1498. * Element to read design from
  1499. * @param designContext
  1500. * the design context
  1501. * @throws DesignException
  1502. * if the given table row contains unexpected children
  1503. */
  1504. protected void readDesign(Element trElement,
  1505. DesignContext designContext) throws DesignException {
  1506. Elements cellElements = trElement.children();
  1507. int totalColSpans = 0;
  1508. for (int i = 0; i < cellElements.size(); ++i) {
  1509. Element element = cellElements.get(i);
  1510. if (!element.tagName().equals(getCellTagName())) {
  1511. throw new DesignException(
  1512. "Unexpected element in tr while expecting "
  1513. + getCellTagName() + ": "
  1514. + element.tagName());
  1515. }
  1516. int columnIndex = i + totalColSpans;
  1517. int colspan = DesignAttributeHandler.readAttribute(
  1518. "colspan", element.attributes(), 1, int.class);
  1519. Set<CELLTYPE> cells = new HashSet<CELLTYPE>();
  1520. for (int c = 0; c < colspan; ++c) {
  1521. cells.add(getCell(section.grid.getColumns()
  1522. .get(columnIndex + c).getPropertyId()));
  1523. }
  1524. if (colspan > 1) {
  1525. totalColSpans += colspan - 1;
  1526. join(cells).readDesign(element, designContext);
  1527. } else {
  1528. cells.iterator().next()
  1529. .readDesign(element, designContext);
  1530. }
  1531. }
  1532. }
  1533. abstract protected String getCellTagName();
  1534. }
  1535. /**
  1536. * A header or footer cell. Has a simple textual caption.
  1537. */
  1538. abstract static class StaticCell implements Serializable {
  1539. private CellState cellState = new CellState();
  1540. private StaticRow<?> row;
  1541. protected StaticCell(StaticRow<?> row) {
  1542. this.row = row;
  1543. }
  1544. void setColumnId(String id) {
  1545. cellState.columnId = id;
  1546. }
  1547. String getColumnId() {
  1548. return cellState.columnId;
  1549. }
  1550. /**
  1551. * Gets the row where this cell is.
  1552. *
  1553. * @return row for this cell
  1554. */
  1555. public StaticRow<?> getRow() {
  1556. return row;
  1557. }
  1558. protected CellState getCellState() {
  1559. return cellState;
  1560. }
  1561. /**
  1562. * Sets the text displayed in this cell.
  1563. *
  1564. * @param text
  1565. * a plain text caption
  1566. */
  1567. public void setText(String text) {
  1568. removeComponentIfPresent();
  1569. cellState.text = text;
  1570. cellState.type = GridStaticCellType.TEXT;
  1571. row.section.markAsDirty();
  1572. }
  1573. /**
  1574. * Returns the text displayed in this cell.
  1575. *
  1576. * @return the plain text caption
  1577. */
  1578. public String getText() {
  1579. if (cellState.type != GridStaticCellType.TEXT) {
  1580. throw new IllegalStateException(
  1581. "Cannot fetch Text from a cell with type "
  1582. + cellState.type);
  1583. }
  1584. return cellState.text;
  1585. }
  1586. /**
  1587. * Returns the HTML content displayed in this cell.
  1588. *
  1589. * @return the html
  1590. *
  1591. */
  1592. public String getHtml() {
  1593. if (cellState.type != GridStaticCellType.HTML) {
  1594. throw new IllegalStateException(
  1595. "Cannot fetch HTML from a cell with type "
  1596. + cellState.type);
  1597. }
  1598. return cellState.html;
  1599. }
  1600. /**
  1601. * Sets the HTML content displayed in this cell.
  1602. *
  1603. * @param html
  1604. * the html to set
  1605. */
  1606. public void setHtml(String html) {
  1607. removeComponentIfPresent();
  1608. cellState.html = html;
  1609. cellState.type = GridStaticCellType.HTML;
  1610. row.section.markAsDirty();
  1611. }
  1612. /**
  1613. * Returns the component displayed in this cell.
  1614. *
  1615. * @return the component
  1616. */
  1617. public Component getComponent() {
  1618. if (cellState.type != GridStaticCellType.WIDGET) {
  1619. throw new IllegalStateException(
  1620. "Cannot fetch Component from a cell with type "
  1621. + cellState.type);
  1622. }
  1623. return (Component) cellState.connector;
  1624. }
  1625. /**
  1626. * Sets the component displayed in this cell.
  1627. *
  1628. * @param component
  1629. * the component to set
  1630. */
  1631. public void setComponent(Component component) {
  1632. removeComponentIfPresent();
  1633. component.setParent(row.section.grid);
  1634. cellState.connector = component;
  1635. cellState.type = GridStaticCellType.WIDGET;
  1636. row.section.markAsDirty();
  1637. }
  1638. /**
  1639. * Returns the type of content stored in this cell.
  1640. *
  1641. * @return cell content type
  1642. */
  1643. public GridStaticCellType getCellType() {
  1644. return cellState.type;
  1645. }
  1646. /**
  1647. * Returns the custom style name for this cell.
  1648. *
  1649. * @return the style name or null if no style name has been set
  1650. */
  1651. public String getStyleName() {
  1652. return cellState.styleName;
  1653. }
  1654. /**
  1655. * Sets a custom style name for this cell.
  1656. *
  1657. * @param styleName
  1658. * the style name to set or null to not use any style
  1659. * name
  1660. */
  1661. public void setStyleName(String styleName) {
  1662. cellState.styleName = styleName;
  1663. row.section.markAsDirty();
  1664. }
  1665. private void removeComponentIfPresent() {
  1666. Component component = (Component) cellState.connector;
  1667. if (component != null) {
  1668. component.setParent(null);
  1669. cellState.connector = null;
  1670. }
  1671. }
  1672. /**
  1673. * Writes the declarative design to the given table cell element.
  1674. *
  1675. * @since 7.5.0
  1676. * @param cellElement
  1677. * Element to write design to
  1678. * @param designContext
  1679. * the design context
  1680. */
  1681. protected void writeDesign(Element cellElement,
  1682. DesignContext designContext) {
  1683. switch (cellState.type) {
  1684. case TEXT:
  1685. DesignAttributeHandler.writeAttribute("plain-text",
  1686. cellElement.attributes(), "", null, String.class);
  1687. cellElement.appendText(getText());
  1688. break;
  1689. case HTML:
  1690. cellElement.append(getHtml());
  1691. break;
  1692. case WIDGET:
  1693. cellElement.appendChild(designContext
  1694. .createElement(getComponent()));
  1695. break;
  1696. }
  1697. }
  1698. /**
  1699. * Reads the declarative design from the given table cell element.
  1700. *
  1701. * @since 7.5.0
  1702. * @param cellElement
  1703. * Element to read design from
  1704. * @param designContext
  1705. * the design context
  1706. */
  1707. protected void readDesign(Element cellElement,
  1708. DesignContext designContext) {
  1709. if (!cellElement.hasAttr("plain-text")) {
  1710. if (cellElement.children().size() > 0
  1711. && cellElement.child(0).tagName().contains("-")) {
  1712. setComponent(designContext.readDesign(cellElement
  1713. .child(0)));
  1714. } else {
  1715. setHtml(cellElement.html());
  1716. }
  1717. } else {
  1718. setText(cellElement.html());
  1719. }
  1720. }
  1721. }
  1722. protected Grid grid;
  1723. protected List<ROWTYPE> rows = new ArrayList<ROWTYPE>();
  1724. /**
  1725. * Sets the visibility of the whole section.
  1726. *
  1727. * @param visible
  1728. * true to show this section, false to hide
  1729. */
  1730. public void setVisible(boolean visible) {
  1731. if (getSectionState().visible != visible) {
  1732. getSectionState().visible = visible;
  1733. markAsDirty();
  1734. }
  1735. }
  1736. /**
  1737. * Returns the visibility of this section.
  1738. *
  1739. * @return true if visible, false otherwise.
  1740. */
  1741. public boolean isVisible() {
  1742. return getSectionState().visible;
  1743. }
  1744. /**
  1745. * Removes the row at the given position.
  1746. *
  1747. * @param index
  1748. * the position of the row
  1749. *
  1750. * @throws IllegalArgumentException
  1751. * if no row exists at given index
  1752. * @see #removeRow(StaticRow)
  1753. * @see #addRowAt(int)
  1754. * @see #appendRow()
  1755. * @see #prependRow()
  1756. */
  1757. public ROWTYPE removeRow(int rowIndex) {
  1758. if (rowIndex >= rows.size() || rowIndex < 0) {
  1759. throw new IllegalArgumentException("No row at given index "
  1760. + rowIndex);
  1761. }
  1762. ROWTYPE row = rows.remove(rowIndex);
  1763. getSectionState().rows.remove(rowIndex);
  1764. markAsDirty();
  1765. return row;
  1766. }
  1767. /**
  1768. * Removes the given row from the section.
  1769. *
  1770. * @param row
  1771. * the row to be removed
  1772. *
  1773. * @throws IllegalArgumentException
  1774. * if the row does not exist in this section
  1775. * @see #removeRow(int)
  1776. * @see #addRowAt(int)
  1777. * @see #appendRow()
  1778. * @see #prependRow()
  1779. */
  1780. public void removeRow(ROWTYPE row) {
  1781. try {
  1782. removeRow(rows.indexOf(row));
  1783. } catch (IndexOutOfBoundsException e) {
  1784. throw new IllegalArgumentException(
  1785. "Section does not contain the given row");
  1786. }
  1787. }
  1788. /**
  1789. * Gets row at given index.
  1790. *
  1791. * @param rowIndex
  1792. * 0 based index for row. Counted from top to bottom
  1793. * @return row at given index
  1794. */
  1795. public ROWTYPE getRow(int rowIndex) {
  1796. if (rowIndex >= rows.size() || rowIndex < 0) {
  1797. throw new IllegalArgumentException("No row at given index "
  1798. + rowIndex);
  1799. }
  1800. return rows.get(rowIndex);
  1801. }
  1802. /**
  1803. * Adds a new row at the top of this section.
  1804. *
  1805. * @return the new row
  1806. * @see #appendRow()
  1807. * @see #addRowAt(int)
  1808. * @see #removeRow(StaticRow)
  1809. * @see #removeRow(int)
  1810. */
  1811. public ROWTYPE prependRow() {
  1812. return addRowAt(0);
  1813. }
  1814. /**
  1815. * Adds a new row at the bottom of this section.
  1816. *
  1817. * @return the new row
  1818. * @see #prependRow()
  1819. * @see #addRowAt(int)
  1820. * @see #removeRow(StaticRow)
  1821. * @see #removeRow(int)
  1822. */
  1823. public ROWTYPE appendRow() {
  1824. return addRowAt(rows.size());
  1825. }
  1826. /**
  1827. * Inserts a new row at the given position.
  1828. *
  1829. * @param index
  1830. * the position at which to insert the row
  1831. * @return the new row
  1832. *
  1833. * @throws IndexOutOfBoundsException
  1834. * if the index is out of bounds
  1835. * @see #appendRow()
  1836. * @see #prependRow()
  1837. * @see #removeRow(StaticRow)
  1838. * @see #removeRow(int)
  1839. */
  1840. public ROWTYPE addRowAt(int index) {
  1841. if (index > rows.size() || index < 0) {
  1842. throw new IllegalArgumentException(
  1843. "Unable to add row at index " + index);
  1844. }
  1845. ROWTYPE row = createRow();
  1846. rows.add(index, row);
  1847. getSectionState().rows.add(index, row.getRowState());
  1848. for (Object id : grid.columns.keySet()) {
  1849. row.addCell(id);
  1850. }
  1851. markAsDirty();
  1852. return row;
  1853. }
  1854. /**
  1855. * Gets the amount of rows in this section.
  1856. *
  1857. * @return row count
  1858. */
  1859. public int getRowCount() {
  1860. return rows.size();
  1861. }
  1862. protected abstract GridStaticSectionState getSectionState();
  1863. protected abstract ROWTYPE createRow();
  1864. /**
  1865. * Informs the grid that state has changed and it should be redrawn.
  1866. */
  1867. protected void markAsDirty() {
  1868. grid.markAsDirty();
  1869. }
  1870. /**
  1871. * Removes a column for given property id from the section.
  1872. *
  1873. * @param propertyId
  1874. * property to be removed
  1875. */
  1876. protected void removeColumn(Object propertyId) {
  1877. for (ROWTYPE row : rows) {
  1878. row.removeCell(propertyId);
  1879. }
  1880. }
  1881. /**
  1882. * Adds a column for given property id to the section.
  1883. *
  1884. * @param propertyId
  1885. * property to be added
  1886. */
  1887. protected void addColumn(Object propertyId) {
  1888. for (ROWTYPE row : rows) {
  1889. row.addCell(propertyId);
  1890. }
  1891. }
  1892. /**
  1893. * Performs a sanity check that section is in correct state.
  1894. *
  1895. * @throws IllegalStateException
  1896. * if merged cells are not i n continuous range
  1897. */
  1898. protected void sanityCheck() throws IllegalStateException {
  1899. List<String> columnOrder = grid.getState().columnOrder;
  1900. for (ROWTYPE row : rows) {
  1901. for (Set<String> cellGroup : row.getRowState().cellGroups
  1902. .keySet()) {
  1903. if (!checkCellGroupAndOrder(columnOrder, cellGroup)) {
  1904. throw new IllegalStateException(
  1905. "Not all merged cells were in a continuous range.");
  1906. }
  1907. }
  1908. }
  1909. }
  1910. private boolean checkCellGroupAndOrder(List<String> columnOrder,
  1911. Set<String> cellGroup) {
  1912. if (!columnOrder.containsAll(cellGroup)) {
  1913. return false;
  1914. }
  1915. for (int i = 0; i < columnOrder.size(); ++i) {
  1916. if (!cellGroup.contains(columnOrder.get(i))) {
  1917. continue;
  1918. }
  1919. for (int j = 1; j < cellGroup.size(); ++j) {
  1920. if (!cellGroup.contains(columnOrder.get(i + j))) {
  1921. return false;
  1922. }
  1923. }
  1924. return true;
  1925. }
  1926. return false;
  1927. }
  1928. /**
  1929. * Writes the declarative design to the given table section element.
  1930. *
  1931. * @since 7.5.0
  1932. * @param tableSectionElement
  1933. * Element to write design to
  1934. * @param designContext
  1935. * the design context
  1936. */
  1937. protected void writeDesign(Element tableSectionElement,
  1938. DesignContext designContext) {
  1939. for (ROWTYPE row : rows) {
  1940. row.writeDesign(tableSectionElement.appendElement("tr"),
  1941. designContext);
  1942. }
  1943. }
  1944. /**
  1945. * Writes the declarative design from the given table section element.
  1946. *
  1947. * @since 7.5.0
  1948. * @param tableSectionElement
  1949. * Element to read design from
  1950. * @param designContext
  1951. * the design context
  1952. * @throws DesignException
  1953. * if the table section contains unexpected children
  1954. */
  1955. protected void readDesign(Element tableSectionElement,
  1956. DesignContext designContext) throws DesignException {
  1957. while (rows.size() > 0) {
  1958. removeRow(0);
  1959. }
  1960. for (Element row : tableSectionElement.children()) {
  1961. if (!row.tagName().equals("tr")) {
  1962. throw new DesignException("Unexpected element in "
  1963. + tableSectionElement.tagName() + ": "
  1964. + row.tagName());
  1965. }
  1966. appendRow().readDesign(row, designContext);
  1967. }
  1968. }
  1969. }
  1970. /**
  1971. * Represents the header section of a Grid.
  1972. */
  1973. protected static class Header extends StaticSection<HeaderRow> {
  1974. private HeaderRow defaultRow = null;
  1975. private final GridStaticSectionState headerState = new GridStaticSectionState();
  1976. protected Header(Grid grid) {
  1977. this.grid = grid;
  1978. grid.getState(true).header = headerState;
  1979. HeaderRow row = createRow();
  1980. rows.add(row);
  1981. setDefaultRow(row);
  1982. getSectionState().rows.add(row.getRowState());
  1983. }
  1984. /**
  1985. * Sets the default row of this header. The default row is a special
  1986. * header row providing a user interface for sorting columns.
  1987. *
  1988. * @param row
  1989. * the new default row, or null for no default row
  1990. *
  1991. * @throws IllegalArgumentException
  1992. * this header does not contain the row
  1993. */
  1994. public void setDefaultRow(HeaderRow row) {
  1995. if (row == defaultRow) {
  1996. return;
  1997. }
  1998. if (row != null && !rows.contains(row)) {
  1999. throw new IllegalArgumentException(
  2000. "Cannot set a default row that does not exist in the section");
  2001. }
  2002. if (defaultRow != null) {
  2003. defaultRow.setDefaultRow(false);
  2004. }
  2005. if (row != null) {
  2006. row.setDefaultRow(true);
  2007. }
  2008. defaultRow = row;
  2009. markAsDirty();
  2010. }
  2011. /**
  2012. * Returns the current default row of this header. The default row is a
  2013. * special header row providing a user interface for sorting columns.
  2014. *
  2015. * @return the default row or null if no default row set
  2016. */
  2017. public HeaderRow getDefaultRow() {
  2018. return defaultRow;
  2019. }
  2020. @Override
  2021. protected GridStaticSectionState getSectionState() {
  2022. return headerState;
  2023. }
  2024. @Override
  2025. protected HeaderRow createRow() {
  2026. return new HeaderRow(this);
  2027. }
  2028. @Override
  2029. public HeaderRow removeRow(int rowIndex) {
  2030. HeaderRow row = super.removeRow(rowIndex);
  2031. if (row == defaultRow) {
  2032. // Default Header Row was just removed.
  2033. setDefaultRow(null);
  2034. }
  2035. return row;
  2036. }
  2037. @Override
  2038. protected void sanityCheck() throws IllegalStateException {
  2039. super.sanityCheck();
  2040. boolean hasDefaultRow = false;
  2041. for (HeaderRow row : rows) {
  2042. if (row.getRowState().defaultRow) {
  2043. if (!hasDefaultRow) {
  2044. hasDefaultRow = true;
  2045. } else {
  2046. throw new IllegalStateException(
  2047. "Multiple default rows in header");
  2048. }
  2049. }
  2050. }
  2051. }
  2052. @Override
  2053. protected void readDesign(Element tableSectionElement,
  2054. DesignContext designContext) {
  2055. super.readDesign(tableSectionElement, designContext);
  2056. if (defaultRow == null && !rows.isEmpty()) {
  2057. grid.setDefaultHeaderRow(rows.get(0));
  2058. }
  2059. }
  2060. }
  2061. /**
  2062. * Represents a header row in Grid.
  2063. */
  2064. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  2065. protected HeaderRow(StaticSection<?> section) {
  2066. super(section);
  2067. }
  2068. private void setDefaultRow(boolean value) {
  2069. getRowState().defaultRow = value;
  2070. }
  2071. private boolean isDefaultRow() {
  2072. return getRowState().defaultRow;
  2073. }
  2074. @Override
  2075. protected HeaderCell createCell() {
  2076. return new HeaderCell(this);
  2077. }
  2078. @Override
  2079. protected String getCellTagName() {
  2080. return "th";
  2081. }
  2082. @Override
  2083. protected void writeDesign(Element trElement,
  2084. DesignContext designContext) {
  2085. super.writeDesign(trElement, designContext);
  2086. if (section.grid.getDefaultHeaderRow() == this) {
  2087. DesignAttributeHandler.writeAttribute("default",
  2088. trElement.attributes(), true, null, boolean.class);
  2089. }
  2090. }
  2091. @Override
  2092. protected void readDesign(Element trElement, DesignContext designContext) {
  2093. super.readDesign(trElement, designContext);
  2094. boolean defaultRow = DesignAttributeHandler.readAttribute(
  2095. "default", trElement.attributes(), false, boolean.class);
  2096. if (defaultRow) {
  2097. section.grid.setDefaultHeaderRow(this);
  2098. }
  2099. }
  2100. }
  2101. /**
  2102. * Represents a header cell in Grid. Can be a merged cell for multiple
  2103. * columns.
  2104. */
  2105. public static class HeaderCell extends StaticSection.StaticCell {
  2106. protected HeaderCell(HeaderRow row) {
  2107. super(row);
  2108. }
  2109. }
  2110. /**
  2111. * Represents the footer section of a Grid. By default Footer is not
  2112. * visible.
  2113. */
  2114. protected static class Footer extends StaticSection<FooterRow> {
  2115. private final GridStaticSectionState footerState = new GridStaticSectionState();
  2116. protected Footer(Grid grid) {
  2117. this.grid = grid;
  2118. grid.getState(true).footer = footerState;
  2119. }
  2120. @Override
  2121. protected GridStaticSectionState getSectionState() {
  2122. return footerState;
  2123. }
  2124. @Override
  2125. protected FooterRow createRow() {
  2126. return new FooterRow(this);
  2127. }
  2128. @Override
  2129. protected void sanityCheck() throws IllegalStateException {
  2130. super.sanityCheck();
  2131. }
  2132. }
  2133. /**
  2134. * Represents a footer row in Grid.
  2135. */
  2136. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  2137. protected FooterRow(StaticSection<?> section) {
  2138. super(section);
  2139. }
  2140. @Override
  2141. protected FooterCell createCell() {
  2142. return new FooterCell(this);
  2143. }
  2144. @Override
  2145. protected String getCellTagName() {
  2146. return "td";
  2147. }
  2148. }
  2149. /**
  2150. * Represents a footer cell in Grid.
  2151. */
  2152. public static class FooterCell extends StaticSection.StaticCell {
  2153. protected FooterCell(FooterRow row) {
  2154. super(row);
  2155. }
  2156. }
  2157. /**
  2158. * A column in the grid. Can be obtained by calling
  2159. * {@link Grid#getColumn(Object propertyId)}.
  2160. */
  2161. public static class Column implements Serializable {
  2162. /**
  2163. * The state of the column shared to the client
  2164. */
  2165. private final GridColumnState state;
  2166. /**
  2167. * The grid this column is associated with
  2168. */
  2169. private final Grid grid;
  2170. /**
  2171. * Backing property for column
  2172. */
  2173. private final Object propertyId;
  2174. private Converter<?, Object> converter;
  2175. /**
  2176. * A check for allowing the {@link #Column(Grid, GridColumnState)
  2177. * constructor} to call {@link #setConverter(Converter)} with a
  2178. * <code>null</code>, even if model and renderer aren't compatible.
  2179. */
  2180. private boolean isFirstConverterAssignment = true;
  2181. /**
  2182. * Internally used constructor.
  2183. *
  2184. * @param grid
  2185. * The grid this column belongs to. Should not be null.
  2186. * @param state
  2187. * the shared state of this column
  2188. * @param propertyId
  2189. * the backing property id for this column
  2190. */
  2191. Column(Grid grid, GridColumnState state, Object propertyId) {
  2192. this.grid = grid;
  2193. this.state = state;
  2194. this.propertyId = propertyId;
  2195. internalSetRenderer(new TextRenderer());
  2196. }
  2197. /**
  2198. * Returns the serializable state of this column that is sent to the
  2199. * client side connector.
  2200. *
  2201. * @return the internal state of the column
  2202. */
  2203. GridColumnState getState() {
  2204. return state;
  2205. }
  2206. /**
  2207. * Returns the property id for the backing property of this Column
  2208. *
  2209. * @return property id
  2210. */
  2211. public Object getPropertyId() {
  2212. return propertyId;
  2213. }
  2214. /**
  2215. * Returns the caption of the header. By default the header caption is
  2216. * the property id of the column.
  2217. *
  2218. * @return the text in the default row of header, null if no default row
  2219. *
  2220. * @throws IllegalStateException
  2221. * if the column no longer is attached to the grid
  2222. */
  2223. public String getHeaderCaption() throws IllegalStateException {
  2224. checkColumnIsAttached();
  2225. HeaderRow row = grid.getHeader().getDefaultRow();
  2226. if (row != null) {
  2227. return row.getCell(grid.getPropertyIdByColumnId(state.id))
  2228. .getText();
  2229. }
  2230. return null;
  2231. }
  2232. /**
  2233. * Sets the caption of the header.
  2234. *
  2235. * @param caption
  2236. * the text to show in the caption
  2237. * @return the column itself
  2238. *
  2239. * @throws IllegalStateException
  2240. * if the column is no longer attached to any grid
  2241. */
  2242. public Column setHeaderCaption(String caption)
  2243. throws IllegalStateException {
  2244. checkColumnIsAttached();
  2245. HeaderRow row = grid.getHeader().getDefaultRow();
  2246. if (row != null) {
  2247. row.getCell(grid.getPropertyIdByColumnId(state.id)).setText(
  2248. caption);
  2249. }
  2250. return this;
  2251. }
  2252. /**
  2253. * Gets the caption of the hiding toggle for this column.
  2254. *
  2255. * @since 7.5.0
  2256. * @see #setHidingToggleCaption(String)
  2257. * @return the caption for the hiding toggle for this column
  2258. * @throws IllegalStateException
  2259. * if the column is no longer attached to any grid
  2260. */
  2261. public String getHidingToggleCaption() throws IllegalStateException {
  2262. checkColumnIsAttached();
  2263. return state.hidingToggleCaption;
  2264. }
  2265. /**
  2266. * Sets the caption of the hiding toggle for this column. Shown in the
  2267. * toggle for this column in the grid's sidebar when the column is
  2268. * {@link #isHidable() hidable}.
  2269. * <p>
  2270. * By default, before triggering this setter, a user friendly version of
  2271. * the column's {@link #getPropertyId() property id} is used.
  2272. * <p>
  2273. * <em>NOTE:</em> setting this to <code>null</code> or empty string
  2274. * might cause the hiding toggle to not render correctly.
  2275. *
  2276. * @since 7.5.0
  2277. * @param hidingToggleCaption
  2278. * the text to show in the column hiding toggle
  2279. * @return the column itself
  2280. * @throws IllegalStateException
  2281. * if the column is no longer attached to any grid
  2282. */
  2283. public Column setHidingToggleCaption(String hidingToggleCaption)
  2284. throws IllegalStateException {
  2285. checkColumnIsAttached();
  2286. state.hidingToggleCaption = hidingToggleCaption;
  2287. grid.markAsDirty();
  2288. return this;
  2289. }
  2290. /**
  2291. * Returns the width (in pixels). By default a column is 100px wide.
  2292. *
  2293. * @return the width in pixels of the column
  2294. * @throws IllegalStateException
  2295. * if the column is no longer attached to any grid
  2296. */
  2297. public double getWidth() throws IllegalStateException {
  2298. checkColumnIsAttached();
  2299. return state.width;
  2300. }
  2301. /**
  2302. * Sets the width (in pixels).
  2303. * <p>
  2304. * This overrides any configuration set by any of
  2305. * {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
  2306. * {@link #setMaximumWidth(double)}.
  2307. *
  2308. * @param pixelWidth
  2309. * the new pixel width of the column
  2310. * @return the column itself
  2311. *
  2312. * @throws IllegalStateException
  2313. * if the column is no longer attached to any grid
  2314. * @throws IllegalArgumentException
  2315. * thrown if pixel width is less than zero
  2316. */
  2317. public Column setWidth(double pixelWidth) throws IllegalStateException,
  2318. IllegalArgumentException {
  2319. checkColumnIsAttached();
  2320. if (pixelWidth < 0) {
  2321. throw new IllegalArgumentException(
  2322. "Pixel width should be greated than 0 (in "
  2323. + toString() + ")");
  2324. }
  2325. state.width = pixelWidth;
  2326. grid.markAsDirty();
  2327. return this;
  2328. }
  2329. /**
  2330. * Marks the column width as undefined meaning that the grid is free to
  2331. * resize the column based on the cell contents and available space in
  2332. * the grid.
  2333. *
  2334. * @return the column itself
  2335. */
  2336. public Column setWidthUndefined() {
  2337. checkColumnIsAttached();
  2338. state.width = -1;
  2339. grid.markAsDirty();
  2340. return this;
  2341. }
  2342. /**
  2343. * Checks if column is attached and throws an
  2344. * {@link IllegalStateException} if it is not
  2345. *
  2346. * @throws IllegalStateException
  2347. * if the column is no longer attached to any grid
  2348. */
  2349. protected void checkColumnIsAttached() throws IllegalStateException {
  2350. if (grid.getColumnByColumnId(state.id) == null) {
  2351. throw new IllegalStateException("Column no longer exists.");
  2352. }
  2353. }
  2354. /**
  2355. * Sets this column as the last frozen column in its grid.
  2356. *
  2357. * @return the column itself
  2358. *
  2359. * @throws IllegalArgumentException
  2360. * if the column is no longer attached to any grid
  2361. * @see Grid#setFrozenColumnCount(int)
  2362. */
  2363. public Column setLastFrozenColumn() {
  2364. checkColumnIsAttached();
  2365. grid.setFrozenColumnCount(grid.getState(false).columnOrder
  2366. .indexOf(getState().id) + 1);
  2367. return this;
  2368. }
  2369. /**
  2370. * Sets the renderer for this column.
  2371. * <p>
  2372. * If a suitable converter isn't defined explicitly, the session
  2373. * converter factory is used to find a compatible converter.
  2374. *
  2375. * @param renderer
  2376. * the renderer to use
  2377. * @return the column itself
  2378. *
  2379. * @throws IllegalArgumentException
  2380. * if no compatible converter could be found
  2381. *
  2382. * @see VaadinSession#getConverterFactory()
  2383. * @see ConverterUtil#getConverter(Class, Class, VaadinSession)
  2384. * @see #setConverter(Converter)
  2385. */
  2386. public Column setRenderer(Renderer<?> renderer) {
  2387. if (!internalSetRenderer(renderer)) {
  2388. throw new IllegalArgumentException(
  2389. "Could not find a converter for converting from the model type "
  2390. + getModelType()
  2391. + " to the renderer presentation type "
  2392. + renderer.getPresentationType() + " (in "
  2393. + toString() + ")");
  2394. }
  2395. return this;
  2396. }
  2397. /**
  2398. * Sets the renderer for this column and the converter used to convert
  2399. * from the property value type to the renderer presentation type.
  2400. *
  2401. * @param renderer
  2402. * the renderer to use, cannot be null
  2403. * @param converter
  2404. * the converter to use
  2405. * @return the column itself
  2406. *
  2407. * @throws IllegalArgumentException
  2408. * if the renderer is already associated with a grid column
  2409. */
  2410. public <T> Column setRenderer(Renderer<T> renderer,
  2411. Converter<? extends T, ?> converter) {
  2412. if (renderer.getParent() != null) {
  2413. throw new IllegalArgumentException(
  2414. "Cannot set a renderer that is already connected to a grid column (in "
  2415. + toString() + ")");
  2416. }
  2417. if (getRenderer() != null) {
  2418. grid.removeExtension(getRenderer());
  2419. }
  2420. grid.addRenderer(renderer);
  2421. state.rendererConnector = renderer;
  2422. setConverter(converter);
  2423. return this;
  2424. }
  2425. /**
  2426. * Sets the converter used to convert from the property value type to
  2427. * the renderer presentation type.
  2428. *
  2429. * @param converter
  2430. * the converter to use, or {@code null} to not use any
  2431. * converters
  2432. * @return the column itself
  2433. *
  2434. * @throws IllegalArgumentException
  2435. * if the types are not compatible
  2436. */
  2437. public Column setConverter(Converter<?, ?> converter)
  2438. throws IllegalArgumentException {
  2439. Class<?> modelType = getModelType();
  2440. if (converter != null) {
  2441. if (!converter.getModelType().isAssignableFrom(modelType)) {
  2442. throw new IllegalArgumentException(
  2443. "The converter model type "
  2444. + converter.getModelType()
  2445. + " is not compatible with the property type "
  2446. + modelType + " (in " + toString() + ")");
  2447. } else if (!getRenderer().getPresentationType()
  2448. .isAssignableFrom(converter.getPresentationType())) {
  2449. throw new IllegalArgumentException(
  2450. "The converter presentation type "
  2451. + converter.getPresentationType()
  2452. + " is not compatible with the renderer presentation type "
  2453. + getRenderer().getPresentationType()
  2454. + " (in " + toString() + ")");
  2455. }
  2456. }
  2457. else {
  2458. /*
  2459. * Since the converter is null (i.e. will be removed), we need
  2460. * to know that the renderer and model are compatible. If not,
  2461. * we can't allow for this to happen.
  2462. *
  2463. * The constructor is allowed to call this method with null
  2464. * without any compatibility checks, therefore we have a special
  2465. * case for it.
  2466. */
  2467. Class<?> rendererPresentationType = getRenderer()
  2468. .getPresentationType();
  2469. if (!isFirstConverterAssignment
  2470. && !rendererPresentationType
  2471. .isAssignableFrom(modelType)) {
  2472. throw new IllegalArgumentException(
  2473. "Cannot remove converter, "
  2474. + "as renderer's presentation type "
  2475. + rendererPresentationType.getName()
  2476. + " and column's "
  2477. + "model "
  2478. + modelType.getName()
  2479. + " type aren't "
  2480. + "directly compatible with each other (in "
  2481. + toString() + ")");
  2482. }
  2483. }
  2484. isFirstConverterAssignment = false;
  2485. @SuppressWarnings("unchecked")
  2486. Converter<?, Object> castConverter = (Converter<?, Object>) converter;
  2487. this.converter = castConverter;
  2488. return this;
  2489. }
  2490. /**
  2491. * Returns the renderer instance used by this column.
  2492. *
  2493. * @return the renderer
  2494. */
  2495. public Renderer<?> getRenderer() {
  2496. return (Renderer<?>) getState().rendererConnector;
  2497. }
  2498. /**
  2499. * Returns the converter instance used by this column.
  2500. *
  2501. * @return the converter
  2502. */
  2503. public Converter<?, ?> getConverter() {
  2504. return converter;
  2505. }
  2506. private <T> boolean internalSetRenderer(Renderer<T> renderer) {
  2507. Converter<? extends T, ?> converter;
  2508. if (isCompatibleWithProperty(renderer, getConverter())) {
  2509. // Use the existing converter (possibly none) if types
  2510. // compatible
  2511. converter = (Converter<? extends T, ?>) getConverter();
  2512. } else {
  2513. converter = ConverterUtil.getConverter(
  2514. renderer.getPresentationType(), getModelType(),
  2515. getSession());
  2516. }
  2517. setRenderer(renderer, converter);
  2518. return isCompatibleWithProperty(renderer, converter);
  2519. }
  2520. private VaadinSession getSession() {
  2521. UI ui = grid.getUI();
  2522. return ui != null ? ui.getSession() : null;
  2523. }
  2524. private boolean isCompatibleWithProperty(Renderer<?> renderer,
  2525. Converter<?, ?> converter) {
  2526. Class<?> type;
  2527. if (converter == null) {
  2528. type = getModelType();
  2529. } else {
  2530. type = converter.getPresentationType();
  2531. }
  2532. return renderer.getPresentationType().isAssignableFrom(type);
  2533. }
  2534. private Class<?> getModelType() {
  2535. return grid.getContainerDataSource().getType(
  2536. grid.getPropertyIdByColumnId(state.id));
  2537. }
  2538. /**
  2539. * Sets whether the column should be sortable by the user. The grid can
  2540. * be sorted by a sortable column by clicking or tapping the column's
  2541. * default header. Programmatic sorting using the Grid.sort methods is
  2542. * not affected by this setting.
  2543. *
  2544. * @param sortable
  2545. * <code>true</code> if the user should be able to sort the
  2546. * column, false otherwise
  2547. * @return the column itself
  2548. */
  2549. public Column setSortable(boolean sortable) {
  2550. checkColumnIsAttached();
  2551. if (sortable) {
  2552. if (!(grid.datasource instanceof Sortable)) {
  2553. throw new IllegalStateException(
  2554. "Can't set column "
  2555. + toString()
  2556. + " sortable. The Container of Grid does not implement Sortable");
  2557. } else if (!((Sortable) grid.datasource)
  2558. .getSortableContainerPropertyIds().contains(propertyId)) {
  2559. throw new IllegalStateException(
  2560. "Can't set column "
  2561. + toString()
  2562. + " sortable. Container doesn't support sorting by property "
  2563. + propertyId);
  2564. }
  2565. }
  2566. state.sortable = sortable;
  2567. grid.markAsDirty();
  2568. return this;
  2569. }
  2570. /**
  2571. * Returns whether the user is able to sort the grid by this column.
  2572. *
  2573. * @return true if the column is sortable by the user, false otherwise
  2574. */
  2575. public boolean isSortable() {
  2576. return state.sortable;
  2577. }
  2578. @Override
  2579. public String toString() {
  2580. return getClass().getSimpleName() + "[propertyId:"
  2581. + grid.getPropertyIdByColumnId(state.id) + "]";
  2582. }
  2583. /**
  2584. * Sets the ratio with which the column expands.
  2585. * <p>
  2586. * By default, all columns expand equally (treated as if all of them had
  2587. * an expand ratio of 1). Once at least one column gets a defined expand
  2588. * ratio, the implicit expand ratio is removed, and only the defined
  2589. * expand ratios are taken into account.
  2590. * <p>
  2591. * If a column has a defined width ({@link #setWidth(double)}), it
  2592. * overrides this method's effects.
  2593. * <p>
  2594. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  2595. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  2596. * as wide as its contents requires</strong>. The column with a ratio of
  2597. * 1 is as wide as it needs, <strong>plus a third of any excess
  2598. * space</strong>, because we have 3 parts total, and this column
  2599. * reserves only one of those. The column with a ratio of 2, is as wide
  2600. * as it needs to be, <strong>plus two thirds</strong> of the excess
  2601. * width.
  2602. *
  2603. * @param expandRatio
  2604. * the expand ratio of this column. {@code 0} to not have it
  2605. * expand at all. A negative number to clear the expand
  2606. * value.
  2607. * @throws IllegalStateException
  2608. * if the column is no longer attached to any grid
  2609. * @see #setWidth(double)
  2610. */
  2611. public Column setExpandRatio(int expandRatio)
  2612. throws IllegalStateException {
  2613. checkColumnIsAttached();
  2614. getState().expandRatio = expandRatio;
  2615. grid.markAsDirty();
  2616. return this;
  2617. }
  2618. /**
  2619. * Returns the column's expand ratio.
  2620. *
  2621. * @return the column's expand ratio
  2622. * @see #setExpandRatio(int)
  2623. */
  2624. public int getExpandRatio() {
  2625. return getState().expandRatio;
  2626. }
  2627. /**
  2628. * Clears the expand ratio for this column.
  2629. * <p>
  2630. * Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  2631. *
  2632. * @throws IllegalStateException
  2633. * if the column is no longer attached to any grid
  2634. */
  2635. public Column clearExpandRatio() throws IllegalStateException {
  2636. return setExpandRatio(-1);
  2637. }
  2638. /**
  2639. * Sets the minimum width for this column.
  2640. * <p>
  2641. * This defines the minimum guaranteed pixel width of the column
  2642. * <em>when it is set to expand</em>.
  2643. *
  2644. * @throws IllegalStateException
  2645. * if the column is no longer attached to any grid
  2646. * @see #setExpandRatio(int)
  2647. */
  2648. public Column setMinimumWidth(double pixels)
  2649. throws IllegalStateException {
  2650. checkColumnIsAttached();
  2651. final double maxwidth = getMaximumWidth();
  2652. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  2653. throw new IllegalArgumentException("New minimum width ("
  2654. + pixels + ") was greater than maximum width ("
  2655. + maxwidth + ")");
  2656. }
  2657. getState().minWidth = pixels;
  2658. grid.markAsDirty();
  2659. return this;
  2660. }
  2661. /**
  2662. * Return the minimum width for this column.
  2663. *
  2664. * @return the minimum width for this column
  2665. * @see #setMinimumWidth(double)
  2666. */
  2667. public double getMinimumWidth() {
  2668. return getState().minWidth;
  2669. }
  2670. /**
  2671. * Sets the maximum width for this column.
  2672. * <p>
  2673. * This defines the maximum allowed pixel width of the column
  2674. * <em>when it is set to expand</em>.
  2675. *
  2676. * @param pixels
  2677. * the maximum width
  2678. * @throws IllegalStateException
  2679. * if the column is no longer attached to any grid
  2680. * @see #setExpandRatio(int)
  2681. */
  2682. public Column setMaximumWidth(double pixels) {
  2683. checkColumnIsAttached();
  2684. final double minwidth = getMinimumWidth();
  2685. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  2686. throw new IllegalArgumentException("New maximum width ("
  2687. + pixels + ") was less than minimum width (" + minwidth
  2688. + ")");
  2689. }
  2690. getState().maxWidth = pixels;
  2691. grid.markAsDirty();
  2692. return this;
  2693. }
  2694. /**
  2695. * Returns the maximum width for this column.
  2696. *
  2697. * @return the maximum width for this column
  2698. * @see #setMaximumWidth(double)
  2699. */
  2700. public double getMaximumWidth() {
  2701. return getState().maxWidth;
  2702. }
  2703. /**
  2704. * Sets whether the properties corresponding to this column should be
  2705. * editable when the item editor is active. By default columns are
  2706. * editable.
  2707. * <p>
  2708. * Values in non-editable columns are currently not displayed when the
  2709. * editor is active, but this will probably change in the future. They
  2710. * are not automatically assigned an editor field and, if one is
  2711. * manually assigned, it is not used. Columns that cannot (or should
  2712. * not) be edited even in principle should be set non-editable.
  2713. *
  2714. * @param editable
  2715. * {@code true} if this column should be editable,
  2716. * {@code false} otherwise
  2717. * @return this column
  2718. *
  2719. * @throws IllegalStateException
  2720. * if the editor is currently active
  2721. *
  2722. * @see Grid#editItem(Object)
  2723. * @see Grid#isEditorActive()
  2724. */
  2725. public Column setEditable(boolean editable) {
  2726. checkColumnIsAttached();
  2727. if (grid.isEditorActive()) {
  2728. throw new IllegalStateException(
  2729. "Cannot change column editable status while the editor is active");
  2730. }
  2731. getState().editable = editable;
  2732. grid.markAsDirty();
  2733. return this;
  2734. }
  2735. /**
  2736. * Returns whether the properties corresponding to this column should be
  2737. * editable when the item editor is active.
  2738. *
  2739. * @return {@code true} if this column is editable, {@code false}
  2740. * otherwise
  2741. *
  2742. * @see Grid#editItem(Object)
  2743. * @see #setEditable(boolean)
  2744. */
  2745. public boolean isEditable() {
  2746. return getState().editable;
  2747. }
  2748. /**
  2749. * Sets the field component used to edit the properties in this column
  2750. * when the item editor is active. If an item has not been set, then the
  2751. * binding is postponed until the item is set using
  2752. * {@link #editItem(Object)}.
  2753. * <p>
  2754. * Setting the field to <code>null</code> clears any previously set
  2755. * field, causing a new field to be created the next time the item
  2756. * editor is opened.
  2757. *
  2758. * @param editor
  2759. * the editor field
  2760. * @return this column
  2761. */
  2762. public Column setEditorField(Field<?> editor) {
  2763. grid.setEditorField(getPropertyId(), editor);
  2764. return this;
  2765. }
  2766. /**
  2767. * Returns the editor field used to edit the properties in this column
  2768. * when the item editor is active. Returns null if the column is not
  2769. * {@link Column#isEditable() editable}.
  2770. * <p>
  2771. * When {@link #editItem(Object) editItem} is called, fields are
  2772. * automatically created and bound for any unbound properties.
  2773. * <p>
  2774. * Getting a field before the editor has been opened depends on special
  2775. * support from the {@link FieldGroup} in use. Using this method with a
  2776. * user-provided <code>FieldGroup</code> might cause
  2777. * {@link com.vaadin.data.fieldgroup.FieldGroup.BindException
  2778. * BindException} to be thrown.
  2779. *
  2780. * @return the bound field; or <code>null</code> if the respective
  2781. * column is not editable
  2782. *
  2783. * @throws IllegalArgumentException
  2784. * if there is no column for the provided property id
  2785. * @throws BindException
  2786. * if no field has been configured and there is a problem
  2787. * building or binding
  2788. */
  2789. public Field<?> getEditorField() {
  2790. return grid.getEditorField(getPropertyId());
  2791. }
  2792. /**
  2793. * Hides or shows the column. By default columns are visible before
  2794. * explicitly hiding them.
  2795. *
  2796. * @since 7.5.0
  2797. * @param hidden
  2798. * <code>true</code> to hide the column, <code>false</code>
  2799. * to show
  2800. * @return this column
  2801. */
  2802. public Column setHidden(boolean hidden) {
  2803. if (hidden != getState().hidden) {
  2804. getState().hidden = hidden;
  2805. grid.markAsDirty();
  2806. grid.fireColumnVisibilityChangeEvent(this, hidden, false);
  2807. }
  2808. return this;
  2809. }
  2810. /**
  2811. * Is this column hidden. Default is {@code false}.
  2812. *
  2813. * @since 7.5.0
  2814. * @return <code>true</code> if the column is currently hidden,
  2815. * <code>false</code> otherwise
  2816. */
  2817. public boolean isHidden() {
  2818. return getState().hidden;
  2819. }
  2820. /**
  2821. * Set whether it is possible for the user to hide this column or not.
  2822. * Default is {@code false}.
  2823. * <p>
  2824. * <em>Note:</em> it is still possible to hide the column
  2825. * programmatically using {@link #setHidden(boolean)}
  2826. *
  2827. * @since 7.5.0
  2828. * @param hidable
  2829. * <code>true</code> iff the column may be hidable by the
  2830. * user via UI interaction
  2831. * @return this column
  2832. */
  2833. public Column setHidable(boolean hidable) {
  2834. if (hidable != getState().hidable) {
  2835. getState().hidable = hidable;
  2836. grid.markAsDirty();
  2837. }
  2838. return this;
  2839. }
  2840. /**
  2841. * Is it possible for the the user to hide this column. Default is
  2842. * {@code false}.
  2843. * <p>
  2844. * <em>Note:</em> the column can be programmatically hidden using
  2845. * {@link #setHidden(boolean)} regardless of the returned value.
  2846. *
  2847. * @since 7.5.0
  2848. * @return <code>true</code> if the user can hide the column,
  2849. * <code>false</code> if not
  2850. */
  2851. public boolean isHidable() {
  2852. return getState().hidable;
  2853. }
  2854. /**
  2855. * Writes the design attributes for this column into given element.
  2856. *
  2857. * @since 7.5.0
  2858. *
  2859. * @param design
  2860. * Element to write attributes into
  2861. *
  2862. * @param designContext
  2863. * the design context
  2864. */
  2865. protected void writeDesign(Element design, DesignContext designContext) {
  2866. Attributes attributes = design.attributes();
  2867. GridColumnState def = new GridColumnState();
  2868. // Sortable is a special attribute that depends on the container.
  2869. DesignAttributeHandler.writeAttribute("sortable", attributes,
  2870. isSortable(), null, boolean.class);
  2871. DesignAttributeHandler.writeAttribute("editable", attributes,
  2872. isEditable(), def.editable, boolean.class);
  2873. DesignAttributeHandler.writeAttribute("width", attributes,
  2874. getWidth(), def.width, Double.class);
  2875. DesignAttributeHandler.writeAttribute("min-width", attributes,
  2876. getMinimumWidth(), def.minWidth, Double.class);
  2877. DesignAttributeHandler.writeAttribute("max-width", attributes,
  2878. getMaximumWidth(), def.maxWidth, Double.class);
  2879. DesignAttributeHandler.writeAttribute("expand", attributes,
  2880. getExpandRatio(), def.expandRatio, Integer.class);
  2881. DesignAttributeHandler.writeAttribute("hidable", attributes,
  2882. isHidable(), def.hidable, boolean.class);
  2883. DesignAttributeHandler.writeAttribute("hidden", attributes,
  2884. isHidden(), def.hidden, boolean.class);
  2885. DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
  2886. attributes, getHidingToggleCaption(),
  2887. SharedUtil.propertyIdToHumanFriendly(getPropertyId()),
  2888. String.class);
  2889. DesignAttributeHandler.writeAttribute("property-id", attributes,
  2890. getPropertyId(), null, Object.class);
  2891. }
  2892. /**
  2893. * Reads the design attributes for this column from given element.
  2894. *
  2895. * @since 7.5.0
  2896. * @param design
  2897. * Element to read attributes from
  2898. * @param designContext
  2899. * the design context
  2900. */
  2901. protected void readDesign(Element design, DesignContext designContext) {
  2902. Attributes attributes = design.attributes();
  2903. if (design.hasAttr("sortable")) {
  2904. setSortable(DesignAttributeHandler.readAttribute("sortable",
  2905. attributes, boolean.class));
  2906. }
  2907. if (design.hasAttr("editable")) {
  2908. setEditable(DesignAttributeHandler.readAttribute("editable",
  2909. attributes, boolean.class));
  2910. }
  2911. if (design.hasAttr("hidable")) {
  2912. setHidable(DesignAttributeHandler.readAttribute("hidable",
  2913. attributes, boolean.class));
  2914. }
  2915. if (design.hasAttr("hidden")) {
  2916. setHidden(DesignAttributeHandler.readAttribute("hidden",
  2917. attributes, boolean.class));
  2918. }
  2919. if (design.hasAttr("hiding-toggle-caption")) {
  2920. setHidingToggleCaption(DesignAttributeHandler.readAttribute(
  2921. "hiding-toggle-caption", attributes, String.class));
  2922. }
  2923. // Read size info where necessary.
  2924. if (design.hasAttr("width")) {
  2925. setWidth(DesignAttributeHandler.readAttribute("width",
  2926. attributes, Double.class));
  2927. }
  2928. if (design.hasAttr("min-width")) {
  2929. setMinimumWidth(DesignAttributeHandler.readAttribute(
  2930. "min-width", attributes, Double.class));
  2931. }
  2932. if (design.hasAttr("max-width")) {
  2933. setMaximumWidth(DesignAttributeHandler.readAttribute(
  2934. "max-width", attributes, Double.class));
  2935. }
  2936. if (design.hasAttr("expand")) {
  2937. if (design.attr("expand").isEmpty()) {
  2938. setExpandRatio(1);
  2939. } else {
  2940. setExpandRatio(DesignAttributeHandler.readAttribute(
  2941. "expand", attributes, Integer.class));
  2942. }
  2943. }
  2944. }
  2945. }
  2946. /**
  2947. * An abstract base class for server-side Grid renderers.
  2948. * {@link com.vaadin.client.widget.grid.Renderer Grid renderers}. This class
  2949. * currently extends the AbstractExtension superclass, but this fact should
  2950. * be regarded as an implementation detail and subject to change in a future
  2951. * major or minor Vaadin revision.
  2952. *
  2953. * @param <T>
  2954. * the type this renderer knows how to present
  2955. */
  2956. public static abstract class AbstractRenderer<T> extends AbstractExtension
  2957. implements Renderer<T> {
  2958. private final Class<T> presentationType;
  2959. protected AbstractRenderer(Class<T> presentationType) {
  2960. this.presentationType = presentationType;
  2961. }
  2962. /**
  2963. * This method is inherited from AbstractExtension but should never be
  2964. * called directly with an AbstractRenderer.
  2965. */
  2966. @Deprecated
  2967. @Override
  2968. protected Class<Grid> getSupportedParentType() {
  2969. return Grid.class;
  2970. }
  2971. /**
  2972. * This method is inherited from AbstractExtension but should never be
  2973. * called directly with an AbstractRenderer.
  2974. */
  2975. @Deprecated
  2976. @Override
  2977. protected void extend(AbstractClientConnector target) {
  2978. super.extend(target);
  2979. }
  2980. @Override
  2981. public Class<T> getPresentationType() {
  2982. return presentationType;
  2983. }
  2984. @Override
  2985. public JsonValue encode(T value) {
  2986. return encode(value, getPresentationType());
  2987. }
  2988. /**
  2989. * Encodes the given value to JSON.
  2990. * <p>
  2991. * This is a helper method that can be invoked by an
  2992. * {@link #encode(Object) encode(T)} override if serializing a value of
  2993. * type other than {@link #getPresentationType() the presentation type}
  2994. * is desired. For instance, a {@code Renderer<Date>} could first turn a
  2995. * date value into a formatted string and return
  2996. * {@code encode(dateString, String.class)}.
  2997. *
  2998. * @param value
  2999. * the value to be encoded
  3000. * @param type
  3001. * the type of the value
  3002. * @return a JSON representation of the given value
  3003. */
  3004. protected <U> JsonValue encode(U value, Class<U> type) {
  3005. return JsonCodec.encode(value, null, type,
  3006. getUI().getConnectorTracker()).getEncodedValue();
  3007. }
  3008. /**
  3009. * Gets the item id for a row key.
  3010. * <p>
  3011. * A key is used to identify a particular row on both a server and a
  3012. * client. This method can be used to get the item id for the row key
  3013. * that the client has sent.
  3014. *
  3015. * @param rowKey
  3016. * the row key for which to retrieve an item id
  3017. * @return the item id corresponding to {@code key}
  3018. */
  3019. protected Object getItemId(String rowKey) {
  3020. return getParentGrid().getKeyMapper().getItemId(rowKey);
  3021. }
  3022. /**
  3023. * Gets the column for a column id.
  3024. * <p>
  3025. * An id is used to identify a particular column on both a server and a
  3026. * client. This method can be used to get the column for the column id
  3027. * that the client has sent.
  3028. *
  3029. * @param columnId
  3030. * the column id for which to retrieve a column
  3031. * @return the column corresponding to {@code columnId}
  3032. */
  3033. protected Column getColumn(String columnId) {
  3034. return getParentGrid().getColumnByColumnId(columnId);
  3035. }
  3036. /**
  3037. * Gets the parent Grid of the renderer.
  3038. *
  3039. * @return parent grid
  3040. * @throws IllegalStateException
  3041. * if parent is not Grid
  3042. */
  3043. protected Grid getParentGrid() {
  3044. if (getParent() instanceof Grid) {
  3045. Grid grid = (Grid) getParent();
  3046. return grid;
  3047. } else {
  3048. throw new IllegalStateException(
  3049. "Renderers can be used only with Grid");
  3050. }
  3051. }
  3052. }
  3053. /**
  3054. * The data source attached to the grid
  3055. */
  3056. private Container.Indexed datasource;
  3057. /**
  3058. * Property id to column instance mapping
  3059. */
  3060. private final Map<Object, Column> columns = new HashMap<Object, Column>();
  3061. /**
  3062. * Key generator for column server-to-client communication
  3063. */
  3064. private final KeyMapper<Object> columnKeys = new KeyMapper<Object>();
  3065. /**
  3066. * The current sort order
  3067. */
  3068. private final List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  3069. /**
  3070. * Property listener for listening to changes in data source properties.
  3071. */
  3072. private final PropertySetChangeListener propertyListener = new PropertySetChangeListener() {
  3073. @Override
  3074. public void containerPropertySetChange(PropertySetChangeEvent event) {
  3075. Collection<?> properties = new HashSet<Object>(event.getContainer()
  3076. .getContainerPropertyIds());
  3077. // Find columns that need to be removed.
  3078. List<Column> removedColumns = new LinkedList<Column>();
  3079. for (Object propertyId : columns.keySet()) {
  3080. if (!properties.contains(propertyId)) {
  3081. removedColumns.add(getColumn(propertyId));
  3082. }
  3083. }
  3084. // Actually remove columns.
  3085. for (Column column : removedColumns) {
  3086. Object propertyId = column.getPropertyId();
  3087. internalRemoveColumn(propertyId);
  3088. columnKeys.remove(propertyId);
  3089. }
  3090. datasourceExtension.columnsRemoved(removedColumns);
  3091. // Add new columns
  3092. List<Column> addedColumns = new LinkedList<Column>();
  3093. for (Object propertyId : properties) {
  3094. if (!columns.containsKey(propertyId)) {
  3095. addedColumns.add(appendColumn(propertyId));
  3096. }
  3097. }
  3098. datasourceExtension.columnsAdded(addedColumns);
  3099. if (getFrozenColumnCount() > columns.size()) {
  3100. setFrozenColumnCount(columns.size());
  3101. }
  3102. // Unset sortable for non-sortable columns.
  3103. if (datasource instanceof Sortable) {
  3104. Collection<?> sortables = ((Sortable) datasource)
  3105. .getSortableContainerPropertyIds();
  3106. for (Object propertyId : columns.keySet()) {
  3107. Column column = columns.get(propertyId);
  3108. if (!sortables.contains(propertyId) && column.isSortable()) {
  3109. column.setSortable(false);
  3110. }
  3111. }
  3112. }
  3113. }
  3114. };
  3115. private RpcDataProviderExtension datasourceExtension;
  3116. /**
  3117. * The selection model that is currently in use. Never <code>null</code>
  3118. * after the constructor has been run.
  3119. */
  3120. private SelectionModel selectionModel;
  3121. /**
  3122. * Used to know whether selection change events originate from the server or
  3123. * the client so the selection change handler knows whether the changes
  3124. * should be sent to the client.
  3125. */
  3126. private boolean applyingSelectionFromClient;
  3127. private final Header header = new Header(this);
  3128. private final Footer footer = new Footer(this);
  3129. private Object editedItemId = null;
  3130. private FieldGroup editorFieldGroup = new CustomFieldGroup();
  3131. private CellStyleGenerator cellStyleGenerator;
  3132. private RowStyleGenerator rowStyleGenerator;
  3133. /**
  3134. * <code>true</code> if Grid is using the internal IndexedContainer created
  3135. * in Grid() constructor, or <code>false</code> if the user has set their
  3136. * own Container.
  3137. *
  3138. * @see #setContainerDataSource()
  3139. * @see #Grid()
  3140. */
  3141. private boolean defaultContainer = true;
  3142. private EditorErrorHandler editorErrorHandler = new DefaultEditorErrorHandler();
  3143. /**
  3144. * The user-defined details generator.
  3145. *
  3146. * @see #setDetailsGenerator(DetailsGenerator)
  3147. */
  3148. private DetailsGenerator detailsGenerator = DetailsGenerator.NULL;
  3149. private DetailComponentManager detailComponentManager = null;
  3150. private static final Method SELECTION_CHANGE_METHOD = ReflectTools
  3151. .findMethod(SelectionListener.class, "select", SelectionEvent.class);
  3152. private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
  3153. .findMethod(SortListener.class, "sort", SortEvent.class);
  3154. private static final Method COLUMN_REORDER_METHOD = ReflectTools
  3155. .findMethod(ColumnReorderListener.class, "columnReorder",
  3156. ColumnReorderEvent.class);
  3157. private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
  3158. .findMethod(ColumnVisibilityChangeListener.class,
  3159. "columnVisibilityChanged",
  3160. ColumnVisibilityChangeEvent.class);
  3161. /**
  3162. * Creates a new Grid with a new {@link IndexedContainer} as the data
  3163. * source.
  3164. */
  3165. public Grid() {
  3166. this(null, null);
  3167. }
  3168. /**
  3169. * Creates a new Grid using the given data source.
  3170. *
  3171. * @param dataSource
  3172. * the indexed container to use as a data source
  3173. */
  3174. public Grid(final Container.Indexed dataSource) {
  3175. this(null, dataSource);
  3176. }
  3177. /**
  3178. * Creates a new Grid with the given caption and a new
  3179. * {@link IndexedContainer} data source.
  3180. *
  3181. * @param caption
  3182. * the caption of the grid
  3183. */
  3184. public Grid(String caption) {
  3185. this(caption, null);
  3186. }
  3187. /**
  3188. * Creates a new Grid with the given caption and data source. If the data
  3189. * source is null, a new {@link IndexedContainer} will be used.
  3190. *
  3191. * @param caption
  3192. * the caption of the grid
  3193. * @param dataSource
  3194. * the indexed container to use as a data source
  3195. */
  3196. public Grid(String caption, Container.Indexed dataSource) {
  3197. if (dataSource == null) {
  3198. internalSetContainerDataSource(new IndexedContainer());
  3199. } else {
  3200. setContainerDataSource(dataSource);
  3201. }
  3202. setCaption(caption);
  3203. initGrid();
  3204. }
  3205. /**
  3206. * Grid initial setup
  3207. */
  3208. private void initGrid() {
  3209. setSelectionMode(getDefaultSelectionMode());
  3210. addSelectionListener(new SelectionListener() {
  3211. @Override
  3212. public void select(SelectionEvent event) {
  3213. if (applyingSelectionFromClient) {
  3214. /*
  3215. * Avoid sending changes back to the client if they
  3216. * originated from the client. Instead, the RPC handler is
  3217. * responsible for keeping track of the resulting selection
  3218. * state and notifying the client if it doens't match the
  3219. * expectation.
  3220. */
  3221. return;
  3222. }
  3223. /*
  3224. * The rows are pinned here to ensure that the client gets the
  3225. * correct key from server when the selected row is first
  3226. * loaded.
  3227. *
  3228. * Once the client has gotten info that it is supposed to select
  3229. * a row, it will pin the data from the client side as well and
  3230. * it will be unpinned once it gets deselected. Nothing on the
  3231. * server side should ever unpin anything from KeyMapper.
  3232. * Pinning is mostly a client feature and is only used when
  3233. * selecting something from the server side.
  3234. */
  3235. for (Object addedItemId : event.getAdded()) {
  3236. if (!getKeyMapper().isPinned(addedItemId)) {
  3237. getKeyMapper().pin(addedItemId);
  3238. }
  3239. }
  3240. getState().selectedKeys = getKeyMapper().getKeys(
  3241. getSelectedRows());
  3242. }
  3243. });
  3244. registerRpc(new GridServerRpc() {
  3245. @Override
  3246. public void select(List<String> selection) {
  3247. Collection<Object> receivedSelection = getKeyMapper()
  3248. .getItemIds(selection);
  3249. applyingSelectionFromClient = true;
  3250. try {
  3251. SelectionModel selectionModel = getSelectionModel();
  3252. if (selectionModel instanceof SelectionModel.Single
  3253. && selection.size() <= 1) {
  3254. Object select = null;
  3255. if (selection.size() == 1) {
  3256. select = getKeyMapper().getItemId(selection.get(0));
  3257. }
  3258. ((SelectionModel.Single) selectionModel).select(select);
  3259. } else if (selectionModel instanceof SelectionModel.Multi) {
  3260. ((SelectionModel.Multi) selectionModel)
  3261. .setSelected(receivedSelection);
  3262. } else {
  3263. throw new IllegalStateException("SelectionModel "
  3264. + selectionModel.getClass().getSimpleName()
  3265. + " does not support selecting the given "
  3266. + selection.size() + " items.");
  3267. }
  3268. } finally {
  3269. applyingSelectionFromClient = false;
  3270. }
  3271. Collection<Object> actualSelection = getSelectedRows();
  3272. // Make sure all selected rows are pinned
  3273. for (Object itemId : actualSelection) {
  3274. if (!getKeyMapper().isPinned(itemId)) {
  3275. getKeyMapper().pin(itemId);
  3276. }
  3277. }
  3278. // Don't mark as dirty since this might be the expected state
  3279. getState(false).selectedKeys = getKeyMapper().getKeys(
  3280. actualSelection);
  3281. JsonObject diffState = getUI().getConnectorTracker()
  3282. .getDiffState(Grid.this);
  3283. final String diffstateKey = "selectedKeys";
  3284. assert diffState.hasKey(diffstateKey) : "Field name has changed";
  3285. if (receivedSelection.equals(actualSelection)) {
  3286. /*
  3287. * We ended up with the same selection state that the client
  3288. * sent us. There's nothing to send back to the client, just
  3289. * update the diffstate so subsequent changes will be
  3290. * detected.
  3291. */
  3292. JsonArray diffSelected = Json.createArray();
  3293. for (String rowKey : getState(false).selectedKeys) {
  3294. diffSelected.set(diffSelected.length(), rowKey);
  3295. }
  3296. diffState.put(diffstateKey, diffSelected);
  3297. } else {
  3298. /*
  3299. * Actual selection is not what the client expects. Make
  3300. * sure the client gets a state change event by clearing the
  3301. * diffstate and marking as dirty
  3302. */
  3303. diffState.remove(diffstateKey);
  3304. markAsDirty();
  3305. }
  3306. }
  3307. @Override
  3308. public void sort(String[] columnIds, SortDirection[] directions,
  3309. boolean userOriginated) {
  3310. assert columnIds.length == directions.length;
  3311. List<SortOrder> order = new ArrayList<SortOrder>(
  3312. columnIds.length);
  3313. for (int i = 0; i < columnIds.length; i++) {
  3314. Object propertyId = getPropertyIdByColumnId(columnIds[i]);
  3315. order.add(new SortOrder(propertyId, directions[i]));
  3316. }
  3317. setSortOrder(order, userOriginated);
  3318. if (!order.equals(getSortOrder())) {
  3319. /*
  3320. * Actual sort order is not what the client expects. Make
  3321. * sure the client gets a state change event by clearing the
  3322. * diffstate and marking as dirty
  3323. */
  3324. ConnectorTracker connectorTracker = getUI()
  3325. .getConnectorTracker();
  3326. JsonObject diffState = connectorTracker
  3327. .getDiffState(Grid.this);
  3328. diffState.remove("sortColumns");
  3329. diffState.remove("sortDirs");
  3330. markAsDirty();
  3331. }
  3332. }
  3333. @Override
  3334. public void selectAll() {
  3335. assert getSelectionModel() instanceof SelectionModel.Multi : "Not a multi selection model!";
  3336. ((SelectionModel.Multi) getSelectionModel()).selectAll();
  3337. }
  3338. @Override
  3339. public void itemClick(String rowKey, String columnId,
  3340. MouseEventDetails details) {
  3341. Object itemId = getKeyMapper().getItemId(rowKey);
  3342. Item item = datasource.getItem(itemId);
  3343. Object propertyId = getPropertyIdByColumnId(columnId);
  3344. fireEvent(new ItemClickEvent(Grid.this, item, itemId,
  3345. propertyId, details));
  3346. }
  3347. @Override
  3348. public void columnsReordered(List<String> newColumnOrder,
  3349. List<String> oldColumnOrder) {
  3350. final String diffStateKey = "columnOrder";
  3351. ConnectorTracker connectorTracker = getUI()
  3352. .getConnectorTracker();
  3353. JsonObject diffState = connectorTracker.getDiffState(Grid.this);
  3354. // discard the change if the columns have been reordered from
  3355. // the server side, as the server side is always right
  3356. if (getState(false).columnOrder.equals(oldColumnOrder)) {
  3357. // Don't mark as dirty since client has the state already
  3358. getState(false).columnOrder = newColumnOrder;
  3359. // write changes to diffState so that possible reverting the
  3360. // column order is sent to client
  3361. assert diffState.hasKey(diffStateKey) : "Field name has changed";
  3362. Type type = null;
  3363. try {
  3364. type = (getState(false).getClass().getDeclaredField(
  3365. diffStateKey).getGenericType());
  3366. } catch (NoSuchFieldException e) {
  3367. e.printStackTrace();
  3368. } catch (SecurityException e) {
  3369. e.printStackTrace();
  3370. }
  3371. EncodeResult encodeResult = JsonCodec.encode(
  3372. getState(false).columnOrder, diffState, type,
  3373. connectorTracker);
  3374. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  3375. fireColumnReorderEvent(true);
  3376. } else {
  3377. // make sure the client is reverted to the order that the
  3378. // server thinks it is
  3379. diffState.remove(diffStateKey);
  3380. markAsDirty();
  3381. }
  3382. }
  3383. @Override
  3384. public void columnVisibilityChanged(String id, boolean hidden,
  3385. boolean userOriginated) {
  3386. final Column column = getColumnByColumnId(id);
  3387. final GridColumnState columnState = column.getState();
  3388. if (columnState.hidden != hidden) {
  3389. columnState.hidden = hidden;
  3390. final String diffStateKey = "columns";
  3391. ConnectorTracker connectorTracker = getUI()
  3392. .getConnectorTracker();
  3393. JsonObject diffState = connectorTracker
  3394. .getDiffState(Grid.this);
  3395. assert diffState.hasKey(diffStateKey) : "Field name has changed";
  3396. Type type = null;
  3397. try {
  3398. type = (getState(false).getClass().getDeclaredField(
  3399. diffStateKey).getGenericType());
  3400. } catch (NoSuchFieldException e) {
  3401. e.printStackTrace();
  3402. } catch (SecurityException e) {
  3403. e.printStackTrace();
  3404. }
  3405. EncodeResult encodeResult = JsonCodec.encode(
  3406. getState(false).columns, diffState, type,
  3407. connectorTracker);
  3408. diffState.put(diffStateKey, encodeResult.getEncodedValue());
  3409. fireColumnVisibilityChangeEvent(column, hidden,
  3410. userOriginated);
  3411. }
  3412. }
  3413. @Override
  3414. public void sendDetailsComponents(int fetchId) {
  3415. getRpcProxy(GridClientRpc.class).setDetailsConnectorChanges(
  3416. detailComponentManager.getAndResetConnectorChanges(),
  3417. fetchId);
  3418. }
  3419. });
  3420. registerRpc(new EditorServerRpc() {
  3421. @Override
  3422. public void bind(int rowIndex) {
  3423. boolean success = false;
  3424. try {
  3425. Object id = getContainerDataSource().getIdByIndex(rowIndex);
  3426. if (editedItemId == null) {
  3427. editedItemId = id;
  3428. }
  3429. if (editedItemId.equals(id)) {
  3430. success = true;
  3431. doEditItem();
  3432. }
  3433. } catch (Exception e) {
  3434. handleError(e);
  3435. }
  3436. getEditorRpc().confirmBind(success);
  3437. }
  3438. @Override
  3439. public void cancel(int rowIndex) {
  3440. try {
  3441. // For future proofing even though cannot currently fail
  3442. doCancelEditor();
  3443. } catch (Exception e) {
  3444. handleError(e);
  3445. }
  3446. }
  3447. @Override
  3448. public void save(int rowIndex) {
  3449. List<String> errorColumnIds = null;
  3450. String errorMessage = null;
  3451. boolean success = false;
  3452. try {
  3453. saveEditor();
  3454. success = true;
  3455. } catch (CommitException e) {
  3456. try {
  3457. CommitErrorEvent event = new CommitErrorEvent(
  3458. Grid.this, e);
  3459. getEditorErrorHandler().commitError(event);
  3460. errorMessage = event.getUserErrorMessage();
  3461. errorColumnIds = new ArrayList<String>();
  3462. for (Column column : event.getErrorColumns()) {
  3463. errorColumnIds.add(column.state.id);
  3464. }
  3465. } catch (Exception ee) {
  3466. // A badly written error handler can throw an exception,
  3467. // which would lock up the Grid
  3468. handleError(ee);
  3469. }
  3470. } catch (Exception e) {
  3471. handleError(e);
  3472. }
  3473. getEditorRpc().confirmSave(success, errorMessage,
  3474. errorColumnIds);
  3475. }
  3476. private void handleError(Exception e) {
  3477. com.vaadin.server.ErrorEvent.findErrorHandler(Grid.this).error(
  3478. new ConnectorErrorEvent(Grid.this, e));
  3479. }
  3480. });
  3481. }
  3482. @Override
  3483. public void beforeClientResponse(boolean initial) {
  3484. try {
  3485. header.sanityCheck();
  3486. footer.sanityCheck();
  3487. } catch (Exception e) {
  3488. e.printStackTrace();
  3489. setComponentError(new ErrorMessage() {
  3490. @Override
  3491. public ErrorLevel getErrorLevel() {
  3492. return ErrorLevel.CRITICAL;
  3493. }
  3494. @Override
  3495. public String getFormattedHtmlMessage() {
  3496. return "Incorrectly merged cells";
  3497. }
  3498. });
  3499. }
  3500. super.beforeClientResponse(initial);
  3501. }
  3502. /**
  3503. * Sets the grid data source.
  3504. *
  3505. * @param container
  3506. * The container data source. Cannot be null.
  3507. * @throws IllegalArgumentException
  3508. * if the data source is null
  3509. */
  3510. public void setContainerDataSource(Container.Indexed container) {
  3511. defaultContainer = false;
  3512. internalSetContainerDataSource(container);
  3513. }
  3514. private void internalSetContainerDataSource(Container.Indexed container) {
  3515. if (container == null) {
  3516. throw new IllegalArgumentException(
  3517. "Cannot set the datasource to null");
  3518. }
  3519. if (datasource == container) {
  3520. return;
  3521. }
  3522. // Remove old listeners
  3523. if (datasource instanceof PropertySetChangeNotifier) {
  3524. ((PropertySetChangeNotifier) datasource)
  3525. .removePropertySetChangeListener(propertyListener);
  3526. }
  3527. if (datasourceExtension != null) {
  3528. removeExtension(datasourceExtension);
  3529. }
  3530. datasource = container;
  3531. resetEditor();
  3532. //
  3533. // Adjust sort order
  3534. //
  3535. if (container instanceof Container.Sortable) {
  3536. // If the container is sortable, go through the current sort order
  3537. // and match each item to the sortable properties of the new
  3538. // container. If the new container does not support an item in the
  3539. // current sort order, that item is removed from the current sort
  3540. // order list.
  3541. Collection<?> sortableProps = ((Container.Sortable) getContainerDataSource())
  3542. .getSortableContainerPropertyIds();
  3543. Iterator<SortOrder> i = sortOrder.iterator();
  3544. while (i.hasNext()) {
  3545. if (!sortableProps.contains(i.next().getPropertyId())) {
  3546. i.remove();
  3547. }
  3548. }
  3549. sort(false);
  3550. } else {
  3551. // Clear sorting order. Don't sort.
  3552. sortOrder.clear();
  3553. }
  3554. datasourceExtension = new RpcDataProviderExtension(container);
  3555. datasourceExtension.extend(this, columnKeys);
  3556. detailComponentManager = datasourceExtension
  3557. .getDetailComponentManager();
  3558. /*
  3559. * selectionModel == null when the invocation comes from the
  3560. * constructor.
  3561. */
  3562. if (selectionModel != null) {
  3563. selectionModel.reset();
  3564. }
  3565. // Listen to changes in properties and remove columns if needed
  3566. if (datasource instanceof PropertySetChangeNotifier) {
  3567. ((PropertySetChangeNotifier) datasource)
  3568. .addPropertySetChangeListener(propertyListener);
  3569. }
  3570. /*
  3571. * activeRowHandler will be updated by the client-side request that
  3572. * occurs on container change - no need to actively re-insert any
  3573. * ValueChangeListeners at this point.
  3574. */
  3575. setFrozenColumnCount(0);
  3576. if (columns.isEmpty()) {
  3577. // Add columns
  3578. for (Object propertyId : datasource.getContainerPropertyIds()) {
  3579. Column column = appendColumn(propertyId);
  3580. // Initial sorting is defined by container
  3581. if (datasource instanceof Sortable) {
  3582. column.setSortable(((Sortable) datasource)
  3583. .getSortableContainerPropertyIds().contains(
  3584. propertyId));
  3585. } else {
  3586. column.setSortable(false);
  3587. }
  3588. }
  3589. } else {
  3590. Collection<?> properties = datasource.getContainerPropertyIds();
  3591. for (Object property : columns.keySet()) {
  3592. if (!properties.contains(property)) {
  3593. throw new IllegalStateException(
  3594. "Found at least one column in Grid that does not exist in the given container: "
  3595. + property
  3596. + " with the header \""
  3597. + getColumn(property).getHeaderCaption()
  3598. + "\"");
  3599. }
  3600. if (!(datasource instanceof Sortable)
  3601. || !((Sortable) datasource)
  3602. .getSortableContainerPropertyIds().contains(
  3603. property)) {
  3604. columns.get(property).setSortable(false);
  3605. }
  3606. }
  3607. }
  3608. }
  3609. /**
  3610. * Returns the grid data source.
  3611. *
  3612. * @return the container data source of the grid
  3613. */
  3614. public Container.Indexed getContainerDataSource() {
  3615. return datasource;
  3616. }
  3617. /**
  3618. * Returns a column based on the property id
  3619. *
  3620. * @param propertyId
  3621. * the property id of the column
  3622. * @return the column or <code>null</code> if not found
  3623. */
  3624. public Column getColumn(Object propertyId) {
  3625. return columns.get(propertyId);
  3626. }
  3627. /**
  3628. * Returns a copy of currently configures columns in their current visual
  3629. * order in this Grid.
  3630. *
  3631. * @return unmodifiable copy of current columns in visual order
  3632. */
  3633. public List<Column> getColumns() {
  3634. List<Column> columns = new ArrayList<Grid.Column>();
  3635. for (String columnId : getState(false).columnOrder) {
  3636. columns.add(getColumnByColumnId(columnId));
  3637. }
  3638. return Collections.unmodifiableList(columns);
  3639. }
  3640. /**
  3641. * Adds a new Column to Grid. Also adds the property to container with data
  3642. * type String, if property for column does not exist in it. Default value
  3643. * for the new property is an empty String.
  3644. * <p>
  3645. * Note that adding a new property is only done for the default container
  3646. * that Grid sets up with the default constructor.
  3647. *
  3648. * @param propertyId
  3649. * the property id of the new column
  3650. * @return the new column
  3651. *
  3652. * @throws IllegalStateException
  3653. * if column for given property already exists in this grid
  3654. */
  3655. public Column addColumn(Object propertyId) throws IllegalStateException {
  3656. if (datasource.getContainerPropertyIds().contains(propertyId)
  3657. && !columns.containsKey(propertyId)) {
  3658. appendColumn(propertyId);
  3659. } else {
  3660. addColumnProperty(propertyId, String.class, "");
  3661. }
  3662. // Inform the data provider of this new column.
  3663. Column column = getColumn(propertyId);
  3664. List<Column> addedColumns = new ArrayList<Column>();
  3665. addedColumns.add(column);
  3666. datasourceExtension.columnsAdded(addedColumns);
  3667. return column;
  3668. }
  3669. /**
  3670. * Adds a new Column to Grid. This function makes sure that the property
  3671. * with the given id and data type exists in the container. If property does
  3672. * not exists, it will be created.
  3673. * <p>
  3674. * Default value for the new property is 0 if type is Integer, Double and
  3675. * Float. If type is String, default value is an empty string. For all other
  3676. * types the default value is null.
  3677. * <p>
  3678. * Note that adding a new property is only done for the default container
  3679. * that Grid sets up with the default constructor.
  3680. *
  3681. * @param propertyId
  3682. * the property id of the new column
  3683. * @param type
  3684. * the data type for the new property
  3685. * @return the new column
  3686. *
  3687. * @throws IllegalStateException
  3688. * if column for given property already exists in this grid or
  3689. * property already exists in the container with wrong type
  3690. */
  3691. public Column addColumn(Object propertyId, Class<?> type) {
  3692. addColumnProperty(propertyId, type, null);
  3693. return getColumn(propertyId);
  3694. }
  3695. protected void addColumnProperty(Object propertyId, Class<?> type,
  3696. Object defaultValue) throws IllegalStateException {
  3697. if (!defaultContainer) {
  3698. throw new IllegalStateException(
  3699. "Container for this Grid is not a default container from Grid() constructor");
  3700. }
  3701. if (!columns.containsKey(propertyId)) {
  3702. if (!datasource.getContainerPropertyIds().contains(propertyId)) {
  3703. datasource.addContainerProperty(propertyId, type, defaultValue);
  3704. } else {
  3705. Property<?> containerProperty = datasource
  3706. .getContainerProperty(datasource.firstItemId(),
  3707. propertyId);
  3708. if (containerProperty.getType() == type) {
  3709. appendColumn(propertyId);
  3710. } else {
  3711. throw new IllegalStateException(
  3712. "DataSource already has the given property "
  3713. + propertyId + " with a different type");
  3714. }
  3715. }
  3716. } else {
  3717. throw new IllegalStateException(
  3718. "Grid already has a column for property " + propertyId);
  3719. }
  3720. }
  3721. /**
  3722. * Removes all columns from this Grid.
  3723. */
  3724. public void removeAllColumns() {
  3725. List<Column> removed = new ArrayList<Column>(columns.values());
  3726. Set<Object> properties = new HashSet<Object>(columns.keySet());
  3727. for (Object propertyId : properties) {
  3728. removeColumn(propertyId);
  3729. }
  3730. datasourceExtension.columnsRemoved(removed);
  3731. }
  3732. /**
  3733. * Used internally by the {@link Grid} to get a {@link Column} by
  3734. * referencing its generated state id. Also used by {@link Column} to verify
  3735. * if it has been detached from the {@link Grid}.
  3736. *
  3737. * @param columnId
  3738. * the client id generated for the column when the column is
  3739. * added to the grid
  3740. * @return the column with the id or <code>null</code> if not found
  3741. */
  3742. Column getColumnByColumnId(String columnId) {
  3743. Object propertyId = getPropertyIdByColumnId(columnId);
  3744. return getColumn(propertyId);
  3745. }
  3746. /**
  3747. * Used internally by the {@link Grid} to get a property id by referencing
  3748. * the columns generated state id.
  3749. *
  3750. * @param columnId
  3751. * The state id of the column
  3752. * @return The column instance or null if not found
  3753. */
  3754. Object getPropertyIdByColumnId(String columnId) {
  3755. return columnKeys.get(columnId);
  3756. }
  3757. /**
  3758. * Returns whether column reordering is allowed. Default value is
  3759. * <code>false</code>.
  3760. *
  3761. * @since 7.5.0
  3762. * @return true if reordering is allowed
  3763. */
  3764. public boolean isColumnReorderingAllowed() {
  3765. return getState(false).columnReorderingAllowed;
  3766. }
  3767. /**
  3768. * Sets whether or not column reordering is allowed. Default value is
  3769. * <code>false</code>.
  3770. *
  3771. * @since 7.5.0
  3772. * @param columnReorderingAllowed
  3773. * specifies whether column reordering is allowed
  3774. */
  3775. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  3776. if (isColumnReorderingAllowed() != columnReorderingAllowed) {
  3777. getState().columnReorderingAllowed = columnReorderingAllowed;
  3778. }
  3779. }
  3780. @Override
  3781. protected GridState getState() {
  3782. return (GridState) super.getState();
  3783. }
  3784. @Override
  3785. protected GridState getState(boolean markAsDirty) {
  3786. return (GridState) super.getState(markAsDirty);
  3787. }
  3788. /**
  3789. * Creates a new column based on a property id and appends it as the last
  3790. * column.
  3791. *
  3792. * @param datasourcePropertyId
  3793. * The property id of a property in the datasource
  3794. */
  3795. private Column appendColumn(Object datasourcePropertyId) {
  3796. if (datasourcePropertyId == null) {
  3797. throw new IllegalArgumentException("Property id cannot be null");
  3798. }
  3799. assert datasource.getContainerPropertyIds().contains(
  3800. datasourcePropertyId) : "Datasource should contain the property id";
  3801. GridColumnState columnState = new GridColumnState();
  3802. columnState.id = columnKeys.key(datasourcePropertyId);
  3803. Column column = new Column(this, columnState, datasourcePropertyId);
  3804. columns.put(datasourcePropertyId, column);
  3805. getState().columns.add(columnState);
  3806. getState().columnOrder.add(columnState.id);
  3807. header.addColumn(datasourcePropertyId);
  3808. footer.addColumn(datasourcePropertyId);
  3809. String humanFriendlyPropertyId = SharedUtil
  3810. .propertyIdToHumanFriendly(String.valueOf(datasourcePropertyId));
  3811. column.setHeaderCaption(humanFriendlyPropertyId);
  3812. column.setHidingToggleCaption(humanFriendlyPropertyId);
  3813. if (datasource instanceof Sortable
  3814. && ((Sortable) datasource).getSortableContainerPropertyIds()
  3815. .contains(datasourcePropertyId)) {
  3816. column.setSortable(true);
  3817. }
  3818. return column;
  3819. }
  3820. /**
  3821. * Removes a column from Grid based on a property id.
  3822. *
  3823. * @param propertyId
  3824. * The property id of column to be removed
  3825. *
  3826. * @throws IllegalArgumentException
  3827. * if there is no column for given property id in this grid
  3828. */
  3829. public void removeColumn(Object propertyId) throws IllegalArgumentException {
  3830. if (!columns.keySet().contains(propertyId)) {
  3831. throw new IllegalArgumentException(
  3832. "There is no column for given property id " + propertyId);
  3833. }
  3834. List<Column> removed = new ArrayList<Column>();
  3835. removed.add(getColumn(propertyId));
  3836. internalRemoveColumn(propertyId);
  3837. datasourceExtension.columnsRemoved(removed);
  3838. }
  3839. private void internalRemoveColumn(Object propertyId) {
  3840. setEditorField(propertyId, null);
  3841. header.removeColumn(propertyId);
  3842. footer.removeColumn(propertyId);
  3843. Column column = columns.remove(propertyId);
  3844. getState().columnOrder.remove(columnKeys.key(propertyId));
  3845. getState().columns.remove(column.getState());
  3846. removeExtension(column.getRenderer());
  3847. }
  3848. /**
  3849. * Sets the columns and their order for the grid. Current columns whose
  3850. * property id is not in propertyIds are removed. Similarly, a column is
  3851. * added for any property id in propertyIds that has no corresponding column
  3852. * in this Grid.
  3853. *
  3854. * @since 7.5.0
  3855. *
  3856. * @param propertyIds
  3857. * properties in the desired column order
  3858. */
  3859. public void setColumns(Object... propertyIds) {
  3860. Set<?> removePids = new HashSet<Object>(columns.keySet());
  3861. removePids.removeAll(Arrays.asList(propertyIds));
  3862. for (Object removePid : removePids) {
  3863. removeColumn(removePid);
  3864. }
  3865. Set<?> addPids = new HashSet<Object>(Arrays.asList(propertyIds));
  3866. addPids.removeAll(columns.keySet());
  3867. for (Object propertyId : addPids) {
  3868. addColumn(propertyId);
  3869. }
  3870. setColumnOrder(propertyIds);
  3871. }
  3872. /**
  3873. * Sets a new column order for the grid. All columns which are not ordered
  3874. * here will remain in the order they were before as the last columns of
  3875. * grid.
  3876. *
  3877. * @param propertyIds
  3878. * properties in the order columns should be
  3879. */
  3880. public void setColumnOrder(Object... propertyIds) {
  3881. List<String> columnOrder = new ArrayList<String>();
  3882. for (Object propertyId : propertyIds) {
  3883. if (columns.containsKey(propertyId)) {
  3884. columnOrder.add(columnKeys.key(propertyId));
  3885. } else {
  3886. throw new IllegalArgumentException(
  3887. "Grid does not contain column for property "
  3888. + String.valueOf(propertyId));
  3889. }
  3890. }
  3891. List<String> stateColumnOrder = getState().columnOrder;
  3892. if (stateColumnOrder.size() != columnOrder.size()) {
  3893. stateColumnOrder.removeAll(columnOrder);
  3894. columnOrder.addAll(stateColumnOrder);
  3895. }
  3896. getState().columnOrder = columnOrder;
  3897. fireColumnReorderEvent(false);
  3898. }
  3899. /**
  3900. * Sets the number of frozen columns in this grid. Setting the count to 0
  3901. * means that no data columns will be frozen, but the built-in selection
  3902. * checkbox column will still be frozen if it's in use. Setting the count to
  3903. * -1 will also disable the selection column.
  3904. * <p>
  3905. * The default value is 0.
  3906. *
  3907. * @param numberOfColumns
  3908. * the number of columns that should be frozen
  3909. *
  3910. * @throws IllegalArgumentException
  3911. * if the column count is < 0 or > the number of visible columns
  3912. */
  3913. public void setFrozenColumnCount(int numberOfColumns) {
  3914. if (numberOfColumns < -1 || numberOfColumns > columns.size()) {
  3915. throw new IllegalArgumentException(
  3916. "count must be between -1 and the current number of columns ("
  3917. + columns.size() + "): " + numberOfColumns);
  3918. }
  3919. getState().frozenColumnCount = numberOfColumns;
  3920. }
  3921. /**
  3922. * Gets the number of frozen columns in this grid. 0 means that no data
  3923. * columns will be frozen, but the built-in selection checkbox column will
  3924. * still be frozen if it's in use. -1 means that not even the selection
  3925. * column is frozen.
  3926. * <p>
  3927. * <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
  3928. * columns} in the count.
  3929. *
  3930. * @see #setFrozenColumnCount(int)
  3931. *
  3932. * @return the number of frozen columns
  3933. */
  3934. public int getFrozenColumnCount() {
  3935. return getState(false).frozenColumnCount;
  3936. }
  3937. /**
  3938. * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
  3939. * <p>
  3940. * If the item has visible details, its size will also be taken into
  3941. * account.
  3942. *
  3943. * @param itemId
  3944. * id of item to scroll to.
  3945. * @throws IllegalArgumentException
  3946. * if the provided id is not recognized by the data source.
  3947. */
  3948. public void scrollTo(Object itemId) throws IllegalArgumentException {
  3949. scrollTo(itemId, ScrollDestination.ANY);
  3950. }
  3951. /**
  3952. * Scrolls to a certain item, using user-specified scroll destination.
  3953. * <p>
  3954. * If the item has visible details, its size will also be taken into
  3955. * account.
  3956. *
  3957. * @param itemId
  3958. * id of item to scroll to.
  3959. * @param destination
  3960. * value specifying desired position of scrolled-to row.
  3961. * @throws IllegalArgumentException
  3962. * if the provided id is not recognized by the data source.
  3963. */
  3964. public void scrollTo(Object itemId, ScrollDestination destination)
  3965. throws IllegalArgumentException {
  3966. int row = datasource.indexOfId(itemId);
  3967. if (row == -1) {
  3968. throw new IllegalArgumentException(
  3969. "Item with specified ID does not exist in data source");
  3970. }
  3971. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  3972. clientRPC.scrollToRow(row, destination);
  3973. }
  3974. /**
  3975. * Scrolls to the beginning of the first data row.
  3976. */
  3977. public void scrollToStart() {
  3978. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  3979. clientRPC.scrollToStart();
  3980. }
  3981. /**
  3982. * Scrolls to the end of the last data row.
  3983. */
  3984. public void scrollToEnd() {
  3985. GridClientRpc clientRPC = getRpcProxy(GridClientRpc.class);
  3986. clientRPC.scrollToEnd();
  3987. }
  3988. /**
  3989. * Sets the number of rows that should be visible in Grid's body, while
  3990. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  3991. * <p>
  3992. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  3993. * remembered, and applied once the mode is applied.
  3994. *
  3995. * @param rows
  3996. * The height in terms of number of rows displayed in Grid's
  3997. * body. If Grid doesn't contain enough rows, white space is
  3998. * displayed instead. If <code>null</code> is given, then Grid's
  3999. * height is undefined
  4000. * @throws IllegalArgumentException
  4001. * if {@code rows} is zero or less
  4002. * @throws IllegalArgumentException
  4003. * if {@code rows} is {@link Double#isInifinite(double)
  4004. * infinite}
  4005. * @throws IllegalArgumentException
  4006. * if {@code rows} is {@link Double#isNaN(double) NaN}
  4007. */
  4008. public void setHeightByRows(double rows) {
  4009. if (rows <= 0.0d) {
  4010. throw new IllegalArgumentException(
  4011. "More than zero rows must be shown.");
  4012. } else if (Double.isInfinite(rows)) {
  4013. throw new IllegalArgumentException(
  4014. "Grid doesn't support infinite heights");
  4015. } else if (Double.isNaN(rows)) {
  4016. throw new IllegalArgumentException("NaN is not a valid row count");
  4017. }
  4018. getState().heightByRows = rows;
  4019. }
  4020. /**
  4021. * Gets the amount of rows in Grid's body that are shown, while
  4022. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  4023. *
  4024. * @return the amount of rows that are being shown in Grid's body
  4025. * @see #setHeightByRows(double)
  4026. */
  4027. public double getHeightByRows() {
  4028. return getState(false).heightByRows;
  4029. }
  4030. /**
  4031. * {@inheritDoc}
  4032. * <p>
  4033. * <em>Note:</em> This method will change the widget's size in the browser
  4034. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  4035. *
  4036. * @see #setHeightMode(HeightMode)
  4037. */
  4038. @Override
  4039. public void setHeight(float height, Unit unit) {
  4040. super.setHeight(height, unit);
  4041. }
  4042. /**
  4043. * Defines the mode in which the Grid widget's height is calculated.
  4044. * <p>
  4045. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  4046. * via a {@code setHeight}-method, and behave as a traditional Component.
  4047. * <p>
  4048. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  4049. * will display as many rows as {@link #getHeightByRows()} defines.
  4050. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  4051. * will resize itself to still display the required amount of rows in its
  4052. * body. It also takes the horizontal scrollbar into account.
  4053. *
  4054. * @param heightMode
  4055. * the mode in to which Grid should be set
  4056. */
  4057. public void setHeightMode(HeightMode heightMode) {
  4058. /*
  4059. * This method is a workaround for the fact that Vaadin re-applies
  4060. * widget dimensions (height/width) on each state change event. The
  4061. * original design was to have setHeight an setHeightByRow be equals,
  4062. * and whichever was called the latest was considered in effect.
  4063. *
  4064. * But, because of Vaadin always calling setHeight on the widget, this
  4065. * approach doesn't work.
  4066. */
  4067. getState().heightMode = heightMode;
  4068. }
  4069. /**
  4070. * Returns the current {@link HeightMode} the Grid is in.
  4071. * <p>
  4072. * Defaults to {@link HeightMode#CSS}.
  4073. *
  4074. * @return the current HeightMode
  4075. */
  4076. public HeightMode getHeightMode() {
  4077. return getState(false).heightMode;
  4078. }
  4079. /* Selection related methods: */
  4080. /**
  4081. * Takes a new {@link SelectionModel} into use.
  4082. * <p>
  4083. * The SelectionModel that is previously in use will have all its items
  4084. * deselected.
  4085. * <p>
  4086. * If the given SelectionModel is already in use, this method does nothing.
  4087. *
  4088. * @param selectionModel
  4089. * the new SelectionModel to use
  4090. * @throws IllegalArgumentException
  4091. * if {@code selectionModel} is <code>null</code>
  4092. */
  4093. public void setSelectionModel(SelectionModel selectionModel)
  4094. throws IllegalArgumentException {
  4095. if (selectionModel == null) {
  4096. throw new IllegalArgumentException(
  4097. "Selection model may not be null");
  4098. }
  4099. if (this.selectionModel != selectionModel) {
  4100. // this.selectionModel is null on init
  4101. if (this.selectionModel != null) {
  4102. this.selectionModel.reset();
  4103. this.selectionModel.setGrid(null);
  4104. }
  4105. this.selectionModel = selectionModel;
  4106. this.selectionModel.setGrid(this);
  4107. this.selectionModel.reset();
  4108. if (selectionModel.getClass().equals(SingleSelectionModel.class)) {
  4109. getState().selectionMode = SharedSelectionMode.SINGLE;
  4110. } else if (selectionModel.getClass().equals(
  4111. MultiSelectionModel.class)) {
  4112. getState().selectionMode = SharedSelectionMode.MULTI;
  4113. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  4114. getState().selectionMode = SharedSelectionMode.NONE;
  4115. } else {
  4116. throw new UnsupportedOperationException("Grid currently "
  4117. + "supports only its own bundled selection models");
  4118. }
  4119. }
  4120. }
  4121. /**
  4122. * Returns the currently used {@link SelectionModel}.
  4123. *
  4124. * @return the currently used SelectionModel
  4125. */
  4126. public SelectionModel getSelectionModel() {
  4127. return selectionModel;
  4128. }
  4129. /**
  4130. * Sets the Grid's selection mode.
  4131. * <p>
  4132. * Grid supports three selection modes: multiselect, single select and no
  4133. * selection, and this is a convenience method for choosing between one of
  4134. * them.
  4135. * <p>
  4136. * Technically, this method is a shortcut that can be used instead of
  4137. * calling {@code setSelectionModel} with a specific SelectionModel
  4138. * instance. Grid comes with three built-in SelectionModel classes, and the
  4139. * {@link SelectionMode} enum represents each of them.
  4140. * <p>
  4141. * Essentially, the two following method calls are equivalent:
  4142. * <p>
  4143. * <code><pre>
  4144. * grid.setSelectionMode(SelectionMode.MULTI);
  4145. * grid.setSelectionModel(new MultiSelectionMode());
  4146. * </pre></code>
  4147. *
  4148. *
  4149. * @param selectionMode
  4150. * the selection mode to switch to
  4151. * @return The {@link SelectionModel} instance that was taken into use
  4152. * @throws IllegalArgumentException
  4153. * if {@code selectionMode} is <code>null</code>
  4154. * @see SelectionModel
  4155. */
  4156. public SelectionModel setSelectionMode(final SelectionMode selectionMode)
  4157. throws IllegalArgumentException {
  4158. if (selectionMode == null) {
  4159. throw new IllegalArgumentException("selection mode may not be null");
  4160. }
  4161. final SelectionModel newSelectionModel = selectionMode.createModel();
  4162. setSelectionModel(newSelectionModel);
  4163. return newSelectionModel;
  4164. }
  4165. /**
  4166. * Checks whether an item is selected or not.
  4167. *
  4168. * @param itemId
  4169. * the item id to check for
  4170. * @return <code>true</code> iff the item is selected
  4171. */
  4172. // keep this javadoc in sync with SelectionModel.isSelected
  4173. public boolean isSelected(Object itemId) {
  4174. return selectionModel.isSelected(itemId);
  4175. }
  4176. /**
  4177. * Returns a collection of all the currently selected itemIds.
  4178. * <p>
  4179. * This method is a shorthand that delegates to the
  4180. * {@link #getSelectionModel() selection model}.
  4181. *
  4182. * @return a collection of all the currently selected itemIds
  4183. */
  4184. // keep this javadoc in sync with SelectionModel.getSelectedRows
  4185. public Collection<Object> getSelectedRows() {
  4186. return getSelectionModel().getSelectedRows();
  4187. }
  4188. /**
  4189. * Gets the item id of the currently selected item.
  4190. * <p>
  4191. * This method is a shorthand that delegates to the
  4192. * {@link #getSelectionModel() selection model}. Only
  4193. * {@link SelectionModel.Single} is supported.
  4194. *
  4195. * @return the item id of the currently selected item, or <code>null</code>
  4196. * if nothing is selected
  4197. * @throws IllegalStateException
  4198. * if the selection model does not implement
  4199. * {@code SelectionModel.Single}
  4200. */
  4201. // keep this javadoc in sync with SelectionModel.Single.getSelectedRow
  4202. public Object getSelectedRow() throws IllegalStateException {
  4203. if (selectionModel instanceof SelectionModel.Single) {
  4204. return ((SelectionModel.Single) selectionModel).getSelectedRow();
  4205. } else if (selectionModel instanceof SelectionModel.Multi) {
  4206. throw new IllegalStateException("Cannot get unique selected row: "
  4207. + "Grid is in multiselect mode "
  4208. + "(the current selection model is "
  4209. + selectionModel.getClass().getName() + ").");
  4210. } else if (selectionModel instanceof SelectionModel.None) {
  4211. throw new IllegalStateException("Cannot get selected row: "
  4212. + "Grid selection is disabled "
  4213. + "(the current selection model is "
  4214. + selectionModel.getClass().getName() + ").");
  4215. } else {
  4216. throw new IllegalStateException("Cannot get selected row: "
  4217. + "Grid selection model does not implement "
  4218. + SelectionModel.Single.class.getName() + " or "
  4219. + SelectionModel.Multi.class.getName()
  4220. + "(the current model is "
  4221. + selectionModel.getClass().getName() + ").");
  4222. }
  4223. }
  4224. /**
  4225. * Marks an item as selected.
  4226. * <p>
  4227. * This method is a shorthand that delegates to the
  4228. * {@link #getSelectionModel() selection model}. Only
  4229. * {@link SelectionModel.Single} and {@link SelectionModel.Multi} are
  4230. * supported.
  4231. *
  4232. * @param itemIds
  4233. * the itemId to mark as selected
  4234. * @return <code>true</code> if the selection state changed,
  4235. * <code>false</code> if the itemId already was selected
  4236. * @throws IllegalArgumentException
  4237. * if the {@code itemId} doesn't exist in the currently active
  4238. * Container
  4239. * @throws IllegalStateException
  4240. * if the selection was illegal. One such reason might be that
  4241. * the implementation already had an item selected, and that
  4242. * needs to be explicitly deselected before re-selecting
  4243. * something.
  4244. * @throws IllegalStateException
  4245. * if the selection model does not implement
  4246. * {@code SelectionModel.Single} or {@code SelectionModel.Multi}
  4247. */
  4248. // keep this javadoc in sync with SelectionModel.Single.select
  4249. public boolean select(Object itemId) throws IllegalArgumentException,
  4250. IllegalStateException {
  4251. if (selectionModel instanceof SelectionModel.Single) {
  4252. return ((SelectionModel.Single) selectionModel).select(itemId);
  4253. } else if (selectionModel instanceof SelectionModel.Multi) {
  4254. return ((SelectionModel.Multi) selectionModel).select(itemId);
  4255. } else if (selectionModel instanceof SelectionModel.None) {
  4256. throw new IllegalStateException("Cannot select row '" + itemId
  4257. + "': Grid selection is disabled "
  4258. + "(the current selection model is "
  4259. + selectionModel.getClass().getName() + ").");
  4260. } else {
  4261. throw new IllegalStateException("Cannot select row '" + itemId
  4262. + "': Grid selection model does not implement "
  4263. + SelectionModel.Single.class.getName() + " or "
  4264. + SelectionModel.Multi.class.getName()
  4265. + "(the current model is "
  4266. + selectionModel.getClass().getName() + ").");
  4267. }
  4268. }
  4269. /**
  4270. * Marks an item as unselected.
  4271. * <p>
  4272. * This method is a shorthand that delegates to the
  4273. * {@link #getSelectionModel() selection model}. Only
  4274. * {@link SelectionModel.Single} and {@link SelectionModel.Multi} are
  4275. * supported.
  4276. *
  4277. * @param itemId
  4278. * the itemId to remove from being selected
  4279. * @return <code>true</code> if the selection state changed,
  4280. * <code>false</code> if the itemId was already selected
  4281. * @throws IllegalArgumentException
  4282. * if the {@code itemId} doesn't exist in the currently active
  4283. * Container
  4284. * @throws IllegalStateException
  4285. * if the deselection was illegal. One such reason might be that
  4286. * the implementation requires one or more items to be selected
  4287. * at all times.
  4288. * @throws IllegalStateException
  4289. * if the selection model does not implement
  4290. * {@code SelectionModel.Single} or {code SelectionModel.Multi}
  4291. */
  4292. // keep this javadoc in sync with SelectionModel.Single.deselect
  4293. public boolean deselect(Object itemId) throws IllegalStateException {
  4294. if (selectionModel instanceof SelectionModel.Single) {
  4295. if (isSelected(itemId)) {
  4296. return ((SelectionModel.Single) selectionModel).select(null);
  4297. }
  4298. return false;
  4299. } else if (selectionModel instanceof SelectionModel.Multi) {
  4300. return ((SelectionModel.Multi) selectionModel).deselect(itemId);
  4301. } else if (selectionModel instanceof SelectionModel.None) {
  4302. throw new IllegalStateException("Cannot deselect row '" + itemId
  4303. + "': Grid selection is disabled "
  4304. + "(the current selection model is "
  4305. + selectionModel.getClass().getName() + ").");
  4306. } else {
  4307. throw new IllegalStateException("Cannot deselect row '" + itemId
  4308. + "': Grid selection model does not implement "
  4309. + SelectionModel.Single.class.getName() + " or "
  4310. + SelectionModel.Multi.class.getName()
  4311. + "(the current model is "
  4312. + selectionModel.getClass().getName() + ").");
  4313. }
  4314. }
  4315. /**
  4316. * Fires a selection change event.
  4317. * <p>
  4318. * <strong>Note:</strong> This is not a method that should be called by
  4319. * application logic. This method is publicly accessible only so that
  4320. * {@link SelectionModel SelectionModels} would be able to inform Grid of
  4321. * these events.
  4322. *
  4323. * @param addedSelections
  4324. * the selections that were added by this event
  4325. * @param removedSelections
  4326. * the selections that were removed by this event
  4327. */
  4328. public void fireSelectionEvent(Collection<Object> oldSelection,
  4329. Collection<Object> newSelection) {
  4330. fireEvent(new SelectionEvent(this, oldSelection, newSelection));
  4331. }
  4332. @Override
  4333. public void addSelectionListener(SelectionListener listener) {
  4334. addListener(SelectionEvent.class, listener, SELECTION_CHANGE_METHOD);
  4335. }
  4336. @Override
  4337. public void removeSelectionListener(SelectionListener listener) {
  4338. removeListener(SelectionEvent.class, listener, SELECTION_CHANGE_METHOD);
  4339. }
  4340. private void fireColumnReorderEvent(boolean userOriginated) {
  4341. fireEvent(new ColumnReorderEvent(this, userOriginated));
  4342. }
  4343. /**
  4344. * Registers a new column reorder listener.
  4345. *
  4346. * @since 7.5.0
  4347. * @param listener
  4348. * the listener to register
  4349. */
  4350. public void addColumnReorderListener(ColumnReorderListener listener) {
  4351. addListener(ColumnReorderEvent.class, listener, COLUMN_REORDER_METHOD);
  4352. }
  4353. /**
  4354. * Removes a previously registered column reorder listener.
  4355. *
  4356. * @since 7.5.0
  4357. * @param listener
  4358. * the listener to remove
  4359. */
  4360. public void removeColumnReorderListener(ColumnReorderListener listener) {
  4361. removeListener(ColumnReorderEvent.class, listener,
  4362. COLUMN_REORDER_METHOD);
  4363. }
  4364. /**
  4365. * Gets the
  4366. * {@link com.vaadin.data.RpcDataProviderExtension.DataProviderKeyMapper
  4367. * DataProviderKeyMapper} being used by the data source.
  4368. *
  4369. * @return the key mapper being used by the data source
  4370. */
  4371. DataProviderKeyMapper getKeyMapper() {
  4372. return datasourceExtension.getKeyMapper();
  4373. }
  4374. /**
  4375. * Adds a renderer to this grid's connector hierarchy.
  4376. *
  4377. * @param renderer
  4378. * the renderer to add
  4379. */
  4380. void addRenderer(Renderer<?> renderer) {
  4381. addExtension(renderer);
  4382. }
  4383. /**
  4384. * Sets the current sort order using the fluid Sort API. Read the
  4385. * documentation for {@link Sort} for more information.
  4386. * <p>
  4387. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  4388. * all possible sorting indicators.
  4389. *
  4390. * @param s
  4391. * a sort instance
  4392. *
  4393. * @throws IllegalStateException
  4394. * if container is not sortable (does not implement
  4395. * Container.Sortable)
  4396. * @throws IllegalArgumentException
  4397. * if trying to sort by non-existing property
  4398. */
  4399. public void sort(Sort s) {
  4400. setSortOrder(s.build());
  4401. }
  4402. /**
  4403. * Sort this Grid in ascending order by a specified property.
  4404. * <p>
  4405. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  4406. * all possible sorting indicators.
  4407. *
  4408. * @param propertyId
  4409. * a property ID
  4410. *
  4411. * @throws IllegalStateException
  4412. * if container is not sortable (does not implement
  4413. * Container.Sortable)
  4414. * @throws IllegalArgumentException
  4415. * if trying to sort by non-existing property
  4416. */
  4417. public void sort(Object propertyId) {
  4418. sort(propertyId, SortDirection.ASCENDING);
  4419. }
  4420. /**
  4421. * Sort this Grid in user-specified {@link SortOrder} by a property.
  4422. * <p>
  4423. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  4424. * all possible sorting indicators.
  4425. *
  4426. * @param propertyId
  4427. * a property ID
  4428. * @param direction
  4429. * a sort order value (ascending/descending)
  4430. *
  4431. * @throws IllegalStateException
  4432. * if container is not sortable (does not implement
  4433. * Container.Sortable)
  4434. * @throws IllegalArgumentException
  4435. * if trying to sort by non-existing property
  4436. */
  4437. public void sort(Object propertyId, SortDirection direction) {
  4438. sort(Sort.by(propertyId, direction));
  4439. }
  4440. /**
  4441. * Clear the current sort order, and re-sort the grid.
  4442. */
  4443. public void clearSortOrder() {
  4444. sortOrder.clear();
  4445. sort(false);
  4446. }
  4447. /**
  4448. * Sets the sort order to use.
  4449. * <p>
  4450. * <em>Note:</em> Sorting by a property that has no column in Grid will hide
  4451. * all possible sorting indicators.
  4452. *
  4453. * @param order
  4454. * a sort order list.
  4455. *
  4456. * @throws IllegalStateException
  4457. * if container is not sortable (does not implement
  4458. * Container.Sortable)
  4459. * @throws IllegalArgumentException
  4460. * if order is null or trying to sort by non-existing property
  4461. */
  4462. public void setSortOrder(List<SortOrder> order) {
  4463. setSortOrder(order, false);
  4464. }
  4465. private void setSortOrder(List<SortOrder> order, boolean userOriginated)
  4466. throws IllegalStateException, IllegalArgumentException {
  4467. if (!(getContainerDataSource() instanceof Container.Sortable)) {
  4468. throw new IllegalStateException(
  4469. "Attached container is not sortable (does not implement Container.Sortable)");
  4470. }
  4471. if (order == null) {
  4472. throw new IllegalArgumentException("Order list may not be null!");
  4473. }
  4474. sortOrder.clear();
  4475. Collection<?> sortableProps = ((Container.Sortable) getContainerDataSource())
  4476. .getSortableContainerPropertyIds();
  4477. for (SortOrder o : order) {
  4478. if (!sortableProps.contains(o.getPropertyId())) {
  4479. throw new IllegalArgumentException(
  4480. "Property "
  4481. + o.getPropertyId()
  4482. + " does not exist or is not sortable in the current container");
  4483. }
  4484. }
  4485. sortOrder.addAll(order);
  4486. sort(userOriginated);
  4487. }
  4488. /**
  4489. * Get the current sort order list.
  4490. *
  4491. * @return a sort order list
  4492. */
  4493. public List<SortOrder> getSortOrder() {
  4494. return Collections.unmodifiableList(sortOrder);
  4495. }
  4496. /**
  4497. * Apply sorting to data source.
  4498. */
  4499. private void sort(boolean userOriginated) {
  4500. Container c = getContainerDataSource();
  4501. if (c instanceof Container.Sortable) {
  4502. Container.Sortable cs = (Container.Sortable) c;
  4503. final int items = sortOrder.size();
  4504. Object[] propertyIds = new Object[items];
  4505. boolean[] directions = new boolean[items];
  4506. SortDirection[] stateDirs = new SortDirection[items];
  4507. for (int i = 0; i < items; ++i) {
  4508. SortOrder order = sortOrder.get(i);
  4509. stateDirs[i] = order.getDirection();
  4510. propertyIds[i] = order.getPropertyId();
  4511. switch (order.getDirection()) {
  4512. case ASCENDING:
  4513. directions[i] = true;
  4514. break;
  4515. case DESCENDING:
  4516. directions[i] = false;
  4517. break;
  4518. default:
  4519. throw new IllegalArgumentException("getDirection() of "
  4520. + order + " returned an unexpected value");
  4521. }
  4522. }
  4523. cs.sort(propertyIds, directions);
  4524. if (columns.keySet().containsAll(Arrays.asList(propertyIds))) {
  4525. String[] columnKeys = new String[items];
  4526. for (int i = 0; i < items; ++i) {
  4527. columnKeys[i] = this.columnKeys.key(propertyIds[i]);
  4528. }
  4529. getState().sortColumns = columnKeys;
  4530. getState(false).sortDirs = stateDirs;
  4531. } else {
  4532. // Not all sorted properties are in Grid. Remove any indicators.
  4533. getState().sortColumns = new String[] {};
  4534. getState(false).sortDirs = new SortDirection[] {};
  4535. }
  4536. fireEvent(new SortEvent(this, new ArrayList<SortOrder>(sortOrder),
  4537. userOriginated));
  4538. } else {
  4539. throw new IllegalStateException(
  4540. "Container is not sortable (does not implement Container.Sortable)");
  4541. }
  4542. }
  4543. /**
  4544. * Adds a sort order change listener that gets notified when the sort order
  4545. * changes.
  4546. *
  4547. * @param listener
  4548. * the sort order change listener to add
  4549. */
  4550. @Override
  4551. public void addSortListener(SortListener listener) {
  4552. addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  4553. }
  4554. /**
  4555. * Removes a sort order change listener previously added using
  4556. * {@link #addSortListener(SortListener)}.
  4557. *
  4558. * @param listener
  4559. * the sort order change listener to remove
  4560. */
  4561. @Override
  4562. public void removeSortListener(SortListener listener) {
  4563. removeListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
  4564. }
  4565. /* Grid Headers */
  4566. /**
  4567. * Returns the header section of this grid. The default header contains a
  4568. * single row displaying the column captions.
  4569. *
  4570. * @return the header
  4571. */
  4572. protected Header getHeader() {
  4573. return header;
  4574. }
  4575. /**
  4576. * Gets the header row at given index.
  4577. *
  4578. * @param rowIndex
  4579. * 0 based index for row. Counted from top to bottom
  4580. * @return header row at given index
  4581. * @throws IllegalArgumentException
  4582. * if no row exists at given index
  4583. */
  4584. public HeaderRow getHeaderRow(int rowIndex) {
  4585. return header.getRow(rowIndex);
  4586. }
  4587. /**
  4588. * Inserts a new row at the given position to the header section. Shifts the
  4589. * row currently at that position and any subsequent rows down (adds one to
  4590. * their indices).
  4591. *
  4592. * @param index
  4593. * the position at which to insert the row
  4594. * @return the new row
  4595. *
  4596. * @throws IllegalArgumentException
  4597. * if the index is less than 0 or greater than row count
  4598. * @see #appendHeaderRow()
  4599. * @see #prependHeaderRow()
  4600. * @see #removeHeaderRow(HeaderRow)
  4601. * @see #removeHeaderRow(int)
  4602. */
  4603. public HeaderRow addHeaderRowAt(int index) {
  4604. return header.addRowAt(index);
  4605. }
  4606. /**
  4607. * Adds a new row at the bottom of the header section.
  4608. *
  4609. * @return the new row
  4610. * @see #prependHeaderRow()
  4611. * @see #addHeaderRowAt(int)
  4612. * @see #removeHeaderRow(HeaderRow)
  4613. * @see #removeHeaderRow(int)
  4614. */
  4615. public HeaderRow appendHeaderRow() {
  4616. return header.appendRow();
  4617. }
  4618. /**
  4619. * Returns the current default row of the header section. The default row is
  4620. * a special header row providing a user interface for sorting columns.
  4621. * Setting a header text for column updates cells in the default header.
  4622. *
  4623. * @return the default row or null if no default row set
  4624. */
  4625. public HeaderRow getDefaultHeaderRow() {
  4626. return header.getDefaultRow();
  4627. }
  4628. /**
  4629. * Gets the row count for the header section.
  4630. *
  4631. * @return row count
  4632. */
  4633. public int getHeaderRowCount() {
  4634. return header.getRowCount();
  4635. }
  4636. /**
  4637. * Adds a new row at the top of the header section.
  4638. *
  4639. * @return the new row
  4640. * @see #appendHeaderRow()
  4641. * @see #addHeaderRowAt(int)
  4642. * @see #removeHeaderRow(HeaderRow)
  4643. * @see #removeHeaderRow(int)
  4644. */
  4645. public HeaderRow prependHeaderRow() {
  4646. return header.prependRow();
  4647. }
  4648. /**
  4649. * Removes the given row from the header section.
  4650. *
  4651. * @param row
  4652. * the row to be removed
  4653. *
  4654. * @throws IllegalArgumentException
  4655. * if the row does not exist in this section
  4656. * @see #removeHeaderRow(int)
  4657. * @see #addHeaderRowAt(int)
  4658. * @see #appendHeaderRow()
  4659. * @see #prependHeaderRow()
  4660. */
  4661. public void removeHeaderRow(HeaderRow row) {
  4662. header.removeRow(row);
  4663. }
  4664. /**
  4665. * Removes the row at the given position from the header section.
  4666. *
  4667. * @param index
  4668. * the position of the row
  4669. *
  4670. * @throws IllegalArgumentException
  4671. * if no row exists at given index
  4672. * @see #removeHeaderRow(HeaderRow)
  4673. * @see #addHeaderRowAt(int)
  4674. * @see #appendHeaderRow()
  4675. * @see #prependHeaderRow()
  4676. */
  4677. public void removeHeaderRow(int rowIndex) {
  4678. header.removeRow(rowIndex);
  4679. }
  4680. /**
  4681. * Sets the default row of the header. The default row is a special header
  4682. * row providing a user interface for sorting columns.
  4683. *
  4684. * @param row
  4685. * the new default row, or null for no default row
  4686. *
  4687. * @throws IllegalArgumentException
  4688. * header does not contain the row
  4689. */
  4690. public void setDefaultHeaderRow(HeaderRow row) {
  4691. header.setDefaultRow(row);
  4692. }
  4693. /**
  4694. * Sets the visibility of the header section.
  4695. *
  4696. * @param visible
  4697. * true to show header section, false to hide
  4698. */
  4699. public void setHeaderVisible(boolean visible) {
  4700. header.setVisible(visible);
  4701. }
  4702. /**
  4703. * Returns the visibility of the header section.
  4704. *
  4705. * @return true if visible, false otherwise.
  4706. */
  4707. public boolean isHeaderVisible() {
  4708. return header.isVisible();
  4709. }
  4710. /* Grid Footers */
  4711. /**
  4712. * Returns the footer section of this grid. The default header contains a
  4713. * single row displaying the column captions.
  4714. *
  4715. * @return the footer
  4716. */
  4717. protected Footer getFooter() {
  4718. return footer;
  4719. }
  4720. /**
  4721. * Gets the footer row at given index.
  4722. *
  4723. * @param rowIndex
  4724. * 0 based index for row. Counted from top to bottom
  4725. * @return footer row at given index
  4726. * @throws IllegalArgumentException
  4727. * if no row exists at given index
  4728. */
  4729. public FooterRow getFooterRow(int rowIndex) {
  4730. return footer.getRow(rowIndex);
  4731. }
  4732. /**
  4733. * Inserts a new row at the given position to the footer section. Shifts the
  4734. * row currently at that position and any subsequent rows down (adds one to
  4735. * their indices).
  4736. *
  4737. * @param index
  4738. * the position at which to insert the row
  4739. * @return the new row
  4740. *
  4741. * @throws IllegalArgumentException
  4742. * if the index is less than 0 or greater than row count
  4743. * @see #appendFooterRow()
  4744. * @see #prependFooterRow()
  4745. * @see #removeFooterRow(FooterRow)
  4746. * @see #removeFooterRow(int)
  4747. */
  4748. public FooterRow addFooterRowAt(int index) {
  4749. return footer.addRowAt(index);
  4750. }
  4751. /**
  4752. * Adds a new row at the bottom of the footer section.
  4753. *
  4754. * @return the new row
  4755. * @see #prependFooterRow()
  4756. * @see #addFooterRowAt(int)
  4757. * @see #removeFooterRow(FooterRow)
  4758. * @see #removeFooterRow(int)
  4759. */
  4760. public FooterRow appendFooterRow() {
  4761. return footer.appendRow();
  4762. }
  4763. /**
  4764. * Gets the row count for the footer.
  4765. *
  4766. * @return row count
  4767. */
  4768. public int getFooterRowCount() {
  4769. return footer.getRowCount();
  4770. }
  4771. /**
  4772. * Adds a new row at the top of the footer section.
  4773. *
  4774. * @return the new row
  4775. * @see #appendFooterRow()
  4776. * @see #addFooterRowAt(int)
  4777. * @see #removeFooterRow(FooterRow)
  4778. * @see #removeFooterRow(int)
  4779. */
  4780. public FooterRow prependFooterRow() {
  4781. return footer.prependRow();
  4782. }
  4783. /**
  4784. * Removes the given row from the footer section.
  4785. *
  4786. * @param row
  4787. * the row to be removed
  4788. *
  4789. * @throws IllegalArgumentException
  4790. * if the row does not exist in this section
  4791. * @see #removeFooterRow(int)
  4792. * @see #addFooterRowAt(int)
  4793. * @see #appendFooterRow()
  4794. * @see #prependFooterRow()
  4795. */
  4796. public void removeFooterRow(FooterRow row) {
  4797. footer.removeRow(row);
  4798. }
  4799. /**
  4800. * Removes the row at the given position from the footer section.
  4801. *
  4802. * @param index
  4803. * the position of the row
  4804. *
  4805. * @throws IllegalArgumentException
  4806. * if no row exists at given index
  4807. * @see #removeFooterRow(FooterRow)
  4808. * @see #addFooterRowAt(int)
  4809. * @see #appendFooterRow()
  4810. * @see #prependFooterRow()
  4811. */
  4812. public void removeFooterRow(int rowIndex) {
  4813. footer.removeRow(rowIndex);
  4814. }
  4815. /**
  4816. * Sets the visibility of the footer section.
  4817. *
  4818. * @param visible
  4819. * true to show footer section, false to hide
  4820. */
  4821. public void setFooterVisible(boolean visible) {
  4822. footer.setVisible(visible);
  4823. }
  4824. /**
  4825. * Returns the visibility of the footer section.
  4826. *
  4827. * @return true if visible, false otherwise.
  4828. */
  4829. public boolean isFooterVisible() {
  4830. return footer.isVisible();
  4831. }
  4832. @Override
  4833. public Iterator<Component> iterator() {
  4834. List<Component> componentList = new ArrayList<Component>();
  4835. Header header = getHeader();
  4836. for (int i = 0; i < header.getRowCount(); ++i) {
  4837. HeaderRow row = header.getRow(i);
  4838. for (Object propId : columns.keySet()) {
  4839. HeaderCell cell = row.getCell(propId);
  4840. if (cell.getCellState().type == GridStaticCellType.WIDGET) {
  4841. componentList.add(cell.getComponent());
  4842. }
  4843. }
  4844. }
  4845. Footer footer = getFooter();
  4846. for (int i = 0; i < footer.getRowCount(); ++i) {
  4847. FooterRow row = footer.getRow(i);
  4848. for (Object propId : columns.keySet()) {
  4849. FooterCell cell = row.getCell(propId);
  4850. if (cell.getCellState().type == GridStaticCellType.WIDGET) {
  4851. componentList.add(cell.getComponent());
  4852. }
  4853. }
  4854. }
  4855. componentList.addAll(getEditorFields());
  4856. componentList.addAll(detailComponentManager.getComponents());
  4857. return componentList.iterator();
  4858. }
  4859. @Override
  4860. public boolean isRendered(Component childComponent) {
  4861. if (getEditorFields().contains(childComponent)) {
  4862. // Only render editor fields if the editor is open
  4863. return isEditorActive();
  4864. } else {
  4865. // TODO Header and footer components should also only be rendered if
  4866. // the header/footer is visible
  4867. return true;
  4868. }
  4869. }
  4870. EditorClientRpc getEditorRpc() {
  4871. return getRpcProxy(EditorClientRpc.class);
  4872. }
  4873. /**
  4874. * Sets the style generator that is used for generating styles for cells
  4875. *
  4876. * @param cellStyleGenerator
  4877. * the cell style generator to set, or <code>null</code> to
  4878. * remove a previously set generator
  4879. */
  4880. public void setCellStyleGenerator(CellStyleGenerator cellStyleGenerator) {
  4881. this.cellStyleGenerator = cellStyleGenerator;
  4882. getState().hasCellStyleGenerator = (cellStyleGenerator != null);
  4883. datasourceExtension.refreshCache();
  4884. }
  4885. /**
  4886. * Gets the style generator that is used for generating styles for cells
  4887. *
  4888. * @return the cell style generator, or <code>null</code> if no generator is
  4889. * set
  4890. */
  4891. public CellStyleGenerator getCellStyleGenerator() {
  4892. return cellStyleGenerator;
  4893. }
  4894. /**
  4895. * Sets the style generator that is used for generating styles for rows
  4896. *
  4897. * @param rowStyleGenerator
  4898. * the row style generator to set, or <code>null</code> to remove
  4899. * a previously set generator
  4900. */
  4901. public void setRowStyleGenerator(RowStyleGenerator rowStyleGenerator) {
  4902. this.rowStyleGenerator = rowStyleGenerator;
  4903. getState().hasRowStyleGenerator = (rowStyleGenerator != null);
  4904. datasourceExtension.refreshCache();
  4905. }
  4906. /**
  4907. * Gets the style generator that is used for generating styles for rows
  4908. *
  4909. * @return the row style generator, or <code>null</code> if no generator is
  4910. * set
  4911. */
  4912. public RowStyleGenerator getRowStyleGenerator() {
  4913. return rowStyleGenerator;
  4914. }
  4915. /**
  4916. * Adds a row to the underlying container. The order of the parameters
  4917. * should match the current visible column order.
  4918. * <p>
  4919. * Please note that it's generally only safe to use this method during
  4920. * initialization. After Grid has been initialized and the visible column
  4921. * order might have been changed, it's better to instead add items directly
  4922. * to the underlying container and use {@link Item#getItemProperty(Object)}
  4923. * to make sure each value is assigned to the intended property.
  4924. *
  4925. * @param values
  4926. * the cell values of the new row, in the same order as the
  4927. * visible column order, not <code>null</code>.
  4928. * @return the item id of the new row
  4929. * @throws IllegalArgumentException
  4930. * if values is null
  4931. * @throws IllegalArgumentException
  4932. * if its length does not match the number of visible columns
  4933. * @throws IllegalArgumentException
  4934. * if a parameter value is not an instance of the corresponding
  4935. * property type
  4936. * @throws UnsupportedOperationException
  4937. * if the container does not support adding new items
  4938. */
  4939. public Object addRow(Object... values) {
  4940. if (values == null) {
  4941. throw new IllegalArgumentException("Values cannot be null");
  4942. }
  4943. Indexed dataSource = getContainerDataSource();
  4944. List<String> columnOrder = getState(false).columnOrder;
  4945. if (values.length != columnOrder.size()) {
  4946. throw new IllegalArgumentException("There are "
  4947. + columnOrder.size() + " visible columns, but "
  4948. + values.length + " cell values were provided.");
  4949. }
  4950. // First verify all parameter types
  4951. for (int i = 0; i < columnOrder.size(); i++) {
  4952. Object propertyId = getPropertyIdByColumnId(columnOrder.get(i));
  4953. Class<?> propertyType = dataSource.getType(propertyId);
  4954. if (values[i] != null && !propertyType.isInstance(values[i])) {
  4955. throw new IllegalArgumentException("Parameter " + i + "("
  4956. + values[i] + ") is not an instance of "
  4957. + propertyType.getCanonicalName());
  4958. }
  4959. }
  4960. Object itemId = dataSource.addItem();
  4961. try {
  4962. Item item = dataSource.getItem(itemId);
  4963. for (int i = 0; i < columnOrder.size(); i++) {
  4964. Object propertyId = getPropertyIdByColumnId(columnOrder.get(i));
  4965. Property<Object> property = item.getItemProperty(propertyId);
  4966. property.setValue(values[i]);
  4967. }
  4968. } catch (RuntimeException e) {
  4969. try {
  4970. dataSource.removeItem(itemId);
  4971. } catch (Exception e2) {
  4972. getLogger().log(Level.SEVERE,
  4973. "Error recovering from exception in addRow", e);
  4974. }
  4975. throw e;
  4976. }
  4977. return itemId;
  4978. }
  4979. private static Logger getLogger() {
  4980. return Logger.getLogger(Grid.class.getName());
  4981. }
  4982. /**
  4983. * Sets whether or not the item editor UI is enabled for this grid. When the
  4984. * editor is enabled, the user can open it by double-clicking a row or
  4985. * hitting enter when a row is focused. The editor can also be opened
  4986. * programmatically using the {@link #editItem(Object)} method.
  4987. *
  4988. * @param isEnabled
  4989. * <code>true</code> to enable the feature, <code>false</code>
  4990. * otherwise
  4991. * @throws IllegalStateException
  4992. * if an item is currently being edited
  4993. *
  4994. * @see #getEditedItemId()
  4995. */
  4996. public void setEditorEnabled(boolean isEnabled)
  4997. throws IllegalStateException {
  4998. if (isEditorActive()) {
  4999. throw new IllegalStateException(
  5000. "Cannot disable the editor while an item ("
  5001. + getEditedItemId() + ") is being edited");
  5002. }
  5003. if (isEditorEnabled() != isEnabled) {
  5004. getState().editorEnabled = isEnabled;
  5005. }
  5006. }
  5007. /**
  5008. * Checks whether the item editor UI is enabled for this grid.
  5009. *
  5010. * @return <code>true</code> iff the editor is enabled for this grid
  5011. *
  5012. * @see #setEditorEnabled(boolean)
  5013. * @see #getEditedItemId()
  5014. */
  5015. public boolean isEditorEnabled() {
  5016. return getState(false).editorEnabled;
  5017. }
  5018. /**
  5019. * Gets the id of the item that is currently being edited.
  5020. *
  5021. * @return the id of the item that is currently being edited, or
  5022. * <code>null</code> if no item is being edited at the moment
  5023. */
  5024. public Object getEditedItemId() {
  5025. return editedItemId;
  5026. }
  5027. /**
  5028. * Gets the field group that is backing the item editor of this grid.
  5029. *
  5030. * @return the backing field group
  5031. */
  5032. public FieldGroup getEditorFieldGroup() {
  5033. return editorFieldGroup;
  5034. }
  5035. /**
  5036. * Sets the field group that is backing the item editor of this grid.
  5037. *
  5038. * @param fieldGroup
  5039. * the backing field group
  5040. *
  5041. * @throws IllegalStateException
  5042. * if the editor is currently active
  5043. */
  5044. public void setEditorFieldGroup(FieldGroup fieldGroup) {
  5045. if (isEditorActive()) {
  5046. throw new IllegalStateException(
  5047. "Cannot change field group while an item ("
  5048. + getEditedItemId() + ") is being edited");
  5049. }
  5050. editorFieldGroup = fieldGroup;
  5051. }
  5052. /**
  5053. * Returns whether an item is currently being edited in the editor.
  5054. *
  5055. * @return true iff the editor is open
  5056. */
  5057. public boolean isEditorActive() {
  5058. return editedItemId != null;
  5059. }
  5060. private void checkColumnExists(Object propertyId) {
  5061. if (getColumn(propertyId) == null) {
  5062. throw new IllegalArgumentException(
  5063. "There is no column with the property id " + propertyId);
  5064. }
  5065. }
  5066. private Field<?> getEditorField(Object propertyId) {
  5067. checkColumnExists(propertyId);
  5068. if (!getColumn(propertyId).isEditable()) {
  5069. return null;
  5070. }
  5071. Field<?> editor = editorFieldGroup.getField(propertyId);
  5072. if (editor == null) {
  5073. editor = editorFieldGroup.buildAndBind(propertyId);
  5074. }
  5075. if (editor.getParent() != Grid.this) {
  5076. assert editor.getParent() == null;
  5077. editor.setParent(this);
  5078. }
  5079. return editor;
  5080. }
  5081. /**
  5082. * Opens the editor interface for the provided item. Scrolls the Grid to
  5083. * bring the item to view if it is not already visible.
  5084. *
  5085. * @param itemId
  5086. * the id of the item to edit
  5087. * @throws IllegalStateException
  5088. * if the editor is not enabled or already editing an item
  5089. * @throws IllegalArgumentException
  5090. * if the {@code itemId} is not in the backing container
  5091. * @see #setEditorEnabled(boolean)
  5092. */
  5093. public void editItem(Object itemId) throws IllegalStateException,
  5094. IllegalArgumentException {
  5095. if (!isEditorEnabled()) {
  5096. throw new IllegalStateException("Item editor is not enabled");
  5097. } else if (editedItemId != null) {
  5098. throw new IllegalStateException("Editing item + " + itemId
  5099. + " failed. Item editor is already editing item "
  5100. + editedItemId);
  5101. } else if (!getContainerDataSource().containsId(itemId)) {
  5102. throw new IllegalArgumentException("Item with id " + itemId
  5103. + " not found in current container");
  5104. }
  5105. editedItemId = itemId;
  5106. getEditorRpc().bind(getContainerDataSource().indexOfId(itemId));
  5107. }
  5108. protected void doEditItem() {
  5109. Item item = getContainerDataSource().getItem(editedItemId);
  5110. editorFieldGroup.setItemDataSource(item);
  5111. for (Column column : getColumns()) {
  5112. column.getState().editorConnector = getEditorField(column
  5113. .getPropertyId());
  5114. }
  5115. }
  5116. private void setEditorField(Object propertyId, Field<?> field) {
  5117. checkColumnExists(propertyId);
  5118. Field<?> oldField = editorFieldGroup.getField(propertyId);
  5119. if (oldField != null) {
  5120. editorFieldGroup.unbind(oldField);
  5121. oldField.setParent(null);
  5122. }
  5123. if (field != null) {
  5124. field.setParent(this);
  5125. editorFieldGroup.bind(field, propertyId);
  5126. }
  5127. }
  5128. /**
  5129. * Saves all changes done to the bound fields.
  5130. * <p>
  5131. * <em>Note:</em> This is a pass-through call to the backing field group.
  5132. *
  5133. * @throws CommitException
  5134. * If the commit was aborted
  5135. *
  5136. * @see FieldGroup#commit()
  5137. */
  5138. public void saveEditor() throws CommitException {
  5139. editorFieldGroup.commit();
  5140. }
  5141. /**
  5142. * Cancels the currently active edit if any. Hides the editor and discards
  5143. * possible unsaved changes in the editor fields.
  5144. */
  5145. public void cancelEditor() {
  5146. if (isEditorActive()) {
  5147. getEditorRpc().cancel(
  5148. getContainerDataSource().indexOfId(editedItemId));
  5149. doCancelEditor();
  5150. }
  5151. }
  5152. protected void doCancelEditor() {
  5153. editedItemId = null;
  5154. editorFieldGroup.discard();
  5155. }
  5156. void resetEditor() {
  5157. if (isEditorActive()) {
  5158. /*
  5159. * Simply force cancel the editing; throwing here would just make
  5160. * Grid.setContainerDataSource semantics more complicated.
  5161. */
  5162. cancelEditor();
  5163. }
  5164. for (Field<?> editor : getEditorFields()) {
  5165. editor.setParent(null);
  5166. }
  5167. editedItemId = null;
  5168. editorFieldGroup = new CustomFieldGroup();
  5169. }
  5170. /**
  5171. * Gets a collection of all fields bound to the item editor of this grid.
  5172. * <p>
  5173. * When {@link #editItem(Object) editItem} is called, fields are
  5174. * automatically created and bound to any unbound properties.
  5175. *
  5176. * @return a collection of all the fields bound to the item editor
  5177. */
  5178. Collection<Field<?>> getEditorFields() {
  5179. Collection<Field<?>> fields = editorFieldGroup.getFields();
  5180. assert allAttached(fields);
  5181. return fields;
  5182. }
  5183. private boolean allAttached(Collection<? extends Component> components) {
  5184. for (Component component : components) {
  5185. if (component.getParent() != this) {
  5186. return false;
  5187. }
  5188. }
  5189. return true;
  5190. }
  5191. /**
  5192. * Sets the field factory for the {@link FieldGroup}. The field factory is
  5193. * only used when {@link FieldGroup} creates a new field.
  5194. * <p>
  5195. * <em>Note:</em> This is a pass-through call to the backing field group.
  5196. *
  5197. * @param fieldFactory
  5198. * The field factory to use
  5199. */
  5200. public void setEditorFieldFactory(FieldGroupFieldFactory fieldFactory) {
  5201. editorFieldGroup.setFieldFactory(fieldFactory);
  5202. }
  5203. /**
  5204. * Sets the error handler for the editor.
  5205. *
  5206. * The error handler is called whenever there is an exception in the editor.
  5207. *
  5208. * @param editorErrorHandler
  5209. * The editor error handler to use
  5210. * @throws IllegalArgumentException
  5211. * if the error handler is null
  5212. */
  5213. public void setEditorErrorHandler(EditorErrorHandler editorErrorHandler)
  5214. throws IllegalArgumentException {
  5215. if (editorErrorHandler == null) {
  5216. throw new IllegalArgumentException(
  5217. "The error handler cannot be null");
  5218. }
  5219. this.editorErrorHandler = editorErrorHandler;
  5220. }
  5221. /**
  5222. * Gets the error handler used for the editor
  5223. *
  5224. * @see #setErrorHandler(com.vaadin.server.ErrorHandler)
  5225. * @return the editor error handler, never null
  5226. */
  5227. public EditorErrorHandler getEditorErrorHandler() {
  5228. return editorErrorHandler;
  5229. }
  5230. /**
  5231. * Gets the field factory for the {@link FieldGroup}. The field factory is
  5232. * only used when {@link FieldGroup} creates a new field.
  5233. * <p>
  5234. * <em>Note:</em> This is a pass-through call to the backing field group.
  5235. *
  5236. * @return The field factory in use
  5237. */
  5238. public FieldGroupFieldFactory getEditorFieldFactory() {
  5239. return editorFieldGroup.getFieldFactory();
  5240. }
  5241. /**
  5242. * Sets the caption on the save button in the Grid editor.
  5243. *
  5244. * @param saveCaption
  5245. * the caption to set
  5246. * @throws IllegalArgumentException
  5247. * if {@code saveCaption} is {@code null}
  5248. */
  5249. public void setEditorSaveCaption(String saveCaption)
  5250. throws IllegalArgumentException {
  5251. if (saveCaption == null) {
  5252. throw new IllegalArgumentException("Save caption cannot be null");
  5253. }
  5254. getState().editorSaveCaption = saveCaption;
  5255. }
  5256. /**
  5257. * Gets the current caption of the save button in the Grid editor.
  5258. *
  5259. * @return the current caption of the save button
  5260. */
  5261. public String getEditorSaveCaption() {
  5262. return getState(false).editorSaveCaption;
  5263. }
  5264. /**
  5265. * Sets the caption on the cancel button in the Grid editor.
  5266. *
  5267. * @param cancelCaption
  5268. * the caption to set
  5269. * @throws IllegalArgumentException
  5270. * if {@code cancelCaption} is {@code null}
  5271. */
  5272. public void setEditorCancelCaption(String cancelCaption)
  5273. throws IllegalArgumentException {
  5274. if (cancelCaption == null) {
  5275. throw new IllegalArgumentException("Cancel caption cannot be null");
  5276. }
  5277. getState().editorCancelCaption = cancelCaption;
  5278. }
  5279. /**
  5280. * Gets the current caption of the cancel button in the Grid editor.
  5281. *
  5282. * @return the current caption of the cancel button
  5283. */
  5284. public String getEditorCancelCaption() {
  5285. return getState(false).editorCancelCaption;
  5286. }
  5287. @Override
  5288. public void addItemClickListener(ItemClickListener listener) {
  5289. addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  5290. listener, ItemClickEvent.ITEM_CLICK_METHOD);
  5291. }
  5292. @Override
  5293. @Deprecated
  5294. public void addListener(ItemClickListener listener) {
  5295. addItemClickListener(listener);
  5296. }
  5297. @Override
  5298. public void removeItemClickListener(ItemClickListener listener) {
  5299. removeListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  5300. listener);
  5301. }
  5302. @Override
  5303. @Deprecated
  5304. public void removeListener(ItemClickListener listener) {
  5305. removeItemClickListener(listener);
  5306. }
  5307. /**
  5308. * Requests that the column widths should be recalculated.
  5309. * <p>
  5310. * In most cases Grid will know when column widths need to be recalculated
  5311. * but this method can be used to force recalculation in situations when
  5312. * grid does not recalculate automatically.
  5313. *
  5314. * @since 7.4.1
  5315. */
  5316. public void recalculateColumnWidths() {
  5317. getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
  5318. }
  5319. /**
  5320. * Registers a new column visibility change listener
  5321. *
  5322. * @since 7.5.0
  5323. * @param listener
  5324. * the listener to register
  5325. */
  5326. public void addColumnVisibilityChangeListener(
  5327. ColumnVisibilityChangeListener listener) {
  5328. addListener(ColumnVisibilityChangeEvent.class, listener,
  5329. COLUMN_VISIBILITY_METHOD);
  5330. }
  5331. /**
  5332. * Removes a previously registered column visibility change listener
  5333. *
  5334. * @since 7.5.0
  5335. * @param listener
  5336. * the listener to remove
  5337. */
  5338. public void removeColumnVisibilityChangeListener(
  5339. ColumnVisibilityChangeListener listener) {
  5340. removeListener(ColumnVisibilityChangeEvent.class, listener,
  5341. COLUMN_VISIBILITY_METHOD);
  5342. }
  5343. private void fireColumnVisibilityChangeEvent(Column column, boolean hidden,
  5344. boolean isUserOriginated) {
  5345. fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
  5346. isUserOriginated));
  5347. }
  5348. /**
  5349. * Sets a new details generator for row details.
  5350. * <p>
  5351. * The currently opened row details will be re-rendered.
  5352. *
  5353. * @since 7.5.0
  5354. * @param detailsGenerator
  5355. * the details generator to set
  5356. * @throws IllegalArgumentException
  5357. * if detailsGenerator is <code>null</code>;
  5358. */
  5359. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  5360. throws IllegalArgumentException {
  5361. if (detailsGenerator == null) {
  5362. throw new IllegalArgumentException(
  5363. "Details generator may not be null");
  5364. } else if (detailsGenerator == this.detailsGenerator) {
  5365. return;
  5366. }
  5367. this.detailsGenerator = detailsGenerator;
  5368. datasourceExtension.refreshDetails();
  5369. getRpcProxy(GridClientRpc.class).setDetailsConnectorChanges(
  5370. detailComponentManager.getAndResetConnectorChanges(), -1);
  5371. }
  5372. /**
  5373. * Gets the current details generator for row details.
  5374. *
  5375. * @since 7.5.0
  5376. * @return the detailsGenerator the current details generator
  5377. */
  5378. public DetailsGenerator getDetailsGenerator() {
  5379. return detailsGenerator;
  5380. }
  5381. /**
  5382. * Shows or hides the details for a specific item.
  5383. *
  5384. * @since 7.5.0
  5385. * @param itemId
  5386. * the id of the item for which to set details visibility
  5387. * @param visible
  5388. * <code>true</code> to show the details, or <code>false</code>
  5389. * to hide them
  5390. */
  5391. public void setDetailsVisible(Object itemId, boolean visible) {
  5392. datasourceExtension.setDetailsVisible(itemId, visible);
  5393. }
  5394. /**
  5395. * Checks whether details are visible for the given item.
  5396. *
  5397. * @since 7.5.0
  5398. * @param itemId
  5399. * the id of the item for which to check details visibility
  5400. * @return <code>true</code> iff the details are visible
  5401. */
  5402. public boolean isDetailsVisible(Object itemId) {
  5403. return datasourceExtension.isDetailsVisible(itemId);
  5404. }
  5405. private static SelectionMode getDefaultSelectionMode() {
  5406. return SelectionMode.SINGLE;
  5407. }
  5408. @Override
  5409. public void readDesign(Element design, DesignContext context) {
  5410. super.readDesign(design, context);
  5411. Attributes attrs = design.attributes();
  5412. if (attrs.hasKey("editable")) {
  5413. setEditorEnabled(DesignAttributeHandler.readAttribute("editable",
  5414. attrs, boolean.class));
  5415. }
  5416. if (attrs.hasKey("rows")) {
  5417. setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
  5418. double.class));
  5419. setHeightMode(HeightMode.ROW);
  5420. }
  5421. if (attrs.hasKey("selection-mode")) {
  5422. setSelectionMode(DesignAttributeHandler.readAttribute(
  5423. "selection-mode", attrs, SelectionMode.class));
  5424. }
  5425. if (design.children().size() > 0) {
  5426. if (design.children().size() > 1
  5427. || !design.child(0).tagName().equals("table")) {
  5428. throw new DesignException(
  5429. "Grid needs to have a table element as its only child");
  5430. }
  5431. Element table = design.child(0);
  5432. Elements colgroups = table.getElementsByTag("colgroup");
  5433. if (colgroups.size() != 1) {
  5434. throw new DesignException(
  5435. "Table element in declarative Grid needs to have a"
  5436. + " colgroup defining the columns used in Grid");
  5437. }
  5438. int i = 0;
  5439. for (Element col : colgroups.get(0).getElementsByTag("col")) {
  5440. String propertyId = DesignAttributeHandler.readAttribute(
  5441. "property-id", col.attributes(), "property-" + i,
  5442. String.class);
  5443. addColumn(propertyId, String.class).readDesign(col, context);
  5444. ++i;
  5445. }
  5446. for (Element child : table.children()) {
  5447. if (child.tagName().equals("thead")) {
  5448. header.readDesign(child, context);
  5449. } else if (child.tagName().equals("tbody")) {
  5450. for (Element row : child.children()) {
  5451. Elements cells = row.children();
  5452. Object[] data = new String[cells.size()];
  5453. for (int c = 0; c < cells.size(); ++c) {
  5454. data[c] = cells.get(c).html();
  5455. }
  5456. addRow(data);
  5457. }
  5458. // Since inline data is used, set HTML renderer for columns
  5459. for (Column c : getColumns()) {
  5460. c.setRenderer(new HtmlRenderer());
  5461. }
  5462. } else if (child.tagName().equals("tfoot")) {
  5463. footer.readDesign(child, context);
  5464. }
  5465. }
  5466. }
  5467. // Read frozen columns after columns are read.
  5468. if (attrs.hasKey("frozen-columns")) {
  5469. setFrozenColumnCount(DesignAttributeHandler.readAttribute(
  5470. "frozen-columns", attrs, int.class));
  5471. }
  5472. }
  5473. @Override
  5474. public void writeDesign(Element design, DesignContext context) {
  5475. super.writeDesign(design, context);
  5476. Attributes attrs = design.attributes();
  5477. Grid def = context.getDefaultInstance(this);
  5478. DesignAttributeHandler.writeAttribute("editable", attrs,
  5479. isEditorEnabled(), def.isEditorEnabled(), boolean.class);
  5480. DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
  5481. getFrozenColumnCount(), def.getFrozenColumnCount(), int.class);
  5482. if (getHeightMode() == HeightMode.ROW) {
  5483. DesignAttributeHandler.writeAttribute("rows", attrs,
  5484. getHeightByRows(), def.getHeightByRows(), double.class);
  5485. }
  5486. SelectionMode selectionMode = null;
  5487. if (selectionModel.getClass().equals(SingleSelectionModel.class)) {
  5488. selectionMode = SelectionMode.SINGLE;
  5489. } else if (selectionModel.getClass().equals(MultiSelectionModel.class)) {
  5490. selectionMode = SelectionMode.MULTI;
  5491. } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
  5492. selectionMode = SelectionMode.NONE;
  5493. }
  5494. assert selectionMode != null : "Unexpected selection model "
  5495. + selectionModel.getClass().getName();
  5496. DesignAttributeHandler.writeAttribute("selection-mode", attrs,
  5497. selectionMode, getDefaultSelectionMode(), SelectionMode.class);
  5498. if (columns.isEmpty()) {
  5499. // Empty grid. Structure not needed.
  5500. return;
  5501. }
  5502. // Do structure.
  5503. Element tableElement = design.appendElement("table");
  5504. Element colGroup = tableElement.appendElement("colgroup");
  5505. List<Column> columnOrder = getColumns();
  5506. for (int i = 0; i < columnOrder.size(); ++i) {
  5507. Column column = columnOrder.get(i);
  5508. Element colElement = colGroup.appendElement("col");
  5509. column.writeDesign(colElement, context);
  5510. }
  5511. // Always write thead. Reads correctly when there no header rows
  5512. header.writeDesign(tableElement.appendElement("thead"), context);
  5513. if (context.shouldWriteData(this)) {
  5514. Element bodyElement = tableElement.appendElement("tbody");
  5515. for (Object itemId : datasource.getItemIds()) {
  5516. Element tableRow = bodyElement.appendElement("tr");
  5517. for (Column c : getColumns()) {
  5518. Object value = datasource.getItem(itemId)
  5519. .getItemProperty(c.getPropertyId()).getValue();
  5520. tableRow.appendElement("td").append(
  5521. (value != null ? value.toString() : ""));
  5522. }
  5523. }
  5524. }
  5525. if (footer.getRowCount() > 0) {
  5526. footer.writeDesign(tableElement.appendElement("tfoot"), context);
  5527. }
  5528. }
  5529. @Override
  5530. protected Collection<String> getCustomAttributes() {
  5531. Collection<String> result = super.getCustomAttributes();
  5532. result.add("editor-enabled");
  5533. result.add("editable");
  5534. result.add("frozen-column-count");
  5535. result.add("frozen-columns");
  5536. result.add("height-by-rows");
  5537. result.add("rows");
  5538. result.add("selection-mode");
  5539. result.add("header-visible");
  5540. result.add("footer-visible");
  5541. result.add("editor-error-handler");
  5542. result.add("height-mode");
  5543. return result;
  5544. }
  5545. }