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

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