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

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