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

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