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

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