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

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