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.

Table.java 218KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528
  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.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.Iterator;
  25. import java.util.LinkedHashMap;
  26. import java.util.LinkedHashSet;
  27. import java.util.LinkedList;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Set;
  31. import java.util.StringTokenizer;
  32. import java.util.logging.Level;
  33. import java.util.logging.Logger;
  34. import org.jsoup.nodes.Element;
  35. import org.jsoup.select.Elements;
  36. import com.vaadin.event.Action;
  37. import com.vaadin.event.Action.Handler;
  38. import com.vaadin.event.ContextClickEvent;
  39. import com.vaadin.event.MouseEvents.ClickEvent;
  40. import com.vaadin.event.dd.DragAndDropEvent;
  41. import com.vaadin.event.dd.DragSource;
  42. import com.vaadin.event.dd.DropHandler;
  43. import com.vaadin.event.dd.DropTarget;
  44. import com.vaadin.event.dd.acceptcriteria.ServerSideCriterion;
  45. import com.vaadin.server.KeyMapper;
  46. import com.vaadin.server.LegacyCommunicationManager;
  47. import com.vaadin.server.LegacyPaint;
  48. import com.vaadin.server.PaintException;
  49. import com.vaadin.server.PaintTarget;
  50. import com.vaadin.server.Resource;
  51. import com.vaadin.shared.MouseEventDetails;
  52. import com.vaadin.shared.ui.MultiSelectMode;
  53. import com.vaadin.shared.util.SharedUtil;
  54. import com.vaadin.ui.Component;
  55. import com.vaadin.ui.Grid;
  56. import com.vaadin.ui.HasChildMeasurementHint;
  57. import com.vaadin.ui.UniqueSerializable;
  58. import com.vaadin.ui.declarative.DesignAttributeHandler;
  59. import com.vaadin.ui.declarative.DesignContext;
  60. import com.vaadin.ui.declarative.DesignException;
  61. import com.vaadin.ui.declarative.DesignFormatter;
  62. import com.vaadin.util.ReflectTools;
  63. import com.vaadin.v7.data.Container;
  64. import com.vaadin.v7.data.Item;
  65. import com.vaadin.v7.data.Property;
  66. import com.vaadin.v7.data.util.ContainerOrderedWrapper;
  67. import com.vaadin.v7.data.util.IndexedContainer;
  68. import com.vaadin.v7.data.util.converter.Converter;
  69. import com.vaadin.v7.data.util.converter.ConverterUtil;
  70. import com.vaadin.v7.event.DataBoundTransferable;
  71. import com.vaadin.v7.event.ItemClickEvent;
  72. import com.vaadin.v7.event.ItemClickEvent.ItemClickListener;
  73. import com.vaadin.v7.event.ItemClickEvent.ItemClickNotifier;
  74. import com.vaadin.v7.shared.ui.table.CollapseMenuContent;
  75. import com.vaadin.v7.shared.ui.table.TableConstants;
  76. import com.vaadin.v7.shared.ui.table.TableConstants.Section;
  77. import com.vaadin.v7.shared.ui.table.TableServerRpc;
  78. import com.vaadin.v7.shared.ui.table.TableState;
  79. /**
  80. * <p>
  81. * <code>Table</code> is used for representing data or components in a pageable
  82. * and selectable table.
  83. * </p>
  84. *
  85. * <p>
  86. * Scalability of the Table is largely dictated by the container. A table does
  87. * not have a limit for the number of items and is just as fast with hundreds of
  88. * thousands of items as with just a few. The current GWT implementation with
  89. * scrolling however limits the number of rows to around 500000, depending on
  90. * the browser and the pixel height of rows.
  91. * </p>
  92. *
  93. * <p>
  94. * Components in a Table will not have their caption nor icon rendered.
  95. * </p>
  96. *
  97. * @author Vaadin Ltd.
  98. * @since 3.0
  99. *
  100. * @deprecated As of 8.0, use {@link Grid} instead
  101. */
  102. @Deprecated
  103. @SuppressWarnings({ "deprecation" })
  104. public class Table extends AbstractSelect implements Action.Container,
  105. Container.Sortable, ItemClickNotifier, DragSource, DropTarget,
  106. HasChildMeasurementHint {
  107. private transient Logger logger = null;
  108. /**
  109. * Modes that Table support as drag sourse.
  110. */
  111. @Deprecated
  112. public enum TableDragMode {
  113. /**
  114. * Table does not start drag and drop events. HTM5 style events started
  115. * by browser may still happen.
  116. */
  117. NONE,
  118. /**
  119. * Table starts drag with a one row only.
  120. */
  121. ROW,
  122. /**
  123. * Table drags selected rows, if drag starts on a selected rows. Else it
  124. * starts like in ROW mode. Note, that in Transferable there will still
  125. * be only the row on which the drag started, other dragged rows need to
  126. * be checked from the source Table.
  127. */
  128. MULTIROW
  129. }
  130. protected static final int CELL_KEY = 0;
  131. protected static final int CELL_HEADER = 1;
  132. protected static final int CELL_ICON = 2;
  133. protected static final int CELL_ITEMID = 3;
  134. protected static final int CELL_GENERATED_ROW = 4;
  135. protected static final int CELL_FIRSTCOL = 5;
  136. @Deprecated
  137. public enum Align {
  138. /**
  139. * Left column alignment. <b>This is the default behavior. </b>
  140. */
  141. LEFT("b"),
  142. /**
  143. * Center column alignment.
  144. */
  145. CENTER("c"),
  146. /**
  147. * Right column alignment.
  148. */
  149. RIGHT("e");
  150. private String alignment;
  151. private Align(String alignment) {
  152. this.alignment = alignment;
  153. }
  154. @Override
  155. public String toString() {
  156. return alignment;
  157. }
  158. public Align convertStringToAlign(String string) {
  159. if (string == null) {
  160. return null;
  161. }
  162. if (string.equals("b")) {
  163. return Align.LEFT;
  164. } else if (string.equals("c")) {
  165. return Align.CENTER;
  166. } else if (string.equals("e")) {
  167. return Align.RIGHT;
  168. } else {
  169. return null;
  170. }
  171. }
  172. }
  173. /**
  174. * @deprecated As of 7.0, use {@link Align#LEFT} instead
  175. */
  176. @Deprecated
  177. public static final Align ALIGN_LEFT = Align.LEFT;
  178. /**
  179. * @deprecated As of 7.0, use {@link Align#CENTER} instead
  180. */
  181. @Deprecated
  182. public static final Align ALIGN_CENTER = Align.CENTER;
  183. /**
  184. * @deprecated As of 7.0, use {@link Align#RIGHT} instead
  185. */
  186. @Deprecated
  187. public static final Align ALIGN_RIGHT = Align.RIGHT;
  188. @Deprecated
  189. public enum ColumnHeaderMode {
  190. /**
  191. * Column headers are hidden.
  192. */
  193. HIDDEN,
  194. /**
  195. * Property ID:s are used as column headers.
  196. */
  197. ID,
  198. /**
  199. * Column headers are explicitly specified with
  200. * {@link #setColumnHeaders(String[])}.
  201. */
  202. EXPLICIT,
  203. /**
  204. * Column headers are explicitly specified with
  205. * {@link #setColumnHeaders(String[])}. If a header is not specified for
  206. * a given property, its property id is used instead.
  207. * <p>
  208. * <b>This is the default behavior. </b>
  209. */
  210. EXPLICIT_DEFAULTS_ID
  211. }
  212. /**
  213. * @deprecated As of 7.0, use {@link ColumnHeaderMode#HIDDEN} instead
  214. */
  215. @Deprecated
  216. public static final ColumnHeaderMode COLUMN_HEADER_MODE_HIDDEN = ColumnHeaderMode.HIDDEN;
  217. /**
  218. * @deprecated As of 7.0, use {@link ColumnHeaderMode#ID} instead
  219. */
  220. @Deprecated
  221. public static final ColumnHeaderMode COLUMN_HEADER_MODE_ID = ColumnHeaderMode.ID;
  222. /**
  223. * @deprecated As of 7.0, use {@link ColumnHeaderMode#EXPLICIT} instead
  224. */
  225. @Deprecated
  226. public static final ColumnHeaderMode COLUMN_HEADER_MODE_EXPLICIT = ColumnHeaderMode.EXPLICIT;
  227. /**
  228. * @deprecated As of 7.0, use {@link ColumnHeaderMode#EXPLICIT_DEFAULTS_ID}
  229. * instead
  230. */
  231. @Deprecated
  232. public static final ColumnHeaderMode COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID = ColumnHeaderMode.EXPLICIT_DEFAULTS_ID;
  233. @Deprecated
  234. public enum RowHeaderMode {
  235. /**
  236. * Row caption mode: The row headers are hidden. <b>This is the default
  237. * mode. </b>
  238. */
  239. HIDDEN(null),
  240. /**
  241. * Row caption mode: Items Id-objects toString is used as row caption.
  242. */
  243. ID(ItemCaptionMode.ID),
  244. /**
  245. * Row caption mode: Item-objects toString is used as row caption.
  246. */
  247. ITEM(ItemCaptionMode.ITEM),
  248. /**
  249. * Row caption mode: Index of the item is used as item caption. The
  250. * index mode can only be used with the containers implementing the
  251. * {@link Container.Indexed} interface.
  252. */
  253. INDEX(ItemCaptionMode.INDEX),
  254. /**
  255. * Row caption mode: Item captions are explicitly specified, but if the
  256. * caption is missing, the item id objects <code>toString()</code> is
  257. * used instead.
  258. */
  259. EXPLICIT_DEFAULTS_ID(ItemCaptionMode.EXPLICIT_DEFAULTS_ID),
  260. /**
  261. * Row caption mode: Item captions are explicitly specified.
  262. */
  263. EXPLICIT(ItemCaptionMode.EXPLICIT),
  264. /**
  265. * Row caption mode: Only icons are shown, the captions are hidden.
  266. */
  267. ICON_ONLY(ItemCaptionMode.ICON_ONLY),
  268. /**
  269. * Row caption mode: Item captions are read from property specified with
  270. * {@link #setItemCaptionPropertyId(Object)} .
  271. */
  272. PROPERTY(ItemCaptionMode.PROPERTY);
  273. ItemCaptionMode mode;
  274. private RowHeaderMode(ItemCaptionMode mode) {
  275. this.mode = mode;
  276. }
  277. public ItemCaptionMode getItemCaptionMode() {
  278. return mode;
  279. }
  280. }
  281. /**
  282. * @deprecated As of 7.0, use {@link RowHeaderMode#HIDDEN} instead
  283. */
  284. @Deprecated
  285. public static final RowHeaderMode ROW_HEADER_MODE_HIDDEN = RowHeaderMode.HIDDEN;
  286. /**
  287. * @deprecated As of 7.0, use {@link RowHeaderMode#ID} instead
  288. */
  289. @Deprecated
  290. public static final RowHeaderMode ROW_HEADER_MODE_ID = RowHeaderMode.ID;
  291. /**
  292. * @deprecated As of 7.0, use {@link RowHeaderMode#ITEM} instead
  293. */
  294. @Deprecated
  295. public static final RowHeaderMode ROW_HEADER_MODE_ITEM = RowHeaderMode.ITEM;
  296. /**
  297. * @deprecated As of 7.0, use {@link RowHeaderMode#INDEX} instead
  298. */
  299. @Deprecated
  300. public static final RowHeaderMode ROW_HEADER_MODE_INDEX = RowHeaderMode.INDEX;
  301. /**
  302. * @deprecated As of 7.0, use {@link RowHeaderMode#EXPLICIT_DEFAULTS_ID}
  303. * instead
  304. */
  305. @Deprecated
  306. public static final RowHeaderMode ROW_HEADER_MODE_EXPLICIT_DEFAULTS_ID = RowHeaderMode.EXPLICIT_DEFAULTS_ID;
  307. /**
  308. * @deprecated As of 7.0, use {@link RowHeaderMode#EXPLICIT} instead
  309. */
  310. @Deprecated
  311. public static final RowHeaderMode ROW_HEADER_MODE_EXPLICIT = RowHeaderMode.EXPLICIT;
  312. /**
  313. * @deprecated As of 7.0, use {@link RowHeaderMode#ICON_ONLY} instead
  314. */
  315. @Deprecated
  316. public static final RowHeaderMode ROW_HEADER_MODE_ICON_ONLY = RowHeaderMode.ICON_ONLY;
  317. /**
  318. * @deprecated As of 7.0, use {@link RowHeaderMode#PROPERTY} instead
  319. */
  320. @Deprecated
  321. public static final RowHeaderMode ROW_HEADER_MODE_PROPERTY = RowHeaderMode.PROPERTY;
  322. /**
  323. * The default rate that table caches rows for smooth scrolling.
  324. */
  325. private static final double CACHE_RATE_DEFAULT = 2;
  326. private static final String ROW_HEADER_COLUMN_KEY = "0";
  327. private static final Object ROW_HEADER_FAKE_PROPERTY_ID = new UniqueSerializable() {
  328. };
  329. /**
  330. * How layout manager should behave when measuring Table's child components
  331. */
  332. private ChildMeasurementHint childMeasurementHint = ChildMeasurementHint.MEASURE_ALWAYS;
  333. /* Private table extensions to Select */
  334. /**
  335. * True if column collapsing is allowed.
  336. */
  337. private boolean columnCollapsingAllowed = false;
  338. /**
  339. * True if reordering of columns is allowed on the client side.
  340. */
  341. private boolean columnReorderingAllowed = false;
  342. /**
  343. * Keymapper for column ids.
  344. */
  345. private final KeyMapper<Object> columnIdMap = new KeyMapper<Object>();
  346. /**
  347. * Holds visible column propertyIds - in order.
  348. */
  349. private LinkedList<Object> visibleColumns = new LinkedList<Object>();
  350. /**
  351. * Holds noncollapsible columns.
  352. */
  353. private HashSet<Object> noncollapsibleColumns = new HashSet<Object>();
  354. /**
  355. * Holds propertyIds of currently collapsed columns.
  356. */
  357. private final HashSet<Object> collapsedColumns = new HashSet<Object>();
  358. /**
  359. * Holds headers for visible columns (by propertyId).
  360. */
  361. private final Map<Object, String> columnHeaders = new HashMap<Object, String>();
  362. /**
  363. * Holds footers for visible columns (by propertyId).
  364. */
  365. private final Map<Object, String> columnFooters = new HashMap<Object, String>();
  366. /**
  367. * Holds icons for visible columns (by propertyId).
  368. */
  369. private final Map<Object, Resource> columnIcons = new HashMap<Object, Resource>();
  370. /**
  371. * Holds alignments for visible columns (by propertyId).
  372. */
  373. private Map<Object, Align> columnAlignments = new HashMap<Object, Align>();
  374. /**
  375. * Holds column widths in pixels for visible columns (by propertyId).
  376. */
  377. private final Map<Object, Integer> columnWidths = new HashMap<Object, Integer>();
  378. /**
  379. * Holds column expand rations for visible columns (by propertyId).
  380. */
  381. private final Map<Object, Float> columnExpandRatios = new HashMap<Object, Float>();
  382. /**
  383. * Holds column generators
  384. */
  385. private final Map<Object, ColumnGenerator> columnGenerators = new LinkedHashMap<Object, ColumnGenerator>();
  386. /**
  387. * Holds value of property pageLength. 0 disables paging.
  388. */
  389. private int pageLength = 15;
  390. /**
  391. * Id the first item on the current page.
  392. */
  393. private Object currentPageFirstItemId = null;
  394. /*
  395. * If all rows get removed then scroll position of the previous container
  396. * can be restored after re-adding/replacing rows via addAll(). This
  397. * resolves #14581.
  398. */
  399. private int repairOnReAddAllRowsDataScrollPositionItemIndex = -1;
  400. /**
  401. * Index of the first item on the current page.
  402. */
  403. private int currentPageFirstItemIndex = 0;
  404. /**
  405. * Index of the "first" item on the last page if a user has used
  406. * setCurrentPageFirstItemIndex to scroll down. -1 if not set.
  407. */
  408. private int currentPageFirstItemIndexOnLastPage = -1;
  409. /**
  410. * Holds value of property selectable.
  411. */
  412. private Boolean selectable;
  413. /**
  414. * Holds value of property columnHeaderMode.
  415. */
  416. private ColumnHeaderMode columnHeaderMode = ColumnHeaderMode.EXPLICIT_DEFAULTS_ID;
  417. /**
  418. * Holds value of property rowHeaderMode.
  419. */
  420. private RowHeaderMode rowHeaderMode = RowHeaderMode.EXPLICIT_DEFAULTS_ID;
  421. /**
  422. * Should the Table footer be visible?
  423. */
  424. private boolean columnFootersVisible = false;
  425. /**
  426. * Page contents buffer used in buffered mode.
  427. */
  428. private Object[][] pageBuffer = null;
  429. /**
  430. * Set of properties listened - the list is kept to release the listeners
  431. * later.
  432. */
  433. private HashSet<Property<?>> listenedProperties = null;
  434. /**
  435. * Set of visible components - the is used for needsRepaint calculation.
  436. */
  437. private HashSet<Component> visibleComponents = null;
  438. /**
  439. * List of action handlers.
  440. */
  441. private LinkedList<Handler> actionHandlers = null;
  442. /**
  443. * Action mapper.
  444. */
  445. private KeyMapper<Action> actionMapper = null;
  446. /**
  447. * Table cell editor factory.
  448. */
  449. private TableFieldFactory fieldFactory = DefaultFieldFactory.get();
  450. /**
  451. * Is table editable.
  452. */
  453. private boolean editable = false;
  454. /**
  455. * Current sorting direction.
  456. */
  457. private boolean sortAscending = true;
  458. /**
  459. * Currently table is sorted on this propertyId.
  460. */
  461. private Object sortContainerPropertyId = null;
  462. /**
  463. * Is table sorting by the user enabled.
  464. */
  465. private boolean sortEnabled = true;
  466. /**
  467. * Number of rows explicitly requested by the client to be painted on next
  468. * paint. This is -1 if no request by the client is made. Painting the
  469. * component will automatically reset this to -1.
  470. */
  471. private int reqRowsToPaint = -1;
  472. /**
  473. * Index of the first rows explicitly requested by the client to be painted.
  474. * This is -1 if no request by the client is made. Painting the component
  475. * will automatically reset this to -1.
  476. */
  477. private int reqFirstRowToPaint = -1;
  478. private int firstToBeRenderedInClient = -1;
  479. private int lastToBeRenderedInClient = -1;
  480. private boolean isContentRefreshesEnabled = true;
  481. private int pageBufferFirstIndex;
  482. private boolean containerChangeToBeRendered = false;
  483. /**
  484. * Table cell specific style generator
  485. */
  486. private CellStyleGenerator cellStyleGenerator = null;
  487. /**
  488. * Table cell specific tooltip generator
  489. */
  490. private ItemDescriptionGenerator itemDescriptionGenerator;
  491. /*
  492. * EXPERIMENTAL feature: will tell the client to re-calculate column widths
  493. * if set to true. Currently no setter: extend to enable.
  494. */
  495. protected boolean alwaysRecalculateColumnWidths = false;
  496. private double cacheRate = CACHE_RATE_DEFAULT;
  497. private TableDragMode dragMode = TableDragMode.NONE;
  498. private DropHandler dropHandler;
  499. private MultiSelectMode multiSelectMode = MultiSelectMode.DEFAULT;
  500. private boolean multiSelectTouchDetectionEnabled = true;
  501. private boolean rowCacheInvalidated;
  502. private RowGenerator rowGenerator = null;
  503. private final Map<Field<?>, Property<?>> associatedProperties = new HashMap<Field<?>, Property<?>>();
  504. private boolean painted = false;
  505. private Map<Object, Converter<String, Object>> propertyValueConverters = new HashMap<Object, Converter<String, Object>>();
  506. /**
  507. * Set to true if the client-side should be informed that the key mapper has
  508. * been reset so it can avoid sending back references to keys that are no
  509. * longer present.
  510. */
  511. private boolean keyMapperReset;
  512. private List<Throwable> exceptionsDuringCachePopulation = new ArrayList<Throwable>();
  513. private boolean isBeingPainted;
  514. /* Table constructors */
  515. /**
  516. * Creates a new empty table.
  517. */
  518. public Table() {
  519. setRowHeaderMode(ROW_HEADER_MODE_HIDDEN);
  520. registerRpc(new TableServerRpc() {
  521. @Override
  522. public void contextClick(String rowKey, String colKey,
  523. Section section, MouseEventDetails details) {
  524. Object itemId = itemIdMapper.get(rowKey);
  525. Object propertyId = columnIdMap.get(colKey);
  526. fireEvent(new TableContextClickEvent(Table.this, details,
  527. itemId, propertyId, section));
  528. }
  529. });
  530. }
  531. /**
  532. * Creates a new empty table with caption.
  533. *
  534. * @param caption
  535. */
  536. public Table(String caption) {
  537. this();
  538. setCaption(caption);
  539. }
  540. /**
  541. * Creates a new table with caption and connect it to a Container.
  542. *
  543. * @param caption
  544. * @param dataSource
  545. */
  546. public Table(String caption, Container dataSource) {
  547. this();
  548. setCaption(caption);
  549. setContainerDataSource(dataSource);
  550. }
  551. /* Table functionality */
  552. /**
  553. * Gets the array of visible column id:s, including generated columns.
  554. *
  555. * <p>
  556. * The columns are show in the order of their appearance in this array.
  557. * </p>
  558. *
  559. * @return an array of currently visible propertyIds and generated column
  560. * ids.
  561. */
  562. public Object[] getVisibleColumns() {
  563. if (visibleColumns == null) {
  564. return null;
  565. }
  566. return visibleColumns.toArray();
  567. }
  568. /**
  569. * Sets the array of visible column property id:s.
  570. *
  571. * <p>
  572. * The columns are show in the order of their appearance in this array.
  573. * </p>
  574. *
  575. * @param visibleColumns
  576. * the Array of shown property id:s.
  577. */
  578. public void setVisibleColumns(Object... visibleColumns) {
  579. // Visible columns must exist
  580. if (visibleColumns == null) {
  581. throw new NullPointerException(
  582. "Can not set visible columns to null value");
  583. }
  584. final LinkedList<Object> newVC = new LinkedList<Object>();
  585. // Checks that the new visible columns contains no nulls, properties
  586. // exist and that there are no duplicates before adding them to newVC.
  587. final Collection<?> properties = getContainerPropertyIds();
  588. for (Object id : visibleColumns) {
  589. if (id == null) {
  590. throw new NullPointerException("Ids must be non-nulls");
  591. } else if (!properties.contains(id)
  592. && !columnGenerators.containsKey(id)) {
  593. throw new IllegalArgumentException(
  594. "Ids must exist in the Container or as a generated column, missing id: "
  595. + id);
  596. } else if (newVC.contains(id)) {
  597. throw new IllegalArgumentException(
  598. "Ids must be unique, duplicate id: " + id);
  599. } else {
  600. newVC.add(id);
  601. }
  602. }
  603. this.visibleColumns = newVC;
  604. // Assures visual refresh
  605. refreshRowCache();
  606. }
  607. /**
  608. * Gets the headers of the columns.
  609. *
  610. * <p>
  611. * The headers match the property id:s given by the set visible column
  612. * headers. The table must be set in either
  613. * {@link #COLUMN_HEADER_MODE_EXPLICIT} or
  614. * {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the
  615. * headers. In the defaults mode any nulls in the headers array are replaced
  616. * with id.toString().
  617. * </p>
  618. *
  619. * @return the Array of column headers.
  620. */
  621. public String[] getColumnHeaders() {
  622. if (columnHeaders == null) {
  623. return null;
  624. }
  625. final String[] headers = new String[visibleColumns.size()];
  626. int i = 0;
  627. for (final Object column : visibleColumns) {
  628. headers[i++] = getColumnHeader(column);
  629. }
  630. return headers;
  631. }
  632. /**
  633. * Sets the headers of the columns.
  634. *
  635. * <p>
  636. * The headers match the property id:s given by the set visible column
  637. * headers. The table must be set in either
  638. * {@link #COLUMN_HEADER_MODE_EXPLICIT} or
  639. * {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the
  640. * headers. In the defaults mode any nulls in the headers array are replaced
  641. * with id.toString() outputs when rendering.
  642. * </p>
  643. *
  644. * @param columnHeaders
  645. * the Array of column headers that match the
  646. * {@link #getVisibleColumns()} method.
  647. */
  648. public void setColumnHeaders(String... columnHeaders) {
  649. if (columnHeaders.length != visibleColumns.size()) {
  650. throw new IllegalArgumentException(
  651. "The length of the headers array must match the number of visible columns");
  652. }
  653. this.columnHeaders.clear();
  654. int i = 0;
  655. for (final Object column : visibleColumns) {
  656. if (i >= columnHeaders.length) {
  657. break;
  658. }
  659. this.columnHeaders.put(column, columnHeaders[i++]);
  660. }
  661. markAsDirty();
  662. }
  663. /**
  664. * Gets the icons of the columns.
  665. *
  666. * <p>
  667. * The icons in headers match the property id:s given by the set visible
  668. * column headers. The table must be set in either
  669. * {@link #COLUMN_HEADER_MODE_EXPLICIT} or
  670. * {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the headers
  671. * with icons.
  672. * </p>
  673. *
  674. * @return the Array of icons that match the {@link #getVisibleColumns()}.
  675. */
  676. public Resource[] getColumnIcons() {
  677. if (columnIcons == null) {
  678. return null;
  679. }
  680. final Resource[] icons = new Resource[visibleColumns.size()];
  681. int i = 0;
  682. for (final Object column : visibleColumns) {
  683. icons[i++] = columnIcons.get(column);
  684. }
  685. return icons;
  686. }
  687. /**
  688. * Sets the icons of the columns.
  689. *
  690. * <p>
  691. * The icons in headers match the property id:s given by the set visible
  692. * column headers. The table must be set in either
  693. * {@link #COLUMN_HEADER_MODE_EXPLICIT} or
  694. * {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the headers
  695. * with icons.
  696. * </p>
  697. *
  698. * @param columnIcons
  699. * the Array of icons that match the {@link #getVisibleColumns()}
  700. * .
  701. */
  702. public void setColumnIcons(Resource... columnIcons) {
  703. if (columnIcons.length != visibleColumns.size()) {
  704. throw new IllegalArgumentException(
  705. "The length of the icons array must match the number of visible columns");
  706. }
  707. this.columnIcons.clear();
  708. int i = 0;
  709. for (final Object column : visibleColumns) {
  710. if (i >= columnIcons.length) {
  711. break;
  712. }
  713. this.columnIcons.put(column, columnIcons[i++]);
  714. }
  715. markAsDirty();
  716. }
  717. /**
  718. * Gets the array of column alignments.
  719. *
  720. * <p>
  721. * The items in the array must match the properties identified by
  722. * {@link #getVisibleColumns()}. The possible values for the alignments
  723. * include:
  724. * <ul>
  725. * <li>{@link Align#LEFT}: Left alignment</li>
  726. * <li>{@link Align#CENTER}: Centered</li>
  727. * <li>{@link Align#RIGHT}: Right alignment</li>
  728. * </ul>
  729. * The alignments default to {@link Align#LEFT}: any null values are
  730. * rendered as align lefts.
  731. * </p>
  732. *
  733. * @return the Column alignments array.
  734. */
  735. public Align[] getColumnAlignments() {
  736. if (columnAlignments == null) {
  737. return null;
  738. }
  739. final Align[] alignments = new Align[visibleColumns.size()];
  740. int i = 0;
  741. for (final Object column : visibleColumns) {
  742. alignments[i++] = getColumnAlignment(column);
  743. }
  744. return alignments;
  745. }
  746. /**
  747. * Sets the column alignments.
  748. *
  749. * <p>
  750. * The amount of items in the array must match the amount of properties
  751. * identified by {@link #getVisibleColumns()}. The possible values for the
  752. * alignments include:
  753. * <ul>
  754. * <li>{@link Align#LEFT}: Left alignment</li>
  755. * <li>{@link Align#CENTER}: Centered</li>
  756. * <li>{@link Align#RIGHT}: Right alignment</li>
  757. * </ul>
  758. * The alignments default to {@link Align#LEFT}
  759. * </p>
  760. *
  761. * @param columnAlignments
  762. * the Column alignments array.
  763. */
  764. public void setColumnAlignments(Align... columnAlignments) {
  765. if (columnAlignments.length != visibleColumns.size()) {
  766. throw new IllegalArgumentException(
  767. "The length of the alignments array must match the number of visible columns");
  768. }
  769. // Resets the alignments
  770. final Map<Object, Align> newCA = new HashMap<Object, Align>();
  771. int i = 0;
  772. for (final Object column : visibleColumns) {
  773. if (i >= columnAlignments.length) {
  774. break;
  775. }
  776. newCA.put(column, columnAlignments[i++]);
  777. }
  778. this.columnAlignments = newCA;
  779. // Assures the visual refresh. No need to reset the page buffer before
  780. // as the content has not changed, only the alignments.
  781. refreshRenderedCells();
  782. }
  783. /**
  784. * Sets columns width (in pixels). Theme may not necessarily respect very
  785. * small or very big values. Setting width to -1 (default) means that theme
  786. * will make decision of width.
  787. *
  788. * <p>
  789. * Column can either have a fixed width or expand ratio. The latter one set
  790. * is used. See @link {@link #setColumnExpandRatio(Object, float)}.
  791. *
  792. * @param propertyId
  793. * columns property id
  794. * @param width
  795. * width to be reserved for columns content
  796. * @since 4.0.3
  797. */
  798. public void setColumnWidth(Object propertyId, int width) {
  799. if (propertyId == null) {
  800. // Since propertyId is null, this is the row header. Use the magic
  801. // id to store the width of the row header.
  802. propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
  803. }
  804. // Setting column width should remove any expand ratios as well
  805. columnExpandRatios.remove(propertyId);
  806. if (width < 0) {
  807. columnWidths.remove(propertyId);
  808. } else {
  809. columnWidths.put(propertyId, width);
  810. }
  811. markAsDirty();
  812. }
  813. /**
  814. * Sets the column expand ratio for given column.
  815. * <p>
  816. * Expand ratios can be defined to customize the way how excess space is
  817. * divided among columns. Table can have excess space if it has its width
  818. * defined and there is horizontally more space than columns consume
  819. * naturally. Excess space is the space that is not used by columns with
  820. * explicit width (see {@link #setColumnWidth(Object, int)}) or with natural
  821. * width (no width nor expand ratio).
  822. *
  823. * <p>
  824. * By default (without expand ratios) the excess space is divided
  825. * proportionally to columns natural widths.
  826. *
  827. * <p>
  828. * Only expand ratios of visible columns are used in final calculations.
  829. *
  830. * <p>
  831. * Column can either have a fixed width or expand ratio. The latter one set
  832. * is used.
  833. *
  834. * <p>
  835. * A column with expand ratio is considered to be minimum width by default
  836. * (if no excess space exists). The minimum width is defined by terminal
  837. * implementation.
  838. *
  839. * <p>
  840. * If terminal implementation supports re-sizable columns the column becomes
  841. * fixed width column if users resizes the column.
  842. *
  843. * @param propertyId
  844. * columns property id
  845. * @param expandRatio
  846. * the expandRatio used to divide excess space for this column
  847. */
  848. public void setColumnExpandRatio(Object propertyId, float expandRatio) {
  849. if (propertyId == null) {
  850. // Since propertyId is null, this is the row header. Use the magic
  851. // id to store the width of the row header.
  852. propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
  853. }
  854. // Setting the column expand ratio should remove and defined column
  855. // width
  856. columnWidths.remove(propertyId);
  857. if (expandRatio < 0) {
  858. columnExpandRatios.remove(propertyId);
  859. } else {
  860. columnExpandRatios.put(propertyId, expandRatio);
  861. }
  862. requestRepaint();
  863. }
  864. /**
  865. * Gets the column expand ratio for a column. See
  866. * {@link #setColumnExpandRatio(Object, float)}
  867. *
  868. * @param propertyId
  869. * columns property id
  870. * @return the expandRatio used to divide excess space for this column
  871. */
  872. public float getColumnExpandRatio(Object propertyId) {
  873. final Float width = columnExpandRatios.get(propertyId);
  874. if (width == null) {
  875. return -1;
  876. }
  877. return width.floatValue();
  878. }
  879. /**
  880. * Gets the pixel width of column.
  881. *
  882. * @param propertyId
  883. * @return width of column or -1 when value not set
  884. */
  885. public int getColumnWidth(Object propertyId) {
  886. if (propertyId == null) {
  887. // Since propertyId is null, this is the row header. Use the magic
  888. // id to retrieve the width of the row header.
  889. propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
  890. }
  891. final Integer width = columnWidths.get(propertyId);
  892. if (width == null) {
  893. return -1;
  894. }
  895. return width.intValue();
  896. }
  897. /**
  898. * Gets the page length.
  899. *
  900. * <p>
  901. * Setting page length 0 disables paging.
  902. * </p>
  903. *
  904. * @return the Length of one page.
  905. */
  906. public int getPageLength() {
  907. return pageLength;
  908. }
  909. /**
  910. * Sets the page length.
  911. *
  912. * <p>
  913. * Setting page length 0 disables paging. The page length defaults to 15.
  914. * </p>
  915. *
  916. * <p>
  917. * If Table has height set ({@link #setHeight(float, Unit)} ) the client
  918. * side may update the page length automatically the correct value.
  919. * </p>
  920. *
  921. * @param pageLength
  922. * the length of one page.
  923. */
  924. public void setPageLength(int pageLength) {
  925. if (pageLength >= 0 && this.pageLength != pageLength) {
  926. this.pageLength = pageLength;
  927. // Assures the visual refresh
  928. refreshRowCache();
  929. }
  930. }
  931. /**
  932. * This method adjusts a possible caching mechanism of table implementation.
  933. *
  934. * <p>
  935. * Table component may fetch and render some rows outside visible area. With
  936. * complex tables (for example containing layouts and components), the
  937. * client side may become unresponsive. Setting the value lower, UI will
  938. * become more responsive. With higher values scrolling in client will hit
  939. * server less frequently.
  940. *
  941. * <p>
  942. * The amount of cached rows will be cacheRate multiplied with pageLength (
  943. * {@link #setPageLength(int)} both below and above visible area..
  944. *
  945. * @param cacheRate
  946. * a value over 0 (fastest rendering time). Higher value will
  947. * cache more rows on server (smoother scrolling). Default value
  948. * is 2.
  949. */
  950. public void setCacheRate(double cacheRate) {
  951. if (cacheRate < 0) {
  952. throw new IllegalArgumentException(
  953. "cacheRate cannot be less than zero");
  954. }
  955. if (this.cacheRate != cacheRate) {
  956. this.cacheRate = cacheRate;
  957. markAsDirty();
  958. }
  959. }
  960. /**
  961. * @see #setCacheRate(double)
  962. *
  963. * @return the current cache rate value
  964. */
  965. public double getCacheRate() {
  966. return cacheRate;
  967. }
  968. /**
  969. * Getter for property currentPageFirstItem.
  970. *
  971. * @return the Value of property currentPageFirstItem.
  972. */
  973. public Object getCurrentPageFirstItemId() {
  974. // Prioritise index over id if indexes are supported
  975. if (items instanceof Container.Indexed) {
  976. final int index = getCurrentPageFirstItemIndex();
  977. Object id = null;
  978. if (index >= 0 && index < size()) {
  979. id = getIdByIndex(index);
  980. }
  981. if (id != null && !id.equals(currentPageFirstItemId)) {
  982. currentPageFirstItemId = id;
  983. }
  984. }
  985. // If there is no item id at all, use the first one
  986. if (currentPageFirstItemId == null) {
  987. currentPageFirstItemId = firstItemId();
  988. }
  989. return currentPageFirstItemId;
  990. }
  991. /**
  992. * Returns the item ID for the item represented by the index given. Assumes
  993. * that the current container implements {@link Container.Indexed}.
  994. *
  995. * See {@link Container.Indexed#getIdByIndex(int)} for more information
  996. * about the exceptions that can be thrown.
  997. *
  998. * @param index
  999. * the index for which the item ID should be fetched
  1000. * @return the item ID for the given index
  1001. *
  1002. * @throws ClassCastException
  1003. * if container does not implement {@link Container.Indexed}
  1004. * @throws IndexOutOfBoundsException
  1005. * thrown by {@link Container.Indexed#getIdByIndex(int)} if the
  1006. * index is invalid
  1007. */
  1008. protected Object getIdByIndex(int index) {
  1009. return ((Container.Indexed) items).getIdByIndex(index);
  1010. }
  1011. /**
  1012. * Setter for property currentPageFirstItemId.
  1013. *
  1014. * @param currentPageFirstItemId
  1015. * the New value of property currentPageFirstItemId.
  1016. */
  1017. public void setCurrentPageFirstItemId(Object currentPageFirstItemId) {
  1018. // Gets the corresponding index
  1019. int index = -1;
  1020. if (items instanceof Container.Indexed) {
  1021. index = indexOfId(currentPageFirstItemId);
  1022. } else {
  1023. // If the table item container does not have index, we have to
  1024. // calculates the index by hand
  1025. Object id = firstItemId();
  1026. while (id != null && !id.equals(currentPageFirstItemId)) {
  1027. index++;
  1028. id = nextItemId(id);
  1029. }
  1030. if (id == null) {
  1031. index = -1;
  1032. }
  1033. }
  1034. // If the search for item index was successful
  1035. if (index >= 0) {
  1036. /*
  1037. * The table is not capable of displaying an item in the container
  1038. * as the first if there are not enough items following the selected
  1039. * item so the whole table (pagelength) is filled.
  1040. */
  1041. int maxIndex = size() - pageLength;
  1042. if (maxIndex < 0) {
  1043. maxIndex = 0;
  1044. }
  1045. if (index > maxIndex) {
  1046. // Note that we pass index, not maxIndex, letting
  1047. // setCurrentPageFirstItemIndex handle the situation.
  1048. setCurrentPageFirstItemIndex(index);
  1049. return;
  1050. }
  1051. this.currentPageFirstItemId = currentPageFirstItemId;
  1052. currentPageFirstItemIndex = index;
  1053. }
  1054. // Assures the visual refresh
  1055. refreshRowCache();
  1056. }
  1057. protected int indexOfId(Object itemId) {
  1058. return ((Container.Indexed) items).indexOfId(itemId);
  1059. }
  1060. /**
  1061. * Gets the icon Resource for the specified column.
  1062. *
  1063. * @param propertyId
  1064. * the propertyId identifying the column.
  1065. * @return the icon for the specified column; null if the column has no icon
  1066. * set, or if the column is not visible.
  1067. */
  1068. public Resource getColumnIcon(Object propertyId) {
  1069. return columnIcons.get(propertyId);
  1070. }
  1071. /**
  1072. * Sets the icon Resource for the specified column.
  1073. * <p>
  1074. * Throws IllegalArgumentException if the specified column is not visible.
  1075. * </p>
  1076. *
  1077. * @param propertyId
  1078. * the propertyId identifying the column.
  1079. * @param icon
  1080. * the icon Resource to set.
  1081. */
  1082. public void setColumnIcon(Object propertyId, Resource icon) {
  1083. if (icon == null) {
  1084. columnIcons.remove(propertyId);
  1085. } else {
  1086. columnIcons.put(propertyId, icon);
  1087. }
  1088. markAsDirty();
  1089. }
  1090. /**
  1091. * Gets the header for the specified column.
  1092. *
  1093. * @param propertyId
  1094. * the propertyId identifying the column.
  1095. * @return the header for the specified column if it has one.
  1096. */
  1097. public String getColumnHeader(Object propertyId) {
  1098. if (getColumnHeaderMode() == ColumnHeaderMode.HIDDEN) {
  1099. return null;
  1100. }
  1101. String header = columnHeaders.get(propertyId);
  1102. if ((header == null
  1103. && getColumnHeaderMode() == ColumnHeaderMode.EXPLICIT_DEFAULTS_ID)
  1104. || getColumnHeaderMode() == ColumnHeaderMode.ID) {
  1105. header = propertyId.toString();
  1106. }
  1107. return header;
  1108. }
  1109. /**
  1110. * Sets the column header for the specified column.
  1111. *
  1112. * @param propertyId
  1113. * the propertyId identifying the column.
  1114. * @param header
  1115. * the header to set.
  1116. */
  1117. public void setColumnHeader(Object propertyId, String header) {
  1118. if (header == null) {
  1119. columnHeaders.remove(propertyId);
  1120. } else {
  1121. columnHeaders.put(propertyId, header);
  1122. }
  1123. markAsDirty();
  1124. }
  1125. /**
  1126. * Gets the specified column's alignment.
  1127. *
  1128. * @param propertyId
  1129. * the propertyID identifying the column.
  1130. * @return the specified column's alignment if it as one; {@link Align#LEFT}
  1131. * otherwise.
  1132. */
  1133. public Align getColumnAlignment(Object propertyId) {
  1134. final Align a = columnAlignments.get(propertyId);
  1135. return a == null ? Align.LEFT : a;
  1136. }
  1137. /**
  1138. * Sets the specified column's alignment.
  1139. *
  1140. * <p>
  1141. * Throws IllegalArgumentException if the alignment is not one of the
  1142. * following: {@link Align#LEFT}, {@link Align#CENTER} or
  1143. * {@link Align#RIGHT}
  1144. * </p>
  1145. *
  1146. * @param propertyId
  1147. * the propertyID identifying the column.
  1148. * @param alignment
  1149. * the desired alignment.
  1150. */
  1151. public void setColumnAlignment(Object propertyId, Align alignment) {
  1152. if (alignment == null || alignment == Align.LEFT) {
  1153. columnAlignments.remove(propertyId);
  1154. } else {
  1155. columnAlignments.put(propertyId, alignment);
  1156. }
  1157. // Assures the visual refresh. No need to reset the page buffer before
  1158. // as the content has not changed, only the alignments.
  1159. refreshRenderedCells();
  1160. }
  1161. /**
  1162. * Checks if the specified column is collapsed.
  1163. *
  1164. * @param propertyId
  1165. * the propertyID identifying the column.
  1166. * @return true if the column is collapsed; false otherwise;
  1167. */
  1168. public boolean isColumnCollapsed(Object propertyId) {
  1169. return collapsedColumns != null
  1170. && collapsedColumns.contains(propertyId);
  1171. }
  1172. /**
  1173. * Sets whether the specified column is collapsed or not.
  1174. *
  1175. *
  1176. * @param propertyId
  1177. * the propertyID identifying the column.
  1178. * @param collapsed
  1179. * the desired collapsedness.
  1180. * @throws IllegalStateException
  1181. * if column collapsing is not allowed
  1182. * @throws IllegalArgumentException
  1183. * if the property id does not exist
  1184. */
  1185. public void setColumnCollapsed(Object propertyId, boolean collapsed)
  1186. throws IllegalStateException {
  1187. if (!isColumnCollapsingAllowed()) {
  1188. throw new IllegalStateException("Column collapsing not allowed!");
  1189. }
  1190. if (collapsed && noncollapsibleColumns.contains(propertyId)) {
  1191. throw new IllegalStateException("The column is noncollapsible!");
  1192. }
  1193. if (!getContainerPropertyIds().contains(propertyId)
  1194. && !columnGenerators.containsKey(propertyId)) {
  1195. throw new IllegalArgumentException("Property '" + propertyId
  1196. + "' was not found in the container");
  1197. }
  1198. if (collapsed) {
  1199. if (collapsedColumns.add(propertyId)) {
  1200. fireColumnCollapseEvent(propertyId);
  1201. }
  1202. } else {
  1203. if (collapsedColumns.remove(propertyId)) {
  1204. fireColumnCollapseEvent(propertyId);
  1205. }
  1206. }
  1207. // Assures the visual refresh
  1208. refreshRowCache();
  1209. }
  1210. /**
  1211. * Checks if column collapsing is allowed.
  1212. *
  1213. * @return true if columns can be collapsed; false otherwise.
  1214. */
  1215. public boolean isColumnCollapsingAllowed() {
  1216. return columnCollapsingAllowed;
  1217. }
  1218. /**
  1219. * Sets whether column collapsing is allowed or not.
  1220. *
  1221. * @param collapsingAllowed
  1222. * specifies whether column collapsing is allowed.
  1223. */
  1224. public void setColumnCollapsingAllowed(boolean collapsingAllowed) {
  1225. columnCollapsingAllowed = collapsingAllowed;
  1226. if (!collapsingAllowed) {
  1227. collapsedColumns.clear();
  1228. }
  1229. // Assures the visual refresh. No need to reset the page buffer before
  1230. // as the content has not changed, only the alignments.
  1231. refreshRenderedCells();
  1232. }
  1233. /**
  1234. * Sets whether the given column is collapsible. Note that collapsible
  1235. * columns can only be actually collapsed (via UI or with
  1236. * {@link #setColumnCollapsed(Object, boolean) setColumnCollapsed()}) if
  1237. * {@link #isColumnCollapsingAllowed()} is true. By default all columns are
  1238. * collapsible.
  1239. *
  1240. * @param propertyId
  1241. * the propertyID identifying the column.
  1242. * @param collapsible
  1243. * true if the column should be collapsible, false otherwise.
  1244. */
  1245. public void setColumnCollapsible(Object propertyId, boolean collapsible) {
  1246. if (collapsible) {
  1247. noncollapsibleColumns.remove(propertyId);
  1248. } else {
  1249. noncollapsibleColumns.add(propertyId);
  1250. collapsedColumns.remove(propertyId);
  1251. }
  1252. refreshRowCache();
  1253. }
  1254. /**
  1255. * Checks if the given column is collapsible. Note that even if this method
  1256. * returns <code>true</code>, the column can only be actually collapsed (via
  1257. * UI or with {@link #setColumnCollapsed(Object, boolean)
  1258. * setColumnCollapsed()}) if {@link #isColumnCollapsingAllowed()} is also
  1259. * true.
  1260. *
  1261. * @return true if the column can be collapsed; false otherwise.
  1262. */
  1263. public boolean isColumnCollapsible(Object propertyId) {
  1264. return !noncollapsibleColumns.contains(propertyId);
  1265. }
  1266. /**
  1267. * Checks if column reordering is allowed.
  1268. *
  1269. * @return true if columns can be reordered; false otherwise.
  1270. */
  1271. public boolean isColumnReorderingAllowed() {
  1272. return columnReorderingAllowed;
  1273. }
  1274. /**
  1275. * Sets whether column reordering is allowed or not.
  1276. *
  1277. * @param columnReorderingAllowed
  1278. * specifies whether column reordering is allowed.
  1279. */
  1280. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  1281. if (columnReorderingAllowed != this.columnReorderingAllowed) {
  1282. this.columnReorderingAllowed = columnReorderingAllowed;
  1283. markAsDirty();
  1284. }
  1285. }
  1286. /*
  1287. * Arranges visible columns according to given columnOrder. Silently ignores
  1288. * colimnId:s that are not visible columns, and keeps the internal order of
  1289. * visible columns left out of the ordering (trailing). Silently does
  1290. * nothing if columnReordering is not allowed.
  1291. */
  1292. private void setColumnOrder(Object[] columnOrder) {
  1293. if (columnOrder == null || !isColumnReorderingAllowed()) {
  1294. return;
  1295. }
  1296. final LinkedList<Object> newOrder = new LinkedList<Object>();
  1297. for (Object id : columnOrder) {
  1298. if (id != null && visibleColumns.contains(id)) {
  1299. visibleColumns.remove(id);
  1300. newOrder.add(id);
  1301. }
  1302. }
  1303. for (final Object columnId : visibleColumns) {
  1304. if (!newOrder.contains(columnId)) {
  1305. newOrder.add(columnId);
  1306. }
  1307. }
  1308. visibleColumns = newOrder;
  1309. // Assure visual refresh
  1310. refreshRowCache();
  1311. }
  1312. /**
  1313. * Getter for property currentPageFirstItem.
  1314. *
  1315. * @return the Value of property currentPageFirstItem.
  1316. */
  1317. public int getCurrentPageFirstItemIndex() {
  1318. return currentPageFirstItemIndex;
  1319. }
  1320. void setCurrentPageFirstItemIndex(int newIndex,
  1321. boolean needsPageBufferReset) {
  1322. if (newIndex < 0) {
  1323. newIndex = 0;
  1324. }
  1325. /*
  1326. * minimize Container.size() calls which may be expensive. For example
  1327. * it may cause sql query.
  1328. */
  1329. final int size = size();
  1330. /*
  1331. * The table is not capable of displaying an item in the container as
  1332. * the first if there are not enough items following the selected item
  1333. * so the whole table (pagelength) is filled.
  1334. */
  1335. int maxIndex = size - pageLength;
  1336. if (maxIndex < 0) {
  1337. maxIndex = 0;
  1338. }
  1339. /*
  1340. * If the new index is on the last page we set the index to be the first
  1341. * item on that last page and make a note of the real index for the
  1342. * client side to be able to move the scroll position to the correct
  1343. * position.
  1344. */
  1345. int indexOnLastPage = -1;
  1346. if (newIndex > maxIndex) {
  1347. indexOnLastPage = newIndex;
  1348. newIndex = maxIndex;
  1349. }
  1350. // Refresh first item id
  1351. if (items instanceof Container.Indexed) {
  1352. try {
  1353. currentPageFirstItemId = getIdByIndex(newIndex);
  1354. } catch (final IndexOutOfBoundsException e) {
  1355. currentPageFirstItemId = null;
  1356. }
  1357. currentPageFirstItemIndex = newIndex;
  1358. if (needsPageBufferReset) {
  1359. /*
  1360. * The flag currentPageFirstItemIndexOnLastPage denotes a user
  1361. * set scrolling position on the last page via
  1362. * setCurrentPageFirstItemIndex() and shouldn't be changed by
  1363. * the table component internally changing the firstvisible item
  1364. * on lazy row fetching. Doing so would make the scrolling
  1365. * position not be updated correctly when the lazy rows are
  1366. * finally rendered.
  1367. */
  1368. boolean isLastRowPossiblyPartiallyVisible = true;
  1369. if (indexOnLastPage != -1) {
  1370. /*
  1371. * If the requested row was greater than maxIndex, the last
  1372. * row should be fully visible (See
  1373. * TestCurrentPageFirstItem).
  1374. */
  1375. isLastRowPossiblyPartiallyVisible = false;
  1376. }
  1377. int extraRows = isLastRowPossiblyPartiallyVisible ? 0 : 1;
  1378. currentPageFirstItemIndexOnLastPage = currentPageFirstItemIndex
  1379. + extraRows;
  1380. } else {
  1381. currentPageFirstItemIndexOnLastPage = -1;
  1382. }
  1383. } else {
  1384. // For containers not supporting indexes, we must iterate the
  1385. // container forwards / backwards
  1386. // next available item forward or backward
  1387. currentPageFirstItemId = firstItemId();
  1388. // Go forwards in the middle of the list (respect borders)
  1389. while (currentPageFirstItemIndex < newIndex
  1390. && !isLastId(currentPageFirstItemId)) {
  1391. currentPageFirstItemIndex++;
  1392. currentPageFirstItemId = nextItemId(currentPageFirstItemId);
  1393. }
  1394. // If we did hit the border
  1395. if (isLastId(currentPageFirstItemId)) {
  1396. currentPageFirstItemIndex = size - 1;
  1397. }
  1398. // Go backwards in the middle of the list (respect borders)
  1399. while (currentPageFirstItemIndex > newIndex
  1400. && !isFirstId(currentPageFirstItemId)) {
  1401. currentPageFirstItemIndex--;
  1402. currentPageFirstItemId = prevItemId(currentPageFirstItemId);
  1403. }
  1404. // If we did hit the border
  1405. if (isFirstId(currentPageFirstItemId)) {
  1406. currentPageFirstItemIndex = 0;
  1407. }
  1408. // Go forwards once more
  1409. while (currentPageFirstItemIndex < newIndex
  1410. && !isLastId(currentPageFirstItemId)) {
  1411. currentPageFirstItemIndex++;
  1412. currentPageFirstItemId = nextItemId(currentPageFirstItemId);
  1413. }
  1414. // If for some reason we do hit border again, override
  1415. // the user index request
  1416. if (isLastId(currentPageFirstItemId)) {
  1417. newIndex = currentPageFirstItemIndex = size - 1;
  1418. }
  1419. }
  1420. if (needsPageBufferReset) {
  1421. // Assures the visual refresh
  1422. refreshRowCache();
  1423. }
  1424. }
  1425. /**
  1426. * Setter for property currentPageFirstItem.
  1427. *
  1428. * @param newIndex
  1429. * the New value of property currentPageFirstItem.
  1430. */
  1431. public void setCurrentPageFirstItemIndex(int newIndex) {
  1432. setCurrentPageFirstItemIndex(newIndex, true);
  1433. }
  1434. /**
  1435. * Returns whether table is selectable.
  1436. *
  1437. * <p>
  1438. * The table is not selectable until it's explicitly set as selectable or at
  1439. * least one {@link ValueChangeListener} is added.
  1440. * </p>
  1441. *
  1442. * @return whether table is selectable.
  1443. */
  1444. public boolean isSelectable() {
  1445. if (selectable == null) {
  1446. return hasListeners(ValueChangeEvent.class);
  1447. }
  1448. return selectable;
  1449. }
  1450. /**
  1451. * Setter for property selectable.
  1452. *
  1453. * <p>
  1454. * The table is not selectable until it's explicitly set as selectable via
  1455. * this method or alternatively at least one {@link ValueChangeListener} is
  1456. * added.
  1457. * </p>
  1458. *
  1459. * @param selectable
  1460. * the New value of property selectable.
  1461. */
  1462. public void setSelectable(boolean selectable) {
  1463. if (!SharedUtil.equals(this.selectable, selectable)) {
  1464. this.selectable = selectable;
  1465. markAsDirty();
  1466. }
  1467. }
  1468. /**
  1469. * Getter for property columnHeaderMode.
  1470. *
  1471. * @return the Value of property columnHeaderMode.
  1472. */
  1473. public ColumnHeaderMode getColumnHeaderMode() {
  1474. return columnHeaderMode;
  1475. }
  1476. /**
  1477. * Setter for property columnHeaderMode.
  1478. *
  1479. * @param columnHeaderMode
  1480. * the New value of property columnHeaderMode.
  1481. */
  1482. public void setColumnHeaderMode(ColumnHeaderMode columnHeaderMode) {
  1483. if (columnHeaderMode == null) {
  1484. throw new IllegalArgumentException(
  1485. "Column header mode can not be null");
  1486. }
  1487. if (columnHeaderMode != this.columnHeaderMode) {
  1488. this.columnHeaderMode = columnHeaderMode;
  1489. markAsDirty();
  1490. }
  1491. }
  1492. /**
  1493. * Refreshes the rows in the internal cache. Only if
  1494. * {@link #resetPageBuffer()} is called before this then all values are
  1495. * guaranteed to be recreated.
  1496. */
  1497. protected void refreshRenderedCells() {
  1498. if (!isAttached()) {
  1499. return;
  1500. }
  1501. if (!isContentRefreshesEnabled) {
  1502. return;
  1503. }
  1504. // Collects the basic facts about the table page
  1505. final int pagelen = getPageLength();
  1506. int rows, totalRows;
  1507. rows = totalRows = size();
  1508. int firstIndex = Math.min(getCurrentPageFirstItemIndex(),
  1509. totalRows - 1);
  1510. if (rows > 0 && firstIndex >= 0) {
  1511. rows -= firstIndex;
  1512. }
  1513. if (pagelen > 0 && pagelen < rows) {
  1514. rows = pagelen;
  1515. }
  1516. // If "to be painted next" variables are set, use them
  1517. if (lastToBeRenderedInClient - firstToBeRenderedInClient > 0) {
  1518. rows = lastToBeRenderedInClient - firstToBeRenderedInClient + 1;
  1519. }
  1520. if (firstToBeRenderedInClient >= 0) {
  1521. if (firstToBeRenderedInClient < totalRows) {
  1522. firstIndex = firstToBeRenderedInClient;
  1523. } else {
  1524. firstIndex = totalRows - 1;
  1525. }
  1526. } else {
  1527. // initial load
  1528. // #8805 send one extra row in the beginning in case a partial
  1529. // row is shown on the UI
  1530. if (firstIndex > 0) {
  1531. firstIndex = firstIndex - 1;
  1532. rows = rows + 1;
  1533. }
  1534. firstToBeRenderedInClient = firstIndex;
  1535. }
  1536. if (totalRows > 0) {
  1537. if (rows + firstIndex > totalRows) {
  1538. rows = totalRows - firstIndex;
  1539. }
  1540. } else {
  1541. rows = 0;
  1542. }
  1543. // Saves the results to internal buffer
  1544. pageBuffer = getVisibleCellsNoCache(firstIndex, rows, true);
  1545. if (rows > 0) {
  1546. pageBufferFirstIndex = firstIndex;
  1547. }
  1548. setRowCacheInvalidated(true);
  1549. markAsDirty();
  1550. maybeThrowCacheUpdateExceptions();
  1551. }
  1552. private void maybeThrowCacheUpdateExceptions() {
  1553. if (!exceptionsDuringCachePopulation.isEmpty()) {
  1554. Throwable[] causes = new Throwable[exceptionsDuringCachePopulation
  1555. .size()];
  1556. exceptionsDuringCachePopulation.toArray(causes);
  1557. exceptionsDuringCachePopulation.clear();
  1558. throw new CacheUpdateException(this,
  1559. "Error during Table cache update.", causes);
  1560. }
  1561. }
  1562. /**
  1563. * Exception thrown when one or more exceptions occurred during updating of
  1564. * the Table cache.
  1565. * <p>
  1566. * Contains all exceptions which occurred during the cache update. The first
  1567. * occurred exception is set as the cause of this exception. All occurred
  1568. * exceptions can be accessed using {@link #getCauses()}.
  1569. * </p>
  1570. *
  1571. */
  1572. @Deprecated
  1573. public static class CacheUpdateException extends RuntimeException {
  1574. private Throwable[] causes;
  1575. private Table table;
  1576. public CacheUpdateException(Table table, String message,
  1577. Throwable[] causes) {
  1578. super(maybeSupplementMessage(message, causes.length), causes[0]);
  1579. this.table = table;
  1580. this.causes = causes;
  1581. }
  1582. private static String maybeSupplementMessage(String message,
  1583. int causeCount) {
  1584. if (causeCount > 1) {
  1585. return message + " Additional causes not shown.";
  1586. } else {
  1587. return message;
  1588. }
  1589. }
  1590. /**
  1591. * Returns the cause(s) for this exception.
  1592. *
  1593. * @return the exception(s) which caused this exception
  1594. */
  1595. public Throwable[] getCauses() {
  1596. return causes;
  1597. }
  1598. public Table getTable() {
  1599. return table;
  1600. }
  1601. }
  1602. /**
  1603. * Requests that the Table should be repainted as soon as possible.
  1604. *
  1605. * Note that a {@code Table} does not necessarily repaint its contents when
  1606. * this method has been called. See {@link #refreshRowCache()} for forcing
  1607. * an update of the contents.
  1608. *
  1609. * @deprecated As of 7.0, use {@link #markAsDirty()} instead
  1610. */
  1611. @Deprecated
  1612. @Override
  1613. public void requestRepaint() {
  1614. markAsDirty();
  1615. }
  1616. /**
  1617. * Requests that the Table should be repainted as soon as possible.
  1618. *
  1619. * Note that a {@code Table} does not necessarily repaint its contents when
  1620. * this method has been called. See {@link #refreshRowCache()} for forcing
  1621. * an update of the contents.
  1622. */
  1623. @Override
  1624. public void markAsDirty() {
  1625. // Overridden only for javadoc
  1626. super.markAsDirty();
  1627. }
  1628. @Override
  1629. public void markAsDirtyRecursive() {
  1630. super.markAsDirtyRecursive();
  1631. // Avoid sending a partial repaint (#8714)
  1632. refreshRowCache();
  1633. }
  1634. private void removeRowsFromCacheAndFillBottom(int firstIndex, int rows) {
  1635. int totalCachedRows = pageBuffer[CELL_ITEMID].length;
  1636. int totalRows = size();
  1637. int firstIndexInPageBuffer = firstIndex - pageBufferFirstIndex;
  1638. /*
  1639. * firstIndexInPageBuffer is the first row to be removed. "rows" rows
  1640. * after that should be removed. If the page buffer does not contain
  1641. * that many rows, we only remove the rows that actually are in the page
  1642. * buffer.
  1643. */
  1644. if (firstIndexInPageBuffer + rows > totalCachedRows) {
  1645. rows = totalCachedRows - firstIndexInPageBuffer;
  1646. }
  1647. /*
  1648. * Unregister components that will no longer be in the page buffer to
  1649. * make sure that no components leak.
  1650. */
  1651. unregisterComponentsAndPropertiesInRows(firstIndex, rows);
  1652. /*
  1653. * The number of rows that should be in the cache after this operation
  1654. * is done (pageBuffer currently contains the expanded items).
  1655. */
  1656. int newCachedRowCount = totalCachedRows;
  1657. if (newCachedRowCount + pageBufferFirstIndex > totalRows) {
  1658. newCachedRowCount = totalRows - pageBufferFirstIndex;
  1659. }
  1660. /*
  1661. * The index at which we should render the first row that does not come
  1662. * from the previous page buffer.
  1663. */
  1664. int firstAppendedRowInPageBuffer = totalCachedRows - rows;
  1665. int firstAppendedRow = firstAppendedRowInPageBuffer
  1666. + pageBufferFirstIndex;
  1667. /*
  1668. * Calculate the maximum number of new rows that we can add to the page
  1669. * buffer. Less than the rows we removed if the container does not
  1670. * contain that many items afterwards.
  1671. */
  1672. int maxRowsToRender = (totalRows - firstAppendedRow);
  1673. int rowsToAdd = rows;
  1674. if (rowsToAdd > maxRowsToRender) {
  1675. rowsToAdd = maxRowsToRender;
  1676. }
  1677. Object[][] cells = null;
  1678. if (rowsToAdd > 0) {
  1679. cells = getVisibleCellsNoCache(firstAppendedRow, rowsToAdd, false);
  1680. }
  1681. /*
  1682. * Create the new cache buffer by copying the first rows from the old
  1683. * buffer, moving the following rows upwards and appending more rows if
  1684. * applicable.
  1685. */
  1686. Object[][] newPageBuffer = new Object[pageBuffer.length][newCachedRowCount];
  1687. for (int i = 0; i < pageBuffer.length; i++) {
  1688. for (int row = 0; row < firstIndexInPageBuffer; row++) {
  1689. // Copy the first rows
  1690. newPageBuffer[i][row] = pageBuffer[i][row];
  1691. }
  1692. for (int row = firstIndexInPageBuffer; row < firstAppendedRowInPageBuffer; row++) {
  1693. // Move the rows that were after the expanded rows
  1694. newPageBuffer[i][row] = pageBuffer[i][row + rows];
  1695. }
  1696. for (int row = firstAppendedRowInPageBuffer; row < newCachedRowCount; row++) {
  1697. // Add the newly rendered rows. Only used if rowsToAdd > 0
  1698. // (cells != null)
  1699. newPageBuffer[i][row] = cells[i][row
  1700. - firstAppendedRowInPageBuffer];
  1701. }
  1702. }
  1703. pageBuffer = newPageBuffer;
  1704. }
  1705. private Object[][] getVisibleCellsUpdateCacheRows(int firstIndex,
  1706. int rows) {
  1707. Object[][] cells = getVisibleCellsNoCache(firstIndex, rows, false);
  1708. int cacheIx = firstIndex - pageBufferFirstIndex;
  1709. // update the new rows in the cache.
  1710. int totalCachedRows = pageBuffer[CELL_ITEMID].length;
  1711. int end = Math.min(cacheIx + rows, totalCachedRows);
  1712. for (int ix = cacheIx; ix < end; ix++) {
  1713. for (int i = 0; i < pageBuffer.length; i++) {
  1714. pageBuffer[i][ix] = cells[i][ix - cacheIx];
  1715. }
  1716. }
  1717. return cells;
  1718. }
  1719. /**
  1720. * @param firstIndex
  1721. * The position where new rows should be inserted
  1722. * @param rows
  1723. * The maximum number of rows that should be inserted at position
  1724. * firstIndex. Less rows will be inserted if the page buffer is
  1725. * too small.
  1726. * @return
  1727. */
  1728. private Object[][] getVisibleCellsInsertIntoCache(int firstIndex,
  1729. int rows) {
  1730. getLogger().log(Level.FINEST,
  1731. "Insert {0} rows at index {1} to existing page buffer requested",
  1732. new Object[] { rows, firstIndex });
  1733. int minPageBufferIndex = getMinPageBufferIndex();
  1734. int maxPageBufferIndex = getMaxPageBufferIndex();
  1735. int maxBufferSize = maxPageBufferIndex - minPageBufferIndex + 1;
  1736. if (getPageLength() == 0) {
  1737. // If pageLength == 0 then all rows should be rendered
  1738. maxBufferSize = pageBuffer[CELL_ITEMID].length + rows;
  1739. }
  1740. /*
  1741. * Number of rows that were previously cached. This is not necessarily
  1742. * the same as maxBufferSize.
  1743. */
  1744. int currentlyCachedRowCount = pageBuffer[CELL_ITEMID].length;
  1745. /* If rows > size available in page buffer */
  1746. if (firstIndex + rows - 1 > maxPageBufferIndex) {
  1747. rows = maxPageBufferIndex - firstIndex + 1;
  1748. }
  1749. /*
  1750. * "rows" rows will be inserted at firstIndex. Find out how many old
  1751. * rows fall outside the new buffer so we can unregister components in
  1752. * the cache.
  1753. */
  1754. /*
  1755. * if there are rows before the new pageBuffer limits they must be
  1756. * removed
  1757. */
  1758. int lastCacheRowToRemove = minPageBufferIndex - 1;
  1759. int rowsFromBeginning = lastCacheRowToRemove - pageBufferFirstIndex + 1;
  1760. if (lastCacheRowToRemove >= pageBufferFirstIndex) {
  1761. unregisterComponentsAndPropertiesInRows(pageBufferFirstIndex,
  1762. rowsFromBeginning);
  1763. } else {
  1764. rowsFromBeginning = 0;
  1765. }
  1766. /*
  1767. * the rows that fall outside of the new pageBuffer limits after the new
  1768. * rows are inserted must also be removed
  1769. */
  1770. int firstCacheRowToRemove = firstIndex;
  1771. /*
  1772. * IF there is space remaining in the buffer after the rows have been
  1773. * inserted, we can keep more rows.
  1774. */
  1775. int numberOfOldRowsAfterInsertedRows = Math.min(
  1776. pageBufferFirstIndex + currentlyCachedRowCount + rows,
  1777. maxPageBufferIndex + 1) - (firstIndex + rows - 1);
  1778. if (numberOfOldRowsAfterInsertedRows > 0) {
  1779. firstCacheRowToRemove += numberOfOldRowsAfterInsertedRows;
  1780. }
  1781. int rowsFromAfter = currentlyCachedRowCount
  1782. - (firstCacheRowToRemove - pageBufferFirstIndex);
  1783. if (rowsFromAfter > 0) {
  1784. /*
  1785. * Unregister all components that fall beyond the cache limits after
  1786. * inserting the new rows.
  1787. */
  1788. unregisterComponentsAndPropertiesInRows(firstCacheRowToRemove,
  1789. rowsFromAfter);
  1790. }
  1791. // Calculate the new cache size
  1792. int newCachedRowCount = maxBufferSize;
  1793. if (pageBufferFirstIndex + currentlyCachedRowCount + rows
  1794. - 1 < maxPageBufferIndex) {
  1795. // there aren't enough rows to fill the whole potential -> use what
  1796. // there is
  1797. newCachedRowCount -= maxPageBufferIndex - (pageBufferFirstIndex
  1798. + currentlyCachedRowCount + rows - 1);
  1799. } else if (minPageBufferIndex < pageBufferFirstIndex) {
  1800. newCachedRowCount -= pageBufferFirstIndex - minPageBufferIndex;
  1801. }
  1802. /*
  1803. * calculate the internal location of the new rows within the new cache
  1804. */
  1805. int firstIndexInNewPageBuffer = firstIndex - pageBufferFirstIndex
  1806. - rowsFromBeginning;
  1807. /* Paint the new rows into a separate buffer */
  1808. Object[][] cells = getVisibleCellsNoCache(firstIndex, rows, false);
  1809. /*
  1810. * Create the new cache buffer and fill it with the data from the old
  1811. * buffer as well as the inserted rows.
  1812. */
  1813. Object[][] newPageBuffer = new Object[pageBuffer.length][newCachedRowCount];
  1814. for (int i = 0; i < pageBuffer.length; i++) {
  1815. for (int row = 0; row < firstIndexInNewPageBuffer; row++) {
  1816. // Copy the first rows
  1817. newPageBuffer[i][row] = pageBuffer[i][rowsFromBeginning + row];
  1818. }
  1819. for (int row = firstIndexInNewPageBuffer; row < firstIndexInNewPageBuffer
  1820. + rows; row++) {
  1821. // Copy the newly created rows
  1822. newPageBuffer[i][row] = cells[i][row
  1823. - firstIndexInNewPageBuffer];
  1824. }
  1825. for (int row = firstIndexInNewPageBuffer
  1826. + rows; row < newCachedRowCount; row++) {
  1827. // Move the old rows down below the newly inserted rows
  1828. newPageBuffer[i][row] = pageBuffer[i][rowsFromBeginning + row
  1829. - rows];
  1830. }
  1831. }
  1832. pageBuffer = newPageBuffer;
  1833. pageBufferFirstIndex = Math.max(
  1834. pageBufferFirstIndex + rowsFromBeginning, minPageBufferIndex);
  1835. if (getLogger().isLoggable(Level.FINEST)) {
  1836. getLogger().log(Level.FINEST,
  1837. "Page Buffer now contains {0} rows ({1}-{2})",
  1838. new Object[] { pageBuffer[CELL_ITEMID].length,
  1839. pageBufferFirstIndex, (pageBufferFirstIndex
  1840. + pageBuffer[CELL_ITEMID].length - 1) });
  1841. }
  1842. return cells;
  1843. }
  1844. private int getMaxPageBufferIndex() {
  1845. int total = size();
  1846. if (getPageLength() == 0) {
  1847. // everything is shown at once, no caching
  1848. return total - 1;
  1849. }
  1850. // Page buffer must not become larger than pageLength*cacheRate after
  1851. // the current page
  1852. int maxPageBufferIndex = getCurrentPageFirstItemIndex()
  1853. + (int) (getPageLength() * (1 + getCacheRate()));
  1854. if (shouldHideNullSelectionItem()) {
  1855. --total;
  1856. }
  1857. if (maxPageBufferIndex >= total) {
  1858. maxPageBufferIndex = total - 1;
  1859. }
  1860. return maxPageBufferIndex;
  1861. }
  1862. private int getMinPageBufferIndex() {
  1863. if (getPageLength() == 0) {
  1864. // everything is shown at once, no caching
  1865. return 0;
  1866. }
  1867. // Page buffer must not become larger than pageLength*cacheRate before
  1868. // the current page
  1869. int minPageBufferIndex = getCurrentPageFirstItemIndex()
  1870. - (int) (getPageLength() * getCacheRate());
  1871. if (minPageBufferIndex < 0) {
  1872. minPageBufferIndex = 0;
  1873. }
  1874. return minPageBufferIndex;
  1875. }
  1876. /**
  1877. * Render rows with index "firstIndex" to "firstIndex+rows-1" to a new
  1878. * buffer.
  1879. *
  1880. * Reuses values from the current page buffer if the rows are found there.
  1881. *
  1882. * @param firstIndex
  1883. * @param rows
  1884. * @param replaceListeners
  1885. * @return
  1886. */
  1887. private Object[][] getVisibleCellsNoCache(int firstIndex, int rows,
  1888. boolean replaceListeners) {
  1889. if (getLogger().isLoggable(Level.FINEST)) {
  1890. getLogger().log(Level.FINEST,
  1891. "Render visible cells for rows {0}-{1}",
  1892. new Object[] { firstIndex, (firstIndex + rows - 1) });
  1893. }
  1894. final Object[] colids = getVisibleColumns();
  1895. final int cols = colids.length;
  1896. HashSet<Property<?>> oldListenedProperties = listenedProperties;
  1897. HashSet<Component> oldVisibleComponents = visibleComponents;
  1898. if (replaceListeners) {
  1899. // initialize the listener collections, this should only be done if
  1900. // the entire cache is refreshed (through refreshRenderedCells)
  1901. listenedProperties = new HashSet<Property<?>>();
  1902. visibleComponents = new HashSet<Component>();
  1903. }
  1904. Object[][] cells = new Object[cols + CELL_FIRSTCOL][rows];
  1905. if (rows == 0) {
  1906. unregisterPropertiesAndComponents(oldListenedProperties,
  1907. oldVisibleComponents);
  1908. return cells;
  1909. }
  1910. final RowHeaderMode headmode = getRowHeaderMode();
  1911. final boolean[] iscomponent = new boolean[cols];
  1912. for (int i = 0; i < cols; i++) {
  1913. iscomponent[i] = columnGenerators.containsKey(colids[i])
  1914. || Component.class.isAssignableFrom(getType(colids[i]));
  1915. }
  1916. int firstIndexNotInCache;
  1917. if (pageBuffer != null && pageBuffer[CELL_ITEMID].length > 0) {
  1918. firstIndexNotInCache = pageBufferFirstIndex
  1919. + pageBuffer[CELL_ITEMID].length;
  1920. } else {
  1921. firstIndexNotInCache = -1;
  1922. }
  1923. // Creates the page contents
  1924. int filledRows = 0;
  1925. if (items instanceof Container.Indexed) {
  1926. // more efficient implementation for containers supporting access by
  1927. // index
  1928. List<?> itemIds = getItemIds(firstIndex, rows);
  1929. for (int i = 0; i < rows && i < itemIds.size(); i++) {
  1930. Object id = itemIds.get(i);
  1931. if (id == null) {
  1932. throw new IllegalStateException(
  1933. "Null itemId returned from container");
  1934. }
  1935. // Start by parsing the values, id should already be set
  1936. parseItemIdToCells(cells, id, i, firstIndex, headmode, cols,
  1937. colids, firstIndexNotInCache, iscomponent,
  1938. oldListenedProperties);
  1939. filledRows++;
  1940. }
  1941. } else {
  1942. // slow back-up implementation for cases where the container does
  1943. // not support access by index
  1944. // Gets the first item id
  1945. Object id = firstItemId();
  1946. for (int i = 0; i < firstIndex; i++) {
  1947. id = nextItemId(id);
  1948. }
  1949. for (int i = 0; i < rows && id != null; i++) {
  1950. // Start by parsing the values, id should already be set
  1951. parseItemIdToCells(cells, id, i, firstIndex, headmode, cols,
  1952. colids, firstIndexNotInCache, iscomponent,
  1953. oldListenedProperties);
  1954. // Gets the next item id for non indexed container
  1955. id = nextItemId(id);
  1956. filledRows++;
  1957. }
  1958. }
  1959. // Assures that all the rows of the cell-buffer are valid
  1960. if (filledRows != cells[0].length) {
  1961. final Object[][] temp = new Object[cells.length][filledRows];
  1962. for (int i = 0; i < cells.length; i++) {
  1963. for (int j = 0; j < filledRows; j++) {
  1964. temp[i][j] = cells[i][j];
  1965. }
  1966. }
  1967. cells = temp;
  1968. }
  1969. unregisterPropertiesAndComponents(oldListenedProperties,
  1970. oldVisibleComponents);
  1971. return cells;
  1972. }
  1973. protected List<Object> getItemIds(int firstIndex, int rows) {
  1974. return (List<Object>) ((Container.Indexed) items).getItemIds(firstIndex,
  1975. rows);
  1976. }
  1977. /**
  1978. * Update a cache array for a row, register any relevant listeners etc.
  1979. *
  1980. * This is an internal method extracted from
  1981. * {@link #getVisibleCellsNoCache(int, int, boolean)} and should be removed
  1982. * when the Table is rewritten.
  1983. */
  1984. private void parseItemIdToCells(Object[][] cells, Object id, int i,
  1985. int firstIndex, RowHeaderMode headmode, int cols, Object[] colids,
  1986. int firstIndexNotInCache, boolean[] iscomponent,
  1987. HashSet<Property<?>> oldListenedProperties) {
  1988. cells[CELL_ITEMID][i] = id;
  1989. cells[CELL_KEY][i] = itemIdMapper.key(id);
  1990. if (headmode != ROW_HEADER_MODE_HIDDEN) {
  1991. switch (headmode) {
  1992. case INDEX:
  1993. cells[CELL_HEADER][i] = String.valueOf(i + firstIndex + 1);
  1994. break;
  1995. default:
  1996. try {
  1997. cells[CELL_HEADER][i] = getItemCaption(id);
  1998. } catch (Exception e) {
  1999. exceptionsDuringCachePopulation.add(e);
  2000. cells[CELL_HEADER][i] = "";
  2001. }
  2002. }
  2003. try {
  2004. cells[CELL_ICON][i] = getItemIcon(id);
  2005. } catch (Exception e) {
  2006. exceptionsDuringCachePopulation.add(e);
  2007. cells[CELL_ICON][i] = null;
  2008. }
  2009. }
  2010. GeneratedRow generatedRow = rowGenerator != null
  2011. ? rowGenerator.generateRow(this, id)
  2012. : null;
  2013. cells[CELL_GENERATED_ROW][i] = generatedRow;
  2014. for (int j = 0; j < cols; j++) {
  2015. if (isColumnCollapsed(colids[j])) {
  2016. continue;
  2017. }
  2018. Property<?> p = null;
  2019. Object value = "";
  2020. boolean isGeneratedRow = generatedRow != null;
  2021. boolean isGeneratedColumn = columnGenerators.containsKey(colids[j]);
  2022. boolean isGenerated = isGeneratedRow || isGeneratedColumn;
  2023. if (!isGenerated) {
  2024. try {
  2025. p = getContainerProperty(id, colids[j]);
  2026. } catch (Exception e) {
  2027. exceptionsDuringCachePopulation.add(e);
  2028. value = null;
  2029. }
  2030. }
  2031. if (isGeneratedRow) {
  2032. if (generatedRow.isSpanColumns() && j > 0) {
  2033. value = null;
  2034. } else if (generatedRow.isSpanColumns() && j == 0
  2035. && generatedRow.getValue() instanceof Component) {
  2036. value = generatedRow.getValue();
  2037. } else if (generatedRow.getText().length > j) {
  2038. value = generatedRow.getText()[j];
  2039. }
  2040. } else {
  2041. // check if current pageBuffer already has row
  2042. int index = firstIndex + i;
  2043. if (p != null || isGenerated) {
  2044. int indexInOldBuffer = index - pageBufferFirstIndex;
  2045. if (index < firstIndexNotInCache
  2046. && index >= pageBufferFirstIndex
  2047. && pageBuffer[CELL_GENERATED_ROW][indexInOldBuffer] == null
  2048. && id.equals(
  2049. pageBuffer[CELL_ITEMID][indexInOldBuffer])) {
  2050. // we already have data in our cache,
  2051. // recycle it instead of fetching it via
  2052. // getValue/getPropertyValue
  2053. value = pageBuffer[CELL_FIRSTCOL + j][indexInOldBuffer];
  2054. if (!isGeneratedColumn && iscomponent[j]
  2055. || !(value instanceof Component)) {
  2056. listenProperty(p, oldListenedProperties);
  2057. }
  2058. } else {
  2059. if (isGeneratedColumn) {
  2060. ColumnGenerator cg = columnGenerators
  2061. .get(colids[j]);
  2062. try {
  2063. value = cg.generateCell(this, id, colids[j]);
  2064. } catch (Exception e) {
  2065. exceptionsDuringCachePopulation.add(e);
  2066. value = null;
  2067. }
  2068. if (value != null && !(value instanceof Component)
  2069. && !(value instanceof String)) {
  2070. // Avoid errors if a generator returns
  2071. // something
  2072. // other than a Component or a String
  2073. value = value.toString();
  2074. }
  2075. } else if (iscomponent[j]) {
  2076. try {
  2077. value = p.getValue();
  2078. } catch (Exception e) {
  2079. exceptionsDuringCachePopulation.add(e);
  2080. value = null;
  2081. }
  2082. listenProperty(p, oldListenedProperties);
  2083. } else if (p != null) {
  2084. try {
  2085. value = getPropertyValue(id, colids[j], p);
  2086. } catch (Exception e) {
  2087. exceptionsDuringCachePopulation.add(e);
  2088. value = null;
  2089. }
  2090. /*
  2091. * If returned value is Component (via fieldfactory
  2092. * or overridden getPropertyValue) we expect it to
  2093. * listen property value changes. Otherwise if
  2094. * property emits value change events, table will
  2095. * start to listen them and refresh content when
  2096. * needed.
  2097. */
  2098. if (!(value instanceof Component)) {
  2099. listenProperty(p, oldListenedProperties);
  2100. }
  2101. } else {
  2102. try {
  2103. value = getPropertyValue(id, colids[j], null);
  2104. } catch (Exception e) {
  2105. exceptionsDuringCachePopulation.add(e);
  2106. value = null;
  2107. }
  2108. }
  2109. }
  2110. }
  2111. }
  2112. if (value instanceof Component) {
  2113. registerComponent((Component) value);
  2114. }
  2115. cells[CELL_FIRSTCOL + j][i] = value;
  2116. }
  2117. }
  2118. protected void registerComponent(Component component) {
  2119. getLogger().log(Level.FINEST, "Registered {0}: {1}", new Object[] {
  2120. component.getClass().getSimpleName(), component.getCaption() });
  2121. if (!equals(component.getParent())) {
  2122. component.setParent(this);
  2123. }
  2124. visibleComponents.add(component);
  2125. }
  2126. private void listenProperty(Property<?> p,
  2127. HashSet<Property<?>> oldListenedProperties) {
  2128. if (p instanceof Property.ValueChangeNotifier) {
  2129. if (oldListenedProperties == null
  2130. || !oldListenedProperties.contains(p)) {
  2131. ((Property.ValueChangeNotifier) p).addListener(this);
  2132. }
  2133. /*
  2134. * register listened properties, so we can do proper cleanup to free
  2135. * memory. Essential if table has loads of data and it is used for a
  2136. * long time.
  2137. */
  2138. listenedProperties.add(p);
  2139. }
  2140. }
  2141. /**
  2142. * @param firstIx
  2143. * Index of the first row to process. Global index, not relative
  2144. * to page buffer.
  2145. * @param count
  2146. */
  2147. private void unregisterComponentsAndPropertiesInRows(int firstIx,
  2148. int count) {
  2149. if (getLogger().isLoggable(Level.FINEST)) {
  2150. getLogger().log(Level.FINEST,
  2151. "Unregistering components in rows {0}-{1}",
  2152. new Object[] { firstIx, (firstIx + count - 1) });
  2153. }
  2154. Object[] colids = getVisibleColumns();
  2155. if (pageBuffer != null && pageBuffer[CELL_ITEMID].length > 0) {
  2156. int bufSize = pageBuffer[CELL_ITEMID].length;
  2157. int ix = firstIx - pageBufferFirstIndex;
  2158. ix = ix < 0 ? 0 : ix;
  2159. if (ix < bufSize) {
  2160. count = count > bufSize - ix ? bufSize - ix : count;
  2161. for (int i = 0; i < count; i++) {
  2162. for (int c = 0; c < colids.length; c++) {
  2163. Object cellVal = pageBuffer[CELL_FIRSTCOL + c][i + ix];
  2164. if (cellVal instanceof Component
  2165. && visibleComponents.contains(cellVal)) {
  2166. visibleComponents.remove(cellVal);
  2167. unregisterComponent((Component) cellVal);
  2168. } else {
  2169. Property<?> p = getContainerProperty(
  2170. pageBuffer[CELL_ITEMID][i + ix], colids[c]);
  2171. if (p instanceof ValueChangeNotifier
  2172. && listenedProperties.contains(p)) {
  2173. listenedProperties.remove(p);
  2174. ((ValueChangeNotifier) p).removeListener(this);
  2175. }
  2176. }
  2177. }
  2178. }
  2179. }
  2180. }
  2181. }
  2182. /**
  2183. * Helper method to remove listeners and maintain correct component
  2184. * hierarchy. Detaches properties and components if those are no more
  2185. * rendered in client.
  2186. *
  2187. * @param oldListenedProperties
  2188. * set of properties that where listened in last render
  2189. * @param oldVisibleComponents
  2190. * set of components that where attached in last render
  2191. */
  2192. private void unregisterPropertiesAndComponents(
  2193. HashSet<Property<?>> oldListenedProperties,
  2194. HashSet<Component> oldVisibleComponents) {
  2195. if (oldVisibleComponents != null) {
  2196. for (final Component c : oldVisibleComponents) {
  2197. if (!visibleComponents.contains(c)) {
  2198. unregisterComponent(c);
  2199. }
  2200. }
  2201. }
  2202. if (oldListenedProperties != null) {
  2203. for (final Property<?> p : oldListenedProperties) {
  2204. Property.ValueChangeNotifier o = (ValueChangeNotifier) p;
  2205. if (!listenedProperties.contains(o)) {
  2206. o.removeListener(this);
  2207. }
  2208. }
  2209. }
  2210. }
  2211. /**
  2212. * This method cleans up a Component that has been generated when Table is
  2213. * in editable mode. The component needs to be detached from its parent and
  2214. * if it is a field, it needs to be detached from its property data source
  2215. * in order to allow garbage collection to take care of removing the unused
  2216. * component from memory.
  2217. *
  2218. * Override this method and getPropertyValue(Object, Object, Property) with
  2219. * custom logic if you need to deal with buffered fields.
  2220. *
  2221. * @see #getPropertyValue(Object, Object, Property)
  2222. *
  2223. * @param component
  2224. * component that should be unregistered.
  2225. */
  2226. protected void unregisterComponent(Component component) {
  2227. getLogger().log(Level.FINEST, "Unregistered {0}: {1}", new Object[] {
  2228. component.getClass().getSimpleName(), component.getCaption() });
  2229. component.setParent(null);
  2230. /*
  2231. * Also remove property data sources to unregister listeners keeping the
  2232. * fields in memory.
  2233. */
  2234. if (component instanceof Field) {
  2235. Field<?> field = (Field<?>) component;
  2236. Property<?> associatedProperty = associatedProperties
  2237. .remove(component);
  2238. if (associatedProperty != null
  2239. && field.getPropertyDataSource() == associatedProperty) {
  2240. // Remove the property data source only if it's the one we
  2241. // added in getPropertyValue
  2242. field.setPropertyDataSource(null);
  2243. }
  2244. }
  2245. }
  2246. /**
  2247. * Sets the row header mode.
  2248. * <p>
  2249. * The mode can be one of the following ones:
  2250. * <ul>
  2251. * <li>{@link #ROW_HEADER_MODE_HIDDEN}: The row captions are hidden.</li>
  2252. * <li>{@link #ROW_HEADER_MODE_ID}: Items Id-objects <code>toString()</code>
  2253. * is used as row caption.
  2254. * <li>{@link #ROW_HEADER_MODE_ITEM}: Item-objects <code>toString()</code>
  2255. * is used as row caption.
  2256. * <li>{@link #ROW_HEADER_MODE_PROPERTY}: Property set with
  2257. * {@link #setItemCaptionPropertyId(Object)} is used as row header.
  2258. * <li>{@link #ROW_HEADER_MODE_EXPLICIT_DEFAULTS_ID}: Items Id-objects
  2259. * <code>toString()</code> is used as row header. If caption is explicitly
  2260. * specified, it overrides the id-caption.
  2261. * <li>{@link #ROW_HEADER_MODE_EXPLICIT}: The row headers must be explicitly
  2262. * specified.</li>
  2263. * <li>{@link #ROW_HEADER_MODE_INDEX}: The index of the item is used as row
  2264. * caption. The index mode can only be used with the containers implementing
  2265. * <code>Container.Indexed</code> interface.</li>
  2266. * </ul>
  2267. * The default value is {@link #ROW_HEADER_MODE_HIDDEN}
  2268. * </p>
  2269. *
  2270. * @param mode
  2271. * the One of the modes listed above.
  2272. */
  2273. public void setRowHeaderMode(RowHeaderMode mode) {
  2274. if (mode != null) {
  2275. rowHeaderMode = mode;
  2276. if (mode != RowHeaderMode.HIDDEN) {
  2277. setItemCaptionMode(mode.getItemCaptionMode());
  2278. }
  2279. // Assures the visual refresh. No need to reset the page buffer
  2280. // before
  2281. // as the content has not changed, only the alignments.
  2282. refreshRenderedCells();
  2283. }
  2284. }
  2285. /**
  2286. * Gets the row header mode.
  2287. *
  2288. * @return the Row header mode.
  2289. * @see #setRowHeaderMode
  2290. */
  2291. public RowHeaderMode getRowHeaderMode() {
  2292. return rowHeaderMode;
  2293. }
  2294. /**
  2295. * Adds the new row to table and fill the visible cells (except generated
  2296. * columns) with given values.
  2297. *
  2298. * @param cells
  2299. * the Object array that is used for filling the visible cells
  2300. * new row. The types must be settable to visible column property
  2301. * types.
  2302. * @param itemId
  2303. * the Id the new row. If null, a new id is automatically
  2304. * assigned. If given, the table cannot already have a item with
  2305. * given id.
  2306. * @return Returns item id for the new row. Returns null if operation fails.
  2307. */
  2308. public Object addItem(Object[] cells, Object itemId)
  2309. throws UnsupportedOperationException {
  2310. // remove generated columns from the list of columns being assigned
  2311. final LinkedList<Object> availableCols = new LinkedList<Object>();
  2312. for (Object id : visibleColumns) {
  2313. if (!columnGenerators.containsKey(id)) {
  2314. availableCols.add(id);
  2315. }
  2316. }
  2317. // Checks that a correct number of cells are given
  2318. if (cells.length != availableCols.size()) {
  2319. return null;
  2320. }
  2321. // Creates new item
  2322. Item item;
  2323. if (itemId == null) {
  2324. itemId = items.addItem();
  2325. if (itemId == null) {
  2326. return null;
  2327. }
  2328. item = items.getItem(itemId);
  2329. } else {
  2330. item = items.addItem(itemId);
  2331. }
  2332. if (item == null) {
  2333. return null;
  2334. }
  2335. // Fills the item properties
  2336. for (int i = 0; i < availableCols.size(); i++) {
  2337. item.getItemProperty(availableCols.get(i)).setValue(cells[i]);
  2338. }
  2339. if (!(items instanceof Container.ItemSetChangeNotifier)) {
  2340. refreshRowCache();
  2341. }
  2342. return itemId;
  2343. }
  2344. /**
  2345. * Discards and recreates the internal row cache. Call this if you make
  2346. * changes that affect the rows but the information about the changes are
  2347. * not automatically propagated to the Table.
  2348. * <p>
  2349. * Do not call this e.g. if you have updated the data model through a
  2350. * Property. These types of changes are automatically propagated to the
  2351. * Table.
  2352. * <p>
  2353. * A typical case when this is needed is if you update a generator (e.g.
  2354. * CellStyleGenerator) and want to ensure that the rows are redrawn with new
  2355. * styles.
  2356. * <p>
  2357. * <i>Note that calling this method is not cheap so avoid calling it
  2358. * unnecessarily.</i>
  2359. *
  2360. * @since 6.7.2
  2361. */
  2362. public void refreshRowCache() {
  2363. resetPageBuffer();
  2364. refreshRenderedCells();
  2365. }
  2366. /**
  2367. * Sets the Container that serves as the data source of the viewer. As a
  2368. * side-effect the table's selection value is set to null as the old
  2369. * selection might not exist in new Container.<br>
  2370. * <br>
  2371. * All rows and columns are generated as visible using this method. If the
  2372. * new container contains properties that are not meant to be shown you
  2373. * should use {@link Table#setContainerDataSource(Container, Collection)}
  2374. * instead, especially if the table is editable.
  2375. * <p>
  2376. * Keeps propertyValueConverters if the corresponding id exists in the new
  2377. * data source and is of a compatible type.
  2378. * </p>
  2379. *
  2380. * @param newDataSource
  2381. * the new data source.
  2382. */
  2383. @Override
  2384. public void setContainerDataSource(Container newDataSource) {
  2385. if (newDataSource == null) {
  2386. newDataSource = new IndexedContainer();
  2387. }
  2388. Collection<Object> generated;
  2389. if (columnGenerators != null) {
  2390. generated = columnGenerators.keySet();
  2391. } else {
  2392. generated = Collections.emptyList();
  2393. }
  2394. List<Object> visibleIds = new ArrayList<Object>();
  2395. if (generated.isEmpty()) {
  2396. visibleIds.addAll(newDataSource.getContainerPropertyIds());
  2397. } else {
  2398. for (Object id : newDataSource.getContainerPropertyIds()) {
  2399. // don't add duplicates
  2400. if (!generated.contains(id)) {
  2401. visibleIds.add(id);
  2402. }
  2403. }
  2404. // generated columns to the end
  2405. visibleIds.addAll(generated);
  2406. }
  2407. setContainerDataSource(newDataSource, visibleIds);
  2408. }
  2409. /**
  2410. * Sets the container data source and the columns that will be visible.
  2411. * Columns are shown in the collection's iteration order.
  2412. * <p>
  2413. * Keeps propertyValueConverters if the corresponding id exists in the new
  2414. * data source and is of a compatible type.
  2415. * </p>
  2416. *
  2417. * @see Table#setContainerDataSource(Container)
  2418. * @see Table#setVisibleColumns(Object[])
  2419. * @see Table#setConverter(Object, Converter<String, ?>)
  2420. *
  2421. * @param newDataSource
  2422. * the new data source.
  2423. * @param visibleIds
  2424. * IDs of the visible columns
  2425. */
  2426. public void setContainerDataSource(Container newDataSource,
  2427. Collection<?> visibleIds) {
  2428. disableContentRefreshing();
  2429. if (newDataSource == null) {
  2430. newDataSource = new IndexedContainer();
  2431. }
  2432. if (visibleIds == null) {
  2433. visibleIds = new ArrayList<Object>();
  2434. }
  2435. // Retain propertyValueConverters if their corresponding ids are
  2436. // properties of the new
  2437. // data source and are of a compatible type
  2438. if (propertyValueConverters != null) {
  2439. Collection<?> newPropertyIds = newDataSource
  2440. .getContainerPropertyIds();
  2441. LinkedList<Object> retainableValueConverters = new LinkedList<Object>();
  2442. for (Object propertyId : newPropertyIds) {
  2443. Converter<String, ?> converter = getConverter(propertyId);
  2444. if (converter != null) {
  2445. if (typeIsCompatible(converter.getModelType(),
  2446. newDataSource.getType(propertyId))) {
  2447. retainableValueConverters.add(propertyId);
  2448. }
  2449. }
  2450. }
  2451. propertyValueConverters.keySet()
  2452. .retainAll(retainableValueConverters);
  2453. }
  2454. // Assures that the data source is ordered by making unordered
  2455. // containers ordered by wrapping them
  2456. if (newDataSource instanceof Container.Ordered) {
  2457. super.setContainerDataSource(newDataSource);
  2458. } else {
  2459. super.setContainerDataSource(
  2460. new ContainerOrderedWrapper(newDataSource));
  2461. }
  2462. // Resets page position
  2463. currentPageFirstItemId = null;
  2464. currentPageFirstItemIndex = 0;
  2465. // Resets column properties
  2466. if (collapsedColumns != null) {
  2467. collapsedColumns.clear();
  2468. }
  2469. // don't add the same id twice
  2470. Collection<Object> col = new LinkedList<Object>();
  2471. for (Object id : visibleIds) {
  2472. if (!col.contains(id)) {
  2473. col.add(id);
  2474. }
  2475. }
  2476. setVisibleColumns(col.toArray());
  2477. // Assure visual refresh
  2478. resetPageBuffer();
  2479. enableContentRefreshing(true);
  2480. }
  2481. /**
  2482. * Checks if class b can be safely assigned to class a.
  2483. *
  2484. * @param a
  2485. * @param b
  2486. * @return
  2487. */
  2488. private boolean typeIsCompatible(Class<?> a, Class<?> b) {
  2489. // TODO Implement this check properly
  2490. // Basically we need to do a a.isAssignableFrom(b)
  2491. // with special considerations for primitive types.
  2492. return true;
  2493. }
  2494. /**
  2495. * Gets items ids from a range of key values
  2496. *
  2497. * @param itemId
  2498. * The start key
  2499. * @param length
  2500. * amount of items to be retrieved
  2501. * @return
  2502. */
  2503. private LinkedHashSet<Object> getItemIdsInRange(Object itemId,
  2504. final int length) {
  2505. LinkedHashSet<Object> ids = new LinkedHashSet<Object>();
  2506. for (int i = 0; i < length; i++) {
  2507. // should not be null unless client-server are out of sync
  2508. assert itemId != null;
  2509. ids.add(itemId);
  2510. itemId = nextItemId(itemId);
  2511. }
  2512. return ids;
  2513. }
  2514. /**
  2515. * Handles selection if selection is a multiselection
  2516. *
  2517. * @param variables
  2518. * The variables
  2519. */
  2520. private void handleSelectedItems(Map<String, Object> variables) {
  2521. final String[] ka = (String[]) variables.get("selected");
  2522. final String[] ranges = (String[]) variables.get("selectedRanges");
  2523. Set<Object> renderedButNotSelectedItemIds = getCurrentlyRenderedItemIds();
  2524. @SuppressWarnings("unchecked")
  2525. HashSet<Object> newValue = new LinkedHashSet<Object>(
  2526. (Collection<Object>) getValue());
  2527. if (variables.containsKey("clearSelections")) {
  2528. // the client side has instructed to swipe all previous selections
  2529. newValue.clear();
  2530. }
  2531. /*
  2532. * Then add (possibly some of them back) rows that are currently
  2533. * selected on the client side (the ones that the client side is aware
  2534. * of).
  2535. */
  2536. for (String k : ka) {
  2537. // key to id
  2538. final Object id = itemIdMapper.get(k);
  2539. if (!isNullSelectionAllowed()
  2540. && (id == null || id == getNullSelectionItemId())) {
  2541. // skip empty selection if nullselection is not allowed
  2542. markAsDirty();
  2543. } else if (id != null && containsId(id)) {
  2544. newValue.add(id);
  2545. renderedButNotSelectedItemIds.remove(id);
  2546. }
  2547. }
  2548. /* Add range items aka shift clicked multiselection areas */
  2549. if (ranges != null) {
  2550. for (String range : ranges) {
  2551. String[] split = range.split("-");
  2552. Object startItemId = itemIdMapper.get(split[0]);
  2553. int length = Integer.valueOf(split[1]);
  2554. LinkedHashSet<Object> itemIdsInRange = getItemIdsInRange(
  2555. startItemId, length);
  2556. newValue.addAll(itemIdsInRange);
  2557. renderedButNotSelectedItemIds.removeAll(itemIdsInRange);
  2558. }
  2559. }
  2560. /*
  2561. * finally clear all currently rendered rows (the ones that the client
  2562. * side counterpart is aware of) that the client didn't send as selected
  2563. */
  2564. newValue.removeAll(renderedButNotSelectedItemIds);
  2565. if (!isNullSelectionAllowed() && newValue.isEmpty()) {
  2566. // empty selection not allowed, keep old value
  2567. markAsDirty();
  2568. return;
  2569. }
  2570. setValue(newValue, true);
  2571. }
  2572. private Set<Object> getCurrentlyRenderedItemIds() {
  2573. HashSet<Object> ids = new HashSet<Object>();
  2574. if (pageBuffer != null) {
  2575. for (Object id : pageBuffer[CELL_ITEMID]) {
  2576. ids.add(id);
  2577. }
  2578. }
  2579. return ids;
  2580. }
  2581. /* Component basics */
  2582. /**
  2583. * Invoked when the value of a variable has changed.
  2584. *
  2585. * @see Select#changeVariables(java.lang.Object, java.util.Map)
  2586. */
  2587. @Override
  2588. public void changeVariables(Object source, Map<String, Object> variables) {
  2589. boolean clientNeedsContentRefresh = false;
  2590. handleClickEvent(variables);
  2591. handleColumnResizeEvent(variables);
  2592. handleColumnWidthUpdates(variables);
  2593. disableContentRefreshing();
  2594. if (!isSelectable() && variables.containsKey("selected")) {
  2595. // Not-selectable is a special case, AbstractSelect does not support
  2596. // TODO could be optimized.
  2597. variables = new HashMap<String, Object>(variables);
  2598. variables.remove("selected");
  2599. } else if (
  2600. /*
  2601. * The AbstractSelect cannot handle the multiselection properly, instead
  2602. * we handle it ourself
  2603. */
  2604. isSelectable() && isMultiSelect() && variables.containsKey("selected")
  2605. && multiSelectMode == MultiSelectMode.DEFAULT) {
  2606. handleSelectedItems(variables);
  2607. variables = new HashMap<String, Object>(variables);
  2608. variables.remove("selected");
  2609. }
  2610. super.changeVariables(source, variables);
  2611. // Client might update the pagelength if Table height is fixed
  2612. if (variables.containsKey("pagelength")) {
  2613. // Sets pageLength directly to avoid repaint that setter causes
  2614. pageLength = (Integer) variables.get("pagelength");
  2615. }
  2616. // Page start index
  2617. if (variables.containsKey("firstvisible")) {
  2618. final Integer value = (Integer) variables.get("firstvisible");
  2619. if (value != null) {
  2620. setCurrentPageFirstItemIndex(value.intValue(), false);
  2621. }
  2622. }
  2623. // Sets requested firstrow and rows for the next paint
  2624. if (variables.containsKey("reqfirstrow")
  2625. || variables.containsKey("reqrows")) {
  2626. try {
  2627. firstToBeRenderedInClient = ((Integer) variables
  2628. .get("firstToBeRendered")).intValue();
  2629. lastToBeRenderedInClient = ((Integer) variables
  2630. .get("lastToBeRendered")).intValue();
  2631. } catch (Exception e) {
  2632. // FIXME: Handle exception
  2633. getLogger().log(Level.FINER,
  2634. "Could not parse the first and/or last rows.", e);
  2635. }
  2636. // respect suggested rows only if table is not otherwise updated
  2637. // (row caches emptied by other event)
  2638. if (!containerChangeToBeRendered) {
  2639. Integer value = (Integer) variables.get("reqfirstrow");
  2640. if (value != null) {
  2641. reqFirstRowToPaint = value.intValue();
  2642. }
  2643. value = (Integer) variables.get("reqrows");
  2644. if (value != null) {
  2645. reqRowsToPaint = value.intValue();
  2646. int size = size();
  2647. // sanity check
  2648. if (reqFirstRowToPaint >= size) {
  2649. reqFirstRowToPaint = size;
  2650. }
  2651. if (reqFirstRowToPaint + reqRowsToPaint > size) {
  2652. reqRowsToPaint = size - reqFirstRowToPaint;
  2653. }
  2654. }
  2655. }
  2656. if (getLogger().isLoggable(Level.FINEST)) {
  2657. getLogger().log(Level.FINEST, "Client wants rows {0}-{1}",
  2658. new Object[] { reqFirstRowToPaint,
  2659. (reqFirstRowToPaint + reqRowsToPaint - 1) });
  2660. }
  2661. clientNeedsContentRefresh = true;
  2662. }
  2663. if (isSortEnabled()) {
  2664. // Sorting
  2665. boolean doSort = false;
  2666. if (variables.containsKey("sortcolumn")) {
  2667. final String colId = (String) variables.get("sortcolumn");
  2668. if (colId != null && !"".equals(colId)
  2669. && !"null".equals(colId)) {
  2670. final Object id = columnIdMap.get(colId);
  2671. setSortContainerPropertyId(id, false);
  2672. doSort = true;
  2673. }
  2674. }
  2675. if (variables.containsKey("sortascending")) {
  2676. final boolean state = ((Boolean) variables.get("sortascending"))
  2677. .booleanValue();
  2678. if (state != sortAscending) {
  2679. setSortAscending(state, false);
  2680. doSort = true;
  2681. }
  2682. }
  2683. if (doSort) {
  2684. this.sort();
  2685. resetPageBuffer();
  2686. }
  2687. }
  2688. // Dynamic column hide/show and order
  2689. // Update visible columns
  2690. if (isColumnCollapsingAllowed()) {
  2691. if (variables.containsKey("collapsedcolumns")) {
  2692. try {
  2693. final Object[] ids = (Object[]) variables
  2694. .get("collapsedcolumns");
  2695. Set<Object> idSet = new HashSet<Object>();
  2696. for (Object id : ids) {
  2697. idSet.add(columnIdMap.get(id.toString()));
  2698. }
  2699. for (final Object propertyId : visibleColumns) {
  2700. if (isColumnCollapsed(propertyId)) {
  2701. if (!idSet.contains(propertyId)) {
  2702. setColumnCollapsed(propertyId, false);
  2703. }
  2704. } else if (idSet.contains(propertyId)) {
  2705. setColumnCollapsed(propertyId, true);
  2706. }
  2707. }
  2708. } catch (final Exception e) {
  2709. // FIXME: Handle exception
  2710. getLogger().log(Level.FINER,
  2711. "Could not determine column collapsing state", e);
  2712. }
  2713. clientNeedsContentRefresh = true;
  2714. }
  2715. }
  2716. if (isColumnReorderingAllowed()) {
  2717. if (variables.containsKey("columnorder")) {
  2718. try {
  2719. final Object[] ids = (Object[]) variables
  2720. .get("columnorder");
  2721. // need a real Object[], ids can be a String[]
  2722. final Object[] idsTemp = new Object[ids.length];
  2723. for (int i = 0; i < ids.length; i++) {
  2724. idsTemp[i] = columnIdMap.get(ids[i].toString());
  2725. }
  2726. setColumnOrder(idsTemp);
  2727. if (hasListeners(ColumnReorderEvent.class)) {
  2728. fireEvent(new ColumnReorderEvent(this));
  2729. }
  2730. } catch (final Exception e) {
  2731. // FIXME: Handle exception
  2732. getLogger().log(Level.FINER,
  2733. "Could not determine column reordering state", e);
  2734. }
  2735. clientNeedsContentRefresh = true;
  2736. }
  2737. }
  2738. enableContentRefreshing(clientNeedsContentRefresh);
  2739. // Actions
  2740. if (variables.containsKey("action")) {
  2741. final StringTokenizer st = new StringTokenizer(
  2742. (String) variables.get("action"), ",");
  2743. if (st.countTokens() == 2) {
  2744. final Object itemId = itemIdMapper.get(st.nextToken());
  2745. final Action action = actionMapper.get(st.nextToken());
  2746. if (action != null && (itemId == null || containsId(itemId))
  2747. && actionHandlers != null) {
  2748. for (Handler ah : actionHandlers) {
  2749. ah.handleAction(action, this, itemId);
  2750. }
  2751. }
  2752. }
  2753. }
  2754. }
  2755. /**
  2756. * Handles click event
  2757. *
  2758. * @param variables
  2759. */
  2760. private void handleClickEvent(Map<String, Object> variables) {
  2761. // Item click event
  2762. if (variables.containsKey("clickEvent")) {
  2763. String key = (String) variables.get("clickedKey");
  2764. Object itemId = itemIdMapper.get(key);
  2765. Object propertyId = null;
  2766. String colkey = (String) variables.get("clickedColKey");
  2767. // click is not necessary on a property
  2768. if (colkey != null) {
  2769. propertyId = columnIdMap.get(colkey);
  2770. }
  2771. MouseEventDetails evt = MouseEventDetails
  2772. .deSerialize((String) variables.get("clickEvent"));
  2773. Item item = getItem(itemId);
  2774. if (item != null) {
  2775. fireEvent(new ItemClickEvent(this, item, itemId, propertyId,
  2776. evt));
  2777. }
  2778. } else if (
  2779. // Header click event
  2780. variables.containsKey("headerClickEvent")) {
  2781. MouseEventDetails details = MouseEventDetails
  2782. .deSerialize((String) variables.get("headerClickEvent"));
  2783. Object cid = variables.get("headerClickCID");
  2784. Object propertyId = null;
  2785. if (cid != null) {
  2786. propertyId = columnIdMap.get(cid.toString());
  2787. }
  2788. fireEvent(new HeaderClickEvent(this, propertyId, details));
  2789. } else if (
  2790. // Footer click event
  2791. variables.containsKey("footerClickEvent")) {
  2792. MouseEventDetails details = MouseEventDetails
  2793. .deSerialize((String) variables.get("footerClickEvent"));
  2794. Object cid = variables.get("footerClickCID");
  2795. Object propertyId = null;
  2796. if (cid != null) {
  2797. propertyId = columnIdMap.get(cid.toString());
  2798. }
  2799. fireEvent(new FooterClickEvent(this, propertyId, details));
  2800. }
  2801. }
  2802. /**
  2803. * Handles the column resize event sent by the client.
  2804. *
  2805. * @param variables
  2806. */
  2807. private void handleColumnResizeEvent(Map<String, Object> variables) {
  2808. if (variables.containsKey("columnResizeEventColumn")) {
  2809. Object cid = variables.get("columnResizeEventColumn");
  2810. Object propertyId = null;
  2811. if (cid != null) {
  2812. propertyId = columnIdMap.get(cid.toString());
  2813. Object prev = variables.get("columnResizeEventPrev");
  2814. int previousWidth = -1;
  2815. if (prev != null) {
  2816. previousWidth = Integer.valueOf(prev.toString());
  2817. }
  2818. Object curr = variables.get("columnResizeEventCurr");
  2819. int currentWidth = -1;
  2820. if (curr != null) {
  2821. currentWidth = Integer.valueOf(curr.toString());
  2822. }
  2823. fireColumnResizeEvent(propertyId, previousWidth, currentWidth);
  2824. }
  2825. }
  2826. }
  2827. private void fireColumnCollapseEvent(Object propertyId) {
  2828. fireEvent(new ColumnCollapseEvent(this, propertyId));
  2829. }
  2830. private void fireColumnResizeEvent(Object propertyId, int previousWidth,
  2831. int currentWidth) {
  2832. /*
  2833. * Update the sizes on the server side. If a column previously had a
  2834. * expand ratio and the user resized the column then the expand ratio
  2835. * will be turned into a static pixel size.
  2836. */
  2837. setColumnWidth(propertyId, currentWidth);
  2838. fireEvent(new ColumnResizeEvent(this, propertyId, previousWidth,
  2839. currentWidth));
  2840. }
  2841. private void handleColumnWidthUpdates(Map<String, Object> variables) {
  2842. if (variables.containsKey("columnWidthUpdates")) {
  2843. String[] events = (String[]) variables.get("columnWidthUpdates");
  2844. for (String str : events) {
  2845. String[] eventDetails = str.split(":");
  2846. Object propertyId = columnIdMap.get(eventDetails[0]);
  2847. if (propertyId == null) {
  2848. propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
  2849. }
  2850. int width = Integer.valueOf(eventDetails[1]);
  2851. setColumnWidth(propertyId, width);
  2852. }
  2853. }
  2854. }
  2855. /**
  2856. * Go to mode where content updates are not done. This is due we want to
  2857. * bypass expensive content for some reason (like when we know we may have
  2858. * other content changes on their way).
  2859. *
  2860. * @return true if content refresh flag was enabled prior this call
  2861. */
  2862. protected boolean disableContentRefreshing() {
  2863. boolean wasDisabled = isContentRefreshesEnabled;
  2864. isContentRefreshesEnabled = false;
  2865. return wasDisabled;
  2866. }
  2867. /**
  2868. * Go to mode where content content refreshing has effect.
  2869. *
  2870. * @param refreshContent
  2871. * true if content refresh needs to be done
  2872. */
  2873. protected void enableContentRefreshing(boolean refreshContent) {
  2874. isContentRefreshesEnabled = true;
  2875. if (refreshContent) {
  2876. refreshRenderedCells();
  2877. // Ensure that client gets a response
  2878. markAsDirty();
  2879. }
  2880. }
  2881. @Override
  2882. public void beforeClientResponse(boolean initial) {
  2883. super.beforeClientResponse(initial);
  2884. // Ensure pageBuffer is filled before sending the response to avoid
  2885. // calls to markAsDirty during paint
  2886. getVisibleCells();
  2887. }
  2888. @Override
  2889. public void paintContent(PaintTarget target) throws PaintException {
  2890. isBeingPainted = true;
  2891. try {
  2892. doPaintContent(target);
  2893. } finally {
  2894. isBeingPainted = false;
  2895. }
  2896. }
  2897. private void doPaintContent(PaintTarget target) throws PaintException {
  2898. /*
  2899. * Body actions - Actions which has the target null and can be invoked
  2900. * by right clicking on the table body.
  2901. */
  2902. final Set<Action> actionSet = findAndPaintBodyActions(target);
  2903. final Object[][] cells = getVisibleCells();
  2904. int rows = findNumRowsToPaint(target, cells);
  2905. int total = size();
  2906. if (shouldHideNullSelectionItem()) {
  2907. total--;
  2908. rows--;
  2909. }
  2910. // Table attributes
  2911. paintTableAttributes(target, rows, total);
  2912. paintVisibleColumnOrder(target);
  2913. // Rows
  2914. if (isPartialRowUpdate() && painted && !target.isFullRepaint()) {
  2915. paintPartialRowUpdate(target, actionSet);
  2916. } else if (target.isFullRepaint() || isRowCacheInvalidated()) {
  2917. paintRows(target, cells, actionSet);
  2918. setRowCacheInvalidated(false);
  2919. }
  2920. /*
  2921. * Send the page buffer indexes to ensure that the client side stays in
  2922. * sync. Otherwise we _might_ have the situation where the client side
  2923. * discards too few or too many rows, causing out of sync issues.
  2924. */
  2925. int pageBufferLastIndex = pageBufferFirstIndex
  2926. + pageBuffer[CELL_ITEMID].length - 1;
  2927. target.addAttribute(TableConstants.ATTRIBUTE_PAGEBUFFER_FIRST,
  2928. pageBufferFirstIndex);
  2929. target.addAttribute(TableConstants.ATTRIBUTE_PAGEBUFFER_LAST,
  2930. pageBufferLastIndex);
  2931. paintSorting(target);
  2932. resetVariablesAndPageBuffer(target);
  2933. // Actions
  2934. paintActions(target, actionSet);
  2935. paintColumnOrder(target);
  2936. // Available columns
  2937. paintAvailableColumns(target);
  2938. paintVisibleColumns(target);
  2939. if (keyMapperReset) {
  2940. keyMapperReset = false;
  2941. target.addAttribute(TableConstants.ATTRIBUTE_KEY_MAPPER_RESET,
  2942. true);
  2943. }
  2944. if (dropHandler != null) {
  2945. dropHandler.getAcceptCriterion().paint(target);
  2946. }
  2947. painted = true;
  2948. }
  2949. private void setRowCacheInvalidated(boolean invalidated) {
  2950. rowCacheInvalidated = invalidated;
  2951. }
  2952. protected boolean isRowCacheInvalidated() {
  2953. return rowCacheInvalidated;
  2954. }
  2955. private void paintPartialRowUpdate(PaintTarget target,
  2956. Set<Action> actionSet) throws PaintException {
  2957. paintPartialRowUpdates(target, actionSet);
  2958. paintPartialRowAdditions(target, actionSet);
  2959. }
  2960. private void paintPartialRowUpdates(PaintTarget target,
  2961. Set<Action> actionSet) throws PaintException {
  2962. final boolean[] iscomponent = findCellsWithComponents();
  2963. int firstIx = getFirstUpdatedItemIndex();
  2964. int count = getUpdatedRowCount();
  2965. target.startTag("urows");
  2966. target.addAttribute("firsturowix", firstIx);
  2967. target.addAttribute("numurows", count);
  2968. // Partial row updates bypass the normal caching mechanism.
  2969. Object[][] cells = getVisibleCellsUpdateCacheRows(firstIx, count);
  2970. for (int indexInRowbuffer = 0; indexInRowbuffer < count; indexInRowbuffer++) {
  2971. final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
  2972. if (shouldHideNullSelectionItem()) {
  2973. // Remove null selection item if null selection is not allowed
  2974. continue;
  2975. }
  2976. paintRow(target, cells, isEditable(), actionSet, iscomponent,
  2977. indexInRowbuffer, itemId);
  2978. }
  2979. target.endTag("urows");
  2980. maybeThrowCacheUpdateExceptions();
  2981. }
  2982. private void paintPartialRowAdditions(PaintTarget target,
  2983. Set<Action> actionSet) throws PaintException {
  2984. final boolean[] iscomponent = findCellsWithComponents();
  2985. int firstIx = getFirstAddedItemIndex();
  2986. int count = getAddedRowCount();
  2987. target.startTag("prows");
  2988. if (!shouldHideAddedRows()) {
  2989. getLogger().log(Level.FINEST,
  2990. "Paint rows for add. Index: {0}, count: {1}.",
  2991. new Object[] { firstIx, count });
  2992. // Partial row additions bypass the normal caching mechanism.
  2993. Object[][] cells = getVisibleCellsInsertIntoCache(firstIx, count);
  2994. if (cells[0].length < count) {
  2995. // delete the rows below, since they will fall beyond the cache
  2996. // page.
  2997. target.addAttribute("delbelow", true);
  2998. count = cells[0].length;
  2999. }
  3000. for (int indexInRowbuffer = 0; indexInRowbuffer < count; indexInRowbuffer++) {
  3001. final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
  3002. if (shouldHideNullSelectionItem()) {
  3003. // Remove null selection item if null selection is not
  3004. // allowed
  3005. continue;
  3006. }
  3007. paintRow(target, cells, isEditable(), actionSet, iscomponent,
  3008. indexInRowbuffer, itemId);
  3009. }
  3010. } else {
  3011. getLogger().log(Level.FINEST,
  3012. "Paint rows for remove. Index: {0}, count: {1}.",
  3013. new Object[] { firstIx, count });
  3014. removeRowsFromCacheAndFillBottom(firstIx, count);
  3015. target.addAttribute("hide", true);
  3016. }
  3017. target.addAttribute("firstprowix", firstIx);
  3018. target.addAttribute("numprows", count);
  3019. target.endTag("prows");
  3020. maybeThrowCacheUpdateExceptions();
  3021. }
  3022. /**
  3023. * Subclass and override this to enable partial row updates and additions,
  3024. * which bypass the normal caching mechanism. This is useful for e.g.
  3025. * TreeTable.
  3026. *
  3027. * @return true if this update is a partial row update, false if not. For
  3028. * plain Table it is always false.
  3029. */
  3030. protected boolean isPartialRowUpdate() {
  3031. return false;
  3032. }
  3033. /**
  3034. * Subclass and override this to enable partial row additions, bypassing the
  3035. * normal caching mechanism. This is useful for e.g. TreeTable, where
  3036. * expanding a node should only fetch and add the items inside of that node.
  3037. *
  3038. * @return The index of the first added item. For plain Table it is always
  3039. * 0.
  3040. */
  3041. protected int getFirstAddedItemIndex() {
  3042. return 0;
  3043. }
  3044. /**
  3045. * Subclass and override this to enable partial row additions, bypassing the
  3046. * normal caching mechanism. This is useful for e.g. TreeTable, where
  3047. * expanding a node should only fetch and add the items inside of that node.
  3048. *
  3049. * @return the number of rows to be added, starting at the index returned by
  3050. * {@link #getFirstAddedItemIndex()}. For plain Table it is always
  3051. * 0.
  3052. */
  3053. protected int getAddedRowCount() {
  3054. return 0;
  3055. }
  3056. /**
  3057. * Subclass and override this to enable removing of rows, bypassing the
  3058. * normal caching and lazy loading mechanism. This is useful for e.g.
  3059. * TreeTable, when you need to hide certain rows as a node is collapsed.
  3060. *
  3061. * This should return true if the rows pointed to by
  3062. * {@link #getFirstAddedItemIndex()} and {@link #getAddedRowCount()} should
  3063. * be hidden instead of added.
  3064. *
  3065. * @return whether the rows to add (see {@link #getFirstAddedItemIndex()}
  3066. * and {@link #getAddedRowCount()}) should be added or hidden. For
  3067. * plain Table it is always false.
  3068. */
  3069. protected boolean shouldHideAddedRows() {
  3070. return false;
  3071. }
  3072. /**
  3073. * Subclass and override this to enable partial row updates, bypassing the
  3074. * normal caching and lazy loading mechanism. This is useful for updating
  3075. * the state of certain rows, e.g. in the TreeTable the collapsed state of a
  3076. * single node is updated using this mechanism.
  3077. *
  3078. * @return the index of the first item to be updated. For plain Table it is
  3079. * always 0.
  3080. */
  3081. protected int getFirstUpdatedItemIndex() {
  3082. return 0;
  3083. }
  3084. /**
  3085. * Subclass and override this to enable partial row updates, bypassing the
  3086. * normal caching and lazy loading mechanism. This is useful for updating
  3087. * the state of certain rows, e.g. in the TreeTable the collapsed state of a
  3088. * single node is updated using this mechanism.
  3089. *
  3090. * @return the number of rows to update, starting at the index returned by
  3091. * {@link #getFirstUpdatedItemIndex()}. For plain table it is always
  3092. * 0.
  3093. */
  3094. protected int getUpdatedRowCount() {
  3095. return 0;
  3096. }
  3097. private void paintTableAttributes(PaintTarget target, int rows, int total)
  3098. throws PaintException {
  3099. paintTabIndex(target);
  3100. paintDragMode(target);
  3101. paintSelectMode(target);
  3102. paintTableChildLayoutMeasureMode(target);
  3103. if (cacheRate != CACHE_RATE_DEFAULT) {
  3104. target.addAttribute("cr", cacheRate);
  3105. }
  3106. target.addAttribute("cols", getVisibleColumns().length);
  3107. target.addAttribute("rows", rows);
  3108. target.addAttribute("firstrow",
  3109. (reqFirstRowToPaint >= 0 ? reqFirstRowToPaint
  3110. : firstToBeRenderedInClient));
  3111. target.addAttribute("totalrows", total);
  3112. if (getPageLength() != 0) {
  3113. target.addAttribute("pagelength", getPageLength());
  3114. }
  3115. if (areColumnHeadersEnabled()) {
  3116. target.addAttribute("colheaders", true);
  3117. }
  3118. if (rowHeadersAreEnabled()) {
  3119. target.addAttribute("rowheaders", true);
  3120. }
  3121. target.addAttribute("colfooters", columnFootersVisible);
  3122. // The cursors are only shown on pageable table
  3123. if (getCurrentPageFirstItemIndex() != 0 || getPageLength() > 0) {
  3124. target.addVariable(this, "firstvisible",
  3125. getCurrentPageFirstItemIndex());
  3126. target.addVariable(this, "firstvisibleonlastpage",
  3127. currentPageFirstItemIndexOnLastPage);
  3128. }
  3129. }
  3130. /**
  3131. * Resets and paints "to be painted next" variables. Also reset pageBuffer
  3132. */
  3133. private void resetVariablesAndPageBuffer(PaintTarget target)
  3134. throws PaintException {
  3135. reqFirstRowToPaint = -1;
  3136. reqRowsToPaint = -1;
  3137. containerChangeToBeRendered = false;
  3138. target.addVariable(this, "reqrows", reqRowsToPaint);
  3139. target.addVariable(this, "reqfirstrow", reqFirstRowToPaint);
  3140. }
  3141. private boolean areColumnHeadersEnabled() {
  3142. return getColumnHeaderMode() != ColumnHeaderMode.HIDDEN;
  3143. }
  3144. private void paintVisibleColumns(PaintTarget target) throws PaintException {
  3145. target.startTag("visiblecolumns");
  3146. if (rowHeadersAreEnabled()) {
  3147. target.startTag("column");
  3148. target.addAttribute("cid", ROW_HEADER_COLUMN_KEY);
  3149. paintColumnWidth(target, ROW_HEADER_FAKE_PROPERTY_ID);
  3150. paintColumnExpandRatio(target, ROW_HEADER_FAKE_PROPERTY_ID);
  3151. target.endTag("column");
  3152. }
  3153. final Collection<?> sortables = getSortableContainerPropertyIds();
  3154. for (Object colId : visibleColumns) {
  3155. if (colId != null) {
  3156. target.startTag("column");
  3157. target.addAttribute("cid", columnIdMap.key(colId));
  3158. final String head = getColumnHeader(colId);
  3159. target.addAttribute("caption", (head != null ? head : ""));
  3160. final String foot = getColumnFooter(colId);
  3161. target.addAttribute("fcaption", (foot != null ? foot : ""));
  3162. if (isColumnCollapsed(colId)) {
  3163. target.addAttribute("collapsed", true);
  3164. }
  3165. if (areColumnHeadersEnabled()) {
  3166. if (getColumnIcon(colId) != null) {
  3167. target.addAttribute("icon", getColumnIcon(colId));
  3168. }
  3169. if (sortables.contains(colId)) {
  3170. target.addAttribute("sortable", true);
  3171. }
  3172. }
  3173. if (!Align.LEFT.equals(getColumnAlignment(colId))) {
  3174. target.addAttribute("align",
  3175. getColumnAlignment(colId).toString());
  3176. }
  3177. paintColumnWidth(target, colId);
  3178. paintColumnExpandRatio(target, colId);
  3179. target.endTag("column");
  3180. }
  3181. }
  3182. target.endTag("visiblecolumns");
  3183. }
  3184. private void paintAvailableColumns(PaintTarget target)
  3185. throws PaintException {
  3186. if (columnCollapsingAllowed) {
  3187. final HashSet<Object> collapsedCols = new HashSet<Object>();
  3188. for (Object colId : visibleColumns) {
  3189. if (isColumnCollapsed(colId)) {
  3190. collapsedCols.add(colId);
  3191. }
  3192. }
  3193. final String[] collapsedKeys = new String[collapsedCols.size()];
  3194. int nextColumn = 0;
  3195. for (Object colId : visibleColumns) {
  3196. if (isColumnCollapsed(colId)) {
  3197. collapsedKeys[nextColumn++] = columnIdMap.key(colId);
  3198. }
  3199. }
  3200. target.addVariable(this, "collapsedcolumns", collapsedKeys);
  3201. final String[] noncollapsibleKeys = new String[noncollapsibleColumns
  3202. .size()];
  3203. nextColumn = 0;
  3204. for (Object colId : noncollapsibleColumns) {
  3205. noncollapsibleKeys[nextColumn++] = columnIdMap.key(colId);
  3206. }
  3207. target.addVariable(this, "noncollapsiblecolumns",
  3208. noncollapsibleKeys);
  3209. }
  3210. }
  3211. private void paintActions(PaintTarget target, final Set<Action> actionSet)
  3212. throws PaintException {
  3213. if (!actionSet.isEmpty()) {
  3214. target.addVariable(this, "action", "");
  3215. target.startTag("actions");
  3216. for (Action a : actionSet) {
  3217. target.startTag("action");
  3218. if (a.getCaption() != null) {
  3219. target.addAttribute("caption", a.getCaption());
  3220. }
  3221. if (a.getIcon() != null) {
  3222. target.addAttribute("icon", a.getIcon());
  3223. }
  3224. target.addAttribute("key", actionMapper.key(a));
  3225. target.endTag("action");
  3226. }
  3227. target.endTag("actions");
  3228. }
  3229. }
  3230. private void paintColumnOrder(PaintTarget target) throws PaintException {
  3231. if (columnReorderingAllowed) {
  3232. final String[] colorder = new String[visibleColumns.size()];
  3233. int i = 0;
  3234. for (Object colId : visibleColumns) {
  3235. colorder[i++] = columnIdMap.key(colId);
  3236. }
  3237. target.addVariable(this, "columnorder", colorder);
  3238. }
  3239. }
  3240. private void paintSorting(PaintTarget target) throws PaintException {
  3241. // Sorting
  3242. if (getContainerDataSource() instanceof Container.Sortable) {
  3243. target.addVariable(this, "sortcolumn",
  3244. columnIdMap.key(sortContainerPropertyId));
  3245. target.addVariable(this, "sortascending", sortAscending);
  3246. }
  3247. }
  3248. private void paintRows(PaintTarget target, final Object[][] cells,
  3249. final Set<Action> actionSet) throws PaintException {
  3250. final boolean[] iscomponent = findCellsWithComponents();
  3251. target.startTag("rows");
  3252. // cells array contains all that are supposed to be visible on client,
  3253. // but we'll start from the one requested by client
  3254. int start = 0;
  3255. if (reqFirstRowToPaint != -1 && firstToBeRenderedInClient != -1) {
  3256. start = reqFirstRowToPaint - firstToBeRenderedInClient;
  3257. }
  3258. int end = cells[0].length;
  3259. if (reqRowsToPaint != -1) {
  3260. end = start + reqRowsToPaint;
  3261. }
  3262. // sanity check
  3263. if (lastToBeRenderedInClient != -1 && lastToBeRenderedInClient < end) {
  3264. end = lastToBeRenderedInClient + 1;
  3265. }
  3266. if (start > cells[CELL_ITEMID].length || start < 0) {
  3267. start = 0;
  3268. }
  3269. if (end > cells[CELL_ITEMID].length) {
  3270. end = cells[CELL_ITEMID].length;
  3271. }
  3272. for (int indexInRowbuffer = start; indexInRowbuffer < end; indexInRowbuffer++) {
  3273. final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
  3274. if (shouldHideNullSelectionItem()) {
  3275. // Remove null selection item if null selection is not allowed
  3276. continue;
  3277. }
  3278. paintRow(target, cells, isEditable(), actionSet, iscomponent,
  3279. indexInRowbuffer, itemId);
  3280. }
  3281. target.endTag("rows");
  3282. }
  3283. private boolean[] findCellsWithComponents() {
  3284. final boolean[] isComponent = new boolean[visibleColumns.size()];
  3285. int ix = 0;
  3286. for (Object columnId : visibleColumns) {
  3287. if (columnGenerators.containsKey(columnId)) {
  3288. isComponent[ix++] = true;
  3289. } else {
  3290. final Class<?> colType = getType(columnId);
  3291. isComponent[ix++] = colType != null
  3292. && Component.class.isAssignableFrom(colType);
  3293. }
  3294. }
  3295. return isComponent;
  3296. }
  3297. private void paintVisibleColumnOrder(PaintTarget target) {
  3298. // Visible column order
  3299. final List<String> visibleColOrder = new ArrayList<String>();
  3300. for (Object columnId : visibleColumns) {
  3301. if (!isColumnCollapsed(columnId)) {
  3302. visibleColOrder.add(columnIdMap.key(columnId));
  3303. }
  3304. }
  3305. target.addAttribute("vcolorder", visibleColOrder.toArray());
  3306. }
  3307. private Set<Action> findAndPaintBodyActions(PaintTarget target) {
  3308. Set<Action> actionSet = new LinkedHashSet<Action>();
  3309. if (actionHandlers != null) {
  3310. final List<String> keys = new ArrayList<String>();
  3311. for (Handler ah : actionHandlers) {
  3312. // Getting actions for the null item, which in this case means
  3313. // the body item
  3314. final Action[] actions = ah.getActions(null, this);
  3315. if (actions != null) {
  3316. for (Action action : actions) {
  3317. actionSet.add(action);
  3318. keys.add(actionMapper.key(action));
  3319. }
  3320. }
  3321. }
  3322. target.addAttribute("alb", keys.toArray());
  3323. }
  3324. return actionSet;
  3325. }
  3326. private boolean shouldHideNullSelectionItem() {
  3327. return !isNullSelectionAllowed() && getNullSelectionItemId() != null
  3328. && containsId(getNullSelectionItemId());
  3329. }
  3330. private int findNumRowsToPaint(PaintTarget target, final Object[][] cells)
  3331. throws PaintException {
  3332. int rows;
  3333. if (reqRowsToPaint >= 0) {
  3334. rows = reqRowsToPaint;
  3335. } else {
  3336. rows = cells[0].length;
  3337. if (alwaysRecalculateColumnWidths) {
  3338. // TODO experimental feature for now: tell the client to
  3339. // recalculate column widths.
  3340. // We'll only do this for paints that do not originate from
  3341. // table scroll/cache requests (i.e when reqRowsToPaint<0)
  3342. target.addAttribute("recalcWidths", true);
  3343. }
  3344. }
  3345. return rows;
  3346. }
  3347. private void paintSelectMode(PaintTarget target) throws PaintException {
  3348. if (multiSelectMode != MultiSelectMode.DEFAULT) {
  3349. target.addAttribute("multiselectmode", multiSelectMode.ordinal());
  3350. }
  3351. if (isSelectable()) {
  3352. target.addAttribute("selectmode",
  3353. (isMultiSelect() ? "multi" : "single"));
  3354. if (isMultiSelect()) {
  3355. target.addAttribute("touchdetection",
  3356. isMultiSelectTouchDetectionEnabled());
  3357. }
  3358. } else {
  3359. target.addAttribute("selectmode", "none");
  3360. }
  3361. if (!isNullSelectionAllowed()) {
  3362. target.addAttribute("nsa", false);
  3363. }
  3364. // selection support
  3365. // The select variable is only enabled if selectable
  3366. if (isSelectable()) {
  3367. target.addVariable(this, "selected", findSelectedKeys());
  3368. }
  3369. }
  3370. private String[] findSelectedKeys() {
  3371. LinkedList<String> selectedKeys = new LinkedList<String>();
  3372. if (isMultiSelect()) {
  3373. HashSet<?> sel = new HashSet<Object>((Set<?>) getValue());
  3374. Collection<?> vids = getVisibleItemIds();
  3375. for (Object id : vids) {
  3376. if (sel.contains(id)) {
  3377. selectedKeys.add(itemIdMapper.key(id));
  3378. }
  3379. }
  3380. } else {
  3381. Object value = getValue();
  3382. if (value == null) {
  3383. value = getNullSelectionItemId();
  3384. }
  3385. if (value != null) {
  3386. selectedKeys.add(itemIdMapper.key(value));
  3387. }
  3388. }
  3389. return selectedKeys.toArray(new String[selectedKeys.size()]);
  3390. }
  3391. private void paintDragMode(PaintTarget target) throws PaintException {
  3392. if (dragMode != TableDragMode.NONE) {
  3393. target.addAttribute("dragmode", dragMode.ordinal());
  3394. }
  3395. }
  3396. private void paintTabIndex(PaintTarget target) throws PaintException {
  3397. // The tab ordering number
  3398. if (getTabIndex() > 0) {
  3399. target.addAttribute("tabindex", getTabIndex());
  3400. }
  3401. }
  3402. private void paintColumnWidth(PaintTarget target, final Object columnId)
  3403. throws PaintException {
  3404. if (columnWidths.containsKey(columnId)) {
  3405. target.addAttribute("width", getColumnWidth(columnId));
  3406. }
  3407. }
  3408. private void paintColumnExpandRatio(PaintTarget target,
  3409. final Object columnId) throws PaintException {
  3410. if (columnExpandRatios.containsKey(columnId)) {
  3411. target.addAttribute("er", getColumnExpandRatio(columnId));
  3412. }
  3413. }
  3414. private void paintTableChildLayoutMeasureMode(PaintTarget target)
  3415. throws PaintException {
  3416. target.addAttribute("measurehint", getChildMeasurementHint().ordinal());
  3417. }
  3418. /**
  3419. * Checks whether row headers are visible.
  3420. *
  3421. * @return {@code false} if row headers are hidden, {@code true} otherwise
  3422. * @since 7.3.9
  3423. */
  3424. protected boolean rowHeadersAreEnabled() {
  3425. return getRowHeaderMode() != RowHeaderMode.HIDDEN;
  3426. }
  3427. private void paintRow(PaintTarget target, final Object[][] cells,
  3428. final boolean iseditable, final Set<Action> actionSet,
  3429. final boolean[] iscomponent, int indexInRowbuffer,
  3430. final Object itemId) throws PaintException {
  3431. target.startTag("tr");
  3432. paintRowAttributes(target, cells, actionSet, indexInRowbuffer, itemId);
  3433. // cells
  3434. int currentColumn = 0;
  3435. for (final Iterator<Object> it = visibleColumns.iterator(); it
  3436. .hasNext(); currentColumn++) {
  3437. final Object columnId = it.next();
  3438. if (columnId == null || isColumnCollapsed(columnId)) {
  3439. continue;
  3440. }
  3441. /*
  3442. * For each cell, if a cellStyleGenerator is specified, get the
  3443. * specific style for the cell. If there is any, add it to the
  3444. * target.
  3445. */
  3446. if (cellStyleGenerator != null) {
  3447. String cellStyle = cellStyleGenerator.getStyle(this, itemId,
  3448. columnId);
  3449. if (cellStyle != null && !cellStyle.equals("")) {
  3450. target.addAttribute("style-" + columnIdMap.key(columnId),
  3451. cellStyle);
  3452. }
  3453. }
  3454. if ((iscomponent[currentColumn] || iseditable
  3455. || cells[CELL_GENERATED_ROW][indexInRowbuffer] != null)
  3456. && Component.class.isInstance(cells[CELL_FIRSTCOL
  3457. + currentColumn][indexInRowbuffer])) {
  3458. final Component c = (Component) cells[CELL_FIRSTCOL
  3459. + currentColumn][indexInRowbuffer];
  3460. if (c == null || !LegacyCommunicationManager
  3461. .isComponentVisibleToClient(c)) {
  3462. target.addText("");
  3463. } else {
  3464. LegacyPaint.paint(c, target);
  3465. }
  3466. } else {
  3467. target.addText((String) cells[CELL_FIRSTCOL
  3468. + currentColumn][indexInRowbuffer]);
  3469. }
  3470. paintCellTooltips(target, itemId, columnId);
  3471. }
  3472. target.endTag("tr");
  3473. }
  3474. private void paintCellTooltips(PaintTarget target, Object itemId,
  3475. Object columnId) throws PaintException {
  3476. if (itemDescriptionGenerator != null) {
  3477. String itemDescription = itemDescriptionGenerator
  3478. .generateDescription(this, itemId, columnId);
  3479. if (itemDescription != null && !itemDescription.equals("")) {
  3480. target.addAttribute("descr-" + columnIdMap.key(columnId),
  3481. itemDescription);
  3482. }
  3483. }
  3484. }
  3485. private void paintRowTooltips(PaintTarget target, Object itemId)
  3486. throws PaintException {
  3487. if (itemDescriptionGenerator != null) {
  3488. String rowDescription = itemDescriptionGenerator
  3489. .generateDescription(this, itemId, null);
  3490. if (rowDescription != null && !rowDescription.equals("")) {
  3491. target.addAttribute("rowdescr", rowDescription);
  3492. }
  3493. }
  3494. }
  3495. private void paintRowAttributes(PaintTarget target, final Object[][] cells,
  3496. final Set<Action> actionSet, int indexInRowbuffer,
  3497. final Object itemId) throws PaintException {
  3498. // tr attributes
  3499. paintRowIcon(target, cells, indexInRowbuffer);
  3500. paintRowHeader(target, cells, indexInRowbuffer);
  3501. paintGeneratedRowInfo(target, cells, indexInRowbuffer);
  3502. target.addAttribute("key",
  3503. Integer.parseInt(cells[CELL_KEY][indexInRowbuffer].toString()));
  3504. if (isSelected(itemId)) {
  3505. target.addAttribute("selected", true);
  3506. }
  3507. // Actions
  3508. if (actionHandlers != null) {
  3509. final List<String> keys = new ArrayList<String>();
  3510. for (Handler ah : actionHandlers) {
  3511. final Action[] aa = ah.getActions(itemId, this);
  3512. if (aa != null) {
  3513. for (int ai = 0; ai < aa.length; ai++) {
  3514. final String key = actionMapper.key(aa[ai]);
  3515. actionSet.add(aa[ai]);
  3516. keys.add(key);
  3517. }
  3518. }
  3519. }
  3520. target.addAttribute("al", keys.toArray());
  3521. }
  3522. /*
  3523. * For each row, if a cellStyleGenerator is specified, get the specific
  3524. * style for the cell, using null as propertyId. If there is any, add it
  3525. * to the target.
  3526. */
  3527. if (cellStyleGenerator != null) {
  3528. String rowStyle = cellStyleGenerator.getStyle(this, itemId, null);
  3529. if (rowStyle != null && !rowStyle.equals("")) {
  3530. target.addAttribute("rowstyle", rowStyle);
  3531. }
  3532. }
  3533. paintRowTooltips(target, itemId);
  3534. paintRowAttributes(target, itemId);
  3535. }
  3536. private void paintGeneratedRowInfo(PaintTarget target, Object[][] cells,
  3537. int indexInRowBuffer) throws PaintException {
  3538. GeneratedRow generatedRow = (GeneratedRow) cells[CELL_GENERATED_ROW][indexInRowBuffer];
  3539. if (generatedRow != null) {
  3540. target.addAttribute("gen_html",
  3541. generatedRow.isHtmlContentAllowed());
  3542. target.addAttribute("gen_span", generatedRow.isSpanColumns());
  3543. target.addAttribute("gen_widget",
  3544. generatedRow.getValue() instanceof Component);
  3545. }
  3546. }
  3547. protected void paintRowHeader(PaintTarget target, Object[][] cells,
  3548. int indexInRowbuffer) throws PaintException {
  3549. if (rowHeadersAreEnabled()) {
  3550. if (cells[CELL_HEADER][indexInRowbuffer] != null) {
  3551. target.addAttribute("caption",
  3552. (String) cells[CELL_HEADER][indexInRowbuffer]);
  3553. }
  3554. }
  3555. }
  3556. protected void paintRowIcon(PaintTarget target, final Object[][] cells,
  3557. int indexInRowbuffer) throws PaintException {
  3558. if (rowHeadersAreEnabled()
  3559. && cells[CELL_ICON][indexInRowbuffer] != null) {
  3560. target.addAttribute("icon",
  3561. (Resource) cells[CELL_ICON][indexInRowbuffer]);
  3562. }
  3563. }
  3564. /**
  3565. * A method where extended Table implementations may add their custom
  3566. * attributes for rows.
  3567. *
  3568. * @param target
  3569. * @param itemId
  3570. */
  3571. protected void paintRowAttributes(PaintTarget target, Object itemId)
  3572. throws PaintException {
  3573. }
  3574. /**
  3575. * Gets the cached visible table contents.
  3576. *
  3577. * @return the cached visible table contents.
  3578. */
  3579. private Object[][] getVisibleCells() {
  3580. if (pageBuffer == null) {
  3581. refreshRenderedCells();
  3582. }
  3583. return pageBuffer;
  3584. }
  3585. /**
  3586. * Gets the value of property.
  3587. *
  3588. * By default if the table is editable the fieldFactory is used to create
  3589. * editors for table cells. Otherwise formatPropertyValue is used to format
  3590. * the value representation.
  3591. *
  3592. * @param rowId
  3593. * the Id of the row (same as item Id).
  3594. * @param colId
  3595. * the Id of the column.
  3596. * @param property
  3597. * the Property to be presented.
  3598. * @return Object Either formatted value or Component for field.
  3599. * @see #setTableFieldFactory(TableFieldFactory)
  3600. */
  3601. protected Object getPropertyValue(Object rowId, Object colId,
  3602. Property property) {
  3603. if (isEditable() && fieldFactory != null) {
  3604. final Field<?> f = fieldFactory
  3605. .createField(getContainerDataSource(), rowId, colId, this);
  3606. if (f != null) {
  3607. // Remember that we have made this association so we can remove
  3608. // it when the component is removed
  3609. associatedProperties.put(f, property);
  3610. bindPropertyToField(rowId, colId, property, f);
  3611. return f;
  3612. }
  3613. }
  3614. return formatPropertyValue(rowId, colId, property);
  3615. }
  3616. /**
  3617. * Binds an item property to a field generated by TableFieldFactory. The
  3618. * default behavior is to bind property straight to Field. If
  3619. * Property.Viewer type property (e.g. PropertyFormatter) is already set for
  3620. * field, the property is bound to that Property.Viewer.
  3621. *
  3622. * @param rowId
  3623. * @param colId
  3624. * @param property
  3625. * @param field
  3626. * @since 6.7.3
  3627. */
  3628. protected void bindPropertyToField(Object rowId, Object colId,
  3629. Property property, Field field) {
  3630. // check if field has a property that is Viewer set. In that case we
  3631. // expect developer has e.g. PropertyFormatter that he wishes to use and
  3632. // assign the property to the Viewer instead.
  3633. boolean hasFilterProperty = field.getPropertyDataSource() != null
  3634. && (field.getPropertyDataSource() instanceof Property.Viewer);
  3635. if (hasFilterProperty) {
  3636. ((Property.Viewer) field.getPropertyDataSource())
  3637. .setPropertyDataSource(property);
  3638. } else {
  3639. field.setPropertyDataSource(property);
  3640. }
  3641. }
  3642. /**
  3643. * Formats table cell property values. By default the property.toString()
  3644. * and return a empty string for null properties.
  3645. *
  3646. * @param rowId
  3647. * the Id of the row (same as item Id).
  3648. * @param colId
  3649. * the Id of the column.
  3650. * @param property
  3651. * the Property to be formatted.
  3652. * @return the String representation of property and its value.
  3653. * @since 3.1
  3654. */
  3655. protected String formatPropertyValue(Object rowId, Object colId,
  3656. Property<?> property) {
  3657. if (property == null) {
  3658. return "";
  3659. }
  3660. Converter<String, Object> converter = null;
  3661. if (hasConverter(colId)) {
  3662. converter = getConverter(colId);
  3663. } else {
  3664. converter = (Converter) ConverterUtil.getConverter(String.class,
  3665. property.getType(), getSession());
  3666. }
  3667. Object value = property.getValue();
  3668. if (converter != null) {
  3669. return converter.convertToPresentation(value, String.class,
  3670. getLocale());
  3671. }
  3672. return (null != value) ? value.toString() : "";
  3673. }
  3674. /* Action container */
  3675. /**
  3676. * Registers a new action handler for this container.
  3677. *
  3678. * @see com.vaadin.event.Action.Container#addActionHandler(Action.Handler)
  3679. */
  3680. @Override
  3681. public void addActionHandler(Action.Handler actionHandler) {
  3682. if (actionHandler != null) {
  3683. if (actionHandlers == null) {
  3684. actionHandlers = new LinkedList<Handler>();
  3685. actionMapper = new KeyMapper<Action>();
  3686. }
  3687. if (!actionHandlers.contains(actionHandler)) {
  3688. actionHandlers.add(actionHandler);
  3689. // Assures the visual refresh. No need to reset the page buffer
  3690. // before as the content has not changed, only the action
  3691. // handlers.
  3692. refreshRenderedCells();
  3693. }
  3694. }
  3695. }
  3696. /**
  3697. * Removes a previously registered action handler for the contents of this
  3698. * container.
  3699. *
  3700. * @see com.vaadin.event.Action.Container#removeActionHandler(Action.Handler)
  3701. */
  3702. @Override
  3703. public void removeActionHandler(Action.Handler actionHandler) {
  3704. if (actionHandlers != null && actionHandlers.contains(actionHandler)) {
  3705. actionHandlers.remove(actionHandler);
  3706. if (actionHandlers.isEmpty()) {
  3707. actionHandlers = null;
  3708. actionMapper = null;
  3709. }
  3710. // Assures the visual refresh. No need to reset the page buffer
  3711. // before as the content has not changed, only the action
  3712. // handlers.
  3713. refreshRenderedCells();
  3714. }
  3715. }
  3716. /**
  3717. * Removes all action handlers.
  3718. */
  3719. public void removeAllActionHandlers() {
  3720. actionHandlers = null;
  3721. actionMapper = null;
  3722. // Assures the visual refresh. No need to reset the page buffer
  3723. // before as the content has not changed, only the action
  3724. // handlers.
  3725. refreshRenderedCells();
  3726. }
  3727. /* Property value change listening support */
  3728. /**
  3729. * Notifies this listener that the Property's value has changed.
  3730. *
  3731. * Also listens changes in rendered items to refresh content area.
  3732. *
  3733. * @see Property.ValueChangeListener#valueChange(Property.ValueChangeEvent)
  3734. */
  3735. @Override
  3736. public void valueChange(Property.ValueChangeEvent event) {
  3737. if (equals(event.getProperty())
  3738. || event.getProperty() == getPropertyDataSource()) {
  3739. super.valueChange(event);
  3740. } else {
  3741. refreshRowCache();
  3742. containerChangeToBeRendered = true;
  3743. }
  3744. markAsDirty();
  3745. }
  3746. /**
  3747. * Clears the current page buffer. Call this before
  3748. * {@link #refreshRenderedCells()} to ensure that all content is updated
  3749. * from the properties.
  3750. */
  3751. protected void resetPageBuffer() {
  3752. firstToBeRenderedInClient = -1;
  3753. lastToBeRenderedInClient = -1;
  3754. reqFirstRowToPaint = -1;
  3755. reqRowsToPaint = -1;
  3756. pageBuffer = null;
  3757. }
  3758. /**
  3759. * Notifies the component that it is connected to an application.
  3760. *
  3761. * @see Component#attach()
  3762. */
  3763. @Override
  3764. public void attach() {
  3765. super.attach();
  3766. refreshRenderedCells();
  3767. }
  3768. /**
  3769. * Notifies the component that it is detached from the application.
  3770. *
  3771. * @see Component#detach()
  3772. */
  3773. @Override
  3774. public void detach() {
  3775. super.detach();
  3776. }
  3777. /**
  3778. * Removes all Items from the Container.
  3779. *
  3780. * @see Container#removeAllItems()
  3781. */
  3782. @Override
  3783. public boolean removeAllItems() {
  3784. currentPageFirstItemId = null;
  3785. currentPageFirstItemIndex = 0;
  3786. return super.removeAllItems();
  3787. }
  3788. /**
  3789. * Removes the Item identified by <code>ItemId</code> from the Container.
  3790. *
  3791. * @see Container#removeItem(Object)
  3792. */
  3793. @Override
  3794. public boolean removeItem(Object itemId) {
  3795. final Object nextItemId = nextItemId(itemId);
  3796. final boolean ret = super.removeItem(itemId);
  3797. if (ret && (itemId != null)
  3798. && (itemId.equals(currentPageFirstItemId))) {
  3799. currentPageFirstItemId = nextItemId;
  3800. }
  3801. if (!(items instanceof Container.ItemSetChangeNotifier)) {
  3802. refreshRowCache();
  3803. }
  3804. return ret;
  3805. }
  3806. /**
  3807. * Removes a Property specified by the given Property ID from the Container.
  3808. *
  3809. * @see Container#removeContainerProperty(Object)
  3810. */
  3811. @Override
  3812. public boolean removeContainerProperty(Object propertyId)
  3813. throws UnsupportedOperationException {
  3814. // If a visible property is removed, remove the corresponding column
  3815. visibleColumns.remove(propertyId);
  3816. columnAlignments.remove(propertyId);
  3817. columnIcons.remove(propertyId);
  3818. columnHeaders.remove(propertyId);
  3819. columnFooters.remove(propertyId);
  3820. // If a propertyValueConverter was defined for the property, remove it.
  3821. propertyValueConverters.remove(propertyId);
  3822. return super.removeContainerProperty(propertyId);
  3823. }
  3824. /**
  3825. * Adds a new property to the table and show it as a visible column.
  3826. *
  3827. * @param propertyId
  3828. * the Id of the property.
  3829. * @param type
  3830. * the class of the property.
  3831. * @param defaultValue
  3832. * the default value given for all existing items.
  3833. * @see Container#addContainerProperty(Object, Class, Object)
  3834. */
  3835. @Override
  3836. public boolean addContainerProperty(Object propertyId, Class<?> type,
  3837. Object defaultValue) throws UnsupportedOperationException {
  3838. boolean visibleColAdded = false;
  3839. if (!visibleColumns.contains(propertyId)) {
  3840. visibleColumns.add(propertyId);
  3841. visibleColAdded = true;
  3842. }
  3843. if (!super.addContainerProperty(propertyId, type, defaultValue)) {
  3844. if (visibleColAdded) {
  3845. visibleColumns.remove(propertyId);
  3846. }
  3847. return false;
  3848. }
  3849. if (!(items instanceof Container.PropertySetChangeNotifier)) {
  3850. refreshRowCache();
  3851. }
  3852. return true;
  3853. }
  3854. /**
  3855. * Adds a new property to the table and show it as a visible column.
  3856. *
  3857. * @param propertyId
  3858. * the Id of the property
  3859. * @param type
  3860. * the class of the property
  3861. * @param defaultValue
  3862. * the default value given for all existing items
  3863. * @param columnHeader
  3864. * the Explicit header of the column. If explicit header is not
  3865. * needed, this should be set null.
  3866. * @param columnIcon
  3867. * the Icon of the column. If icon is not needed, this should be
  3868. * set null.
  3869. * @param columnAlignment
  3870. * the Alignment of the column. Null implies align left.
  3871. * @throws UnsupportedOperationException
  3872. * if the operation is not supported.
  3873. * @see Container#addContainerProperty(Object, Class, Object)
  3874. */
  3875. public boolean addContainerProperty(Object propertyId, Class<?> type,
  3876. Object defaultValue, String columnHeader, Resource columnIcon,
  3877. Align columnAlignment) throws UnsupportedOperationException {
  3878. if (!this.addContainerProperty(propertyId, type, defaultValue)) {
  3879. return false;
  3880. }
  3881. setColumnAlignment(propertyId, columnAlignment);
  3882. setColumnHeader(propertyId, columnHeader);
  3883. setColumnIcon(propertyId, columnIcon);
  3884. return true;
  3885. }
  3886. /**
  3887. * Adds a generated column to the Table.
  3888. * <p>
  3889. * A generated column is a column that exists only in the Table, not as a
  3890. * property in the underlying Container. It shows up just as a regular
  3891. * column.
  3892. * </p>
  3893. * <p>
  3894. * A generated column will override a property with the same id, so that the
  3895. * generated column is shown instead of the column representing the
  3896. * property. Note that getContainerProperty() will still get the real
  3897. * property.
  3898. * </p>
  3899. * <p>
  3900. * Table will not listen to value change events from properties overridden
  3901. * by generated columns. If the content of your generated column depends on
  3902. * properties that are not directly visible in the table, attach value
  3903. * change listener to update the content on all depended properties.
  3904. * Otherwise your UI might not get updated as expected.
  3905. * </p>
  3906. * <p>
  3907. * Also note that getVisibleColumns() will return the generated columns,
  3908. * while getContainerPropertyIds() will not.
  3909. * </p>
  3910. *
  3911. * @param id
  3912. * the id of the column to be added
  3913. * @param generatedColumn
  3914. * the {@link ColumnGenerator} to use for this column
  3915. */
  3916. public void addGeneratedColumn(Object id, ColumnGenerator generatedColumn) {
  3917. if (generatedColumn == null) {
  3918. throw new IllegalArgumentException(
  3919. "Can not add null as a GeneratedColumn");
  3920. }
  3921. if (columnGenerators.containsKey(id)) {
  3922. throw new IllegalArgumentException(
  3923. "Can not add the same GeneratedColumn twice, id:" + id);
  3924. } else {
  3925. columnGenerators.put(id, generatedColumn);
  3926. /*
  3927. * add to visible column list unless already there (overriding
  3928. * column from DS)
  3929. */
  3930. if (!visibleColumns.contains(id)) {
  3931. visibleColumns.add(id);
  3932. }
  3933. refreshRowCache();
  3934. }
  3935. }
  3936. /**
  3937. * Returns the ColumnGenerator used to generate the given column.
  3938. *
  3939. * @param columnId
  3940. * The id of the generated column
  3941. * @return The ColumnGenerator used for the given columnId or null.
  3942. */
  3943. public ColumnGenerator getColumnGenerator(Object columnId)
  3944. throws IllegalArgumentException {
  3945. return columnGenerators.get(columnId);
  3946. }
  3947. /**
  3948. * Removes a generated column previously added with addGeneratedColumn.
  3949. *
  3950. * @param columnId
  3951. * id of the generated column to remove
  3952. * @return true if the column could be removed (existed in the Table)
  3953. */
  3954. public boolean removeGeneratedColumn(Object columnId) {
  3955. if (columnGenerators.containsKey(columnId)) {
  3956. columnGenerators.remove(columnId);
  3957. // remove column from visibleColumns list unless it exists in
  3958. // container (generator previously overrode this column)
  3959. if (!items.getContainerPropertyIds().contains(columnId)) {
  3960. visibleColumns.remove(columnId);
  3961. }
  3962. refreshRowCache();
  3963. return true;
  3964. } else {
  3965. return false;
  3966. }
  3967. }
  3968. /**
  3969. * Returns item identifiers of the items which are currently rendered on the
  3970. * client.
  3971. * <p>
  3972. * Note, that some due to historical reasons the name of the method is bit
  3973. * misleading. Some items may be partly or totally out of the viewport of
  3974. * the table's scrollable area. Actually detecting rows which can be
  3975. * actually seen by the end user may be problematic due to the client server
  3976. * architecture. Using {@link #getCurrentPageFirstItemId()} combined with
  3977. * {@link #getPageLength()} may produce good enough estimates in some
  3978. * situations.
  3979. *
  3980. * @see Select#getVisibleItemIds()
  3981. */
  3982. @Override
  3983. public Collection<?> getVisibleItemIds() {
  3984. final LinkedList<Object> visible = new LinkedList<Object>();
  3985. final Object[][] cells = getVisibleCells();
  3986. // may be null if the table has not been rendered yet (e.g. not attached
  3987. // to a layout)
  3988. if (null != cells) {
  3989. for (Object id : cells[CELL_ITEMID]) {
  3990. visible.add(id);
  3991. }
  3992. }
  3993. return visible;
  3994. }
  3995. /**
  3996. * Container datasource item set change. Table must flush its buffers on
  3997. * change.
  3998. *
  3999. * @see Container.ItemSetChangeListener#containerItemSetChange(Container.ItemSetChangeEvent)
  4000. */
  4001. @Override
  4002. public void containerItemSetChange(Container.ItemSetChangeEvent event) {
  4003. if (isBeingPainted) {
  4004. return;
  4005. }
  4006. super.containerItemSetChange(event);
  4007. // super method clears the key map, must inform client about this to
  4008. // avoid getting invalid keys back (#8584)
  4009. keyMapperReset = true;
  4010. int currentFirstItemIndex = getCurrentPageFirstItemIndex();
  4011. if (event.getContainer().size() == 0) {
  4012. repairOnReAddAllRowsDataScrollPositionItemIndex = getCurrentPageFirstItemIndex();
  4013. } else {
  4014. if (repairOnReAddAllRowsDataScrollPositionItemIndex != -1) {
  4015. currentFirstItemIndex = repairOnReAddAllRowsDataScrollPositionItemIndex;
  4016. /*
  4017. * Reset repairOnReAddAllRowsDataScrollPositionItemIndex.
  4018. *
  4019. * Next string should be commented (removed) if we want to have
  4020. * possibility to restore scroll position during adding items to
  4021. * container one by one via add() but not only addAll(). The
  4022. * problem in this case: we cannot track what happened between
  4023. * add() and add()... So it is ambiguous where to stop restore
  4024. * scroll position.
  4025. */
  4026. repairOnReAddAllRowsDataScrollPositionItemIndex = -1;
  4027. }
  4028. }
  4029. // ensure that page still has first item in page, ignore buffer refresh
  4030. // (forced in this method)
  4031. setCurrentPageFirstItemIndex(currentFirstItemIndex, false);
  4032. refreshRowCache();
  4033. }
  4034. /**
  4035. * Container datasource property set change. Table must flush its buffers on
  4036. * change.
  4037. *
  4038. * @see Container.PropertySetChangeListener#containerPropertySetChange(Container.PropertySetChangeEvent)
  4039. */
  4040. @Override
  4041. public void containerPropertySetChange(
  4042. Container.PropertySetChangeEvent event) {
  4043. if (isBeingPainted) {
  4044. return;
  4045. }
  4046. disableContentRefreshing();
  4047. super.containerPropertySetChange(event);
  4048. // sanitize visibleColumns. note that we are not adding previously
  4049. // non-existing properties as columns
  4050. Collection<?> containerPropertyIds = getContainerDataSource()
  4051. .getContainerPropertyIds();
  4052. LinkedList<Object> newVisibleColumns = new LinkedList<Object>(
  4053. visibleColumns);
  4054. for (Iterator<Object> iterator = newVisibleColumns.iterator(); iterator
  4055. .hasNext();) {
  4056. Object id = iterator.next();
  4057. if (!(containerPropertyIds.contains(id)
  4058. || columnGenerators.containsKey(id))) {
  4059. iterator.remove();
  4060. }
  4061. }
  4062. setVisibleColumns(newVisibleColumns.toArray());
  4063. // same for collapsed columns
  4064. for (Iterator<Object> iterator = collapsedColumns.iterator(); iterator
  4065. .hasNext();) {
  4066. Object id = iterator.next();
  4067. if (!(containerPropertyIds.contains(id)
  4068. || columnGenerators.containsKey(id))) {
  4069. iterator.remove();
  4070. }
  4071. }
  4072. resetPageBuffer();
  4073. enableContentRefreshing(true);
  4074. }
  4075. /**
  4076. * Adding new items is not supported.
  4077. *
  4078. * @throws UnsupportedOperationException
  4079. * if set to true.
  4080. * @see Select#setNewItemsAllowed(boolean)
  4081. */
  4082. @Override
  4083. public void setNewItemsAllowed(boolean allowNewOptions)
  4084. throws UnsupportedOperationException {
  4085. if (allowNewOptions) {
  4086. throw new UnsupportedOperationException();
  4087. }
  4088. }
  4089. /**
  4090. * Gets the ID of the Item following the Item that corresponds to itemId.
  4091. *
  4092. * @see Container.Ordered#nextItemId(java.lang.Object)
  4093. */
  4094. @Override
  4095. public Object nextItemId(Object itemId) {
  4096. return ((Container.Ordered) items).nextItemId(itemId);
  4097. }
  4098. /**
  4099. * Gets the ID of the Item preceding the Item that corresponds to the
  4100. * itemId.
  4101. *
  4102. * @see Container.Ordered#prevItemId(java.lang.Object)
  4103. */
  4104. @Override
  4105. public Object prevItemId(Object itemId) {
  4106. return ((Container.Ordered) items).prevItemId(itemId);
  4107. }
  4108. /**
  4109. * Gets the ID of the first Item in the Container.
  4110. *
  4111. * @see Container.Ordered#firstItemId()
  4112. */
  4113. @Override
  4114. public Object firstItemId() {
  4115. return ((Container.Ordered) items).firstItemId();
  4116. }
  4117. /**
  4118. * Gets the ID of the last Item in the Container.
  4119. *
  4120. * @see Container.Ordered#lastItemId()
  4121. */
  4122. @Override
  4123. public Object lastItemId() {
  4124. return ((Container.Ordered) items).lastItemId();
  4125. }
  4126. /**
  4127. * Tests if the Item corresponding to the given Item ID is the first Item in
  4128. * the Container.
  4129. *
  4130. * @see Container.Ordered#isFirstId(java.lang.Object)
  4131. */
  4132. @Override
  4133. public boolean isFirstId(Object itemId) {
  4134. return ((Container.Ordered) items).isFirstId(itemId);
  4135. }
  4136. /**
  4137. * Tests if the Item corresponding to the given Item ID is the last Item in
  4138. * the Container.
  4139. *
  4140. * @see Container.Ordered#isLastId(java.lang.Object)
  4141. */
  4142. @Override
  4143. public boolean isLastId(Object itemId) {
  4144. return ((Container.Ordered) items).isLastId(itemId);
  4145. }
  4146. /**
  4147. * Adds new item after the given item.
  4148. *
  4149. * @see Container.Ordered#addItemAfter(java.lang.Object)
  4150. */
  4151. @Override
  4152. public Object addItemAfter(Object previousItemId)
  4153. throws UnsupportedOperationException {
  4154. Object itemId = ((Container.Ordered) items)
  4155. .addItemAfter(previousItemId);
  4156. if (!(items instanceof Container.ItemSetChangeNotifier)) {
  4157. refreshRowCache();
  4158. }
  4159. return itemId;
  4160. }
  4161. /**
  4162. * Adds new item after the given item.
  4163. *
  4164. * @see Container.Ordered#addItemAfter(java.lang.Object, java.lang.Object)
  4165. */
  4166. @Override
  4167. public Item addItemAfter(Object previousItemId, Object newItemId)
  4168. throws UnsupportedOperationException {
  4169. Item item = ((Container.Ordered) items).addItemAfter(previousItemId,
  4170. newItemId);
  4171. if (!(items instanceof Container.ItemSetChangeNotifier)) {
  4172. refreshRowCache();
  4173. }
  4174. return item;
  4175. }
  4176. /**
  4177. * Sets the TableFieldFactory that is used to create editor for table cells.
  4178. *
  4179. * The TableFieldFactory is only used if the Table is editable. By default
  4180. * the DefaultFieldFactory is used.
  4181. *
  4182. * @param fieldFactory
  4183. * the field factory to set.
  4184. * @see #isEditable
  4185. * @see DefaultFieldFactory
  4186. */
  4187. public void setTableFieldFactory(TableFieldFactory fieldFactory) {
  4188. this.fieldFactory = fieldFactory;
  4189. // Assure visual refresh
  4190. refreshRowCache();
  4191. }
  4192. /**
  4193. * Gets the TableFieldFactory that is used to create editor for table cells.
  4194. *
  4195. * The FieldFactory is only used if the Table is editable.
  4196. *
  4197. * @return TableFieldFactory used to create the Field instances.
  4198. * @see #isEditable
  4199. */
  4200. public TableFieldFactory getTableFieldFactory() {
  4201. return fieldFactory;
  4202. }
  4203. /**
  4204. * Is table editable.
  4205. *
  4206. * If table is editable a editor of type Field is created for each table
  4207. * cell. The assigned FieldFactory is used to create the instances.
  4208. *
  4209. * To provide custom editors for table cells create a class implementing the
  4210. * FieldFactory interface, and assign it to table, and set the editable
  4211. * property to true.
  4212. *
  4213. * @return true if table is editable, false otherwise.
  4214. * @see Field
  4215. * @see FieldFactory
  4216. *
  4217. */
  4218. public boolean isEditable() {
  4219. return editable;
  4220. }
  4221. /**
  4222. * Sets the editable property.
  4223. *
  4224. * If table is editable a editor of type Field is created for each table
  4225. * cell. The assigned FieldFactory is used to create the instances.
  4226. *
  4227. * To provide custom editors for table cells create a class implementing the
  4228. * FieldFactory interface, and assign it to table, and set the editable
  4229. * property to true.
  4230. *
  4231. * @param editable
  4232. * true if table should be editable by user.
  4233. * @see Field
  4234. * @see FieldFactory
  4235. *
  4236. */
  4237. public void setEditable(boolean editable) {
  4238. this.editable = editable;
  4239. // Assure visual refresh
  4240. refreshRowCache();
  4241. }
  4242. /**
  4243. * Sorts the table.
  4244. *
  4245. * @throws UnsupportedOperationException
  4246. * if the container data source does not implement
  4247. * Container.Sortable
  4248. * @see Container.Sortable#sort(java.lang.Object[], boolean[])
  4249. *
  4250. */
  4251. @Override
  4252. public void sort(Object[] propertyId, boolean[] ascending)
  4253. throws UnsupportedOperationException {
  4254. final Container c = getContainerDataSource();
  4255. if (c instanceof Container.Sortable) {
  4256. final int pageIndex = getCurrentPageFirstItemIndex();
  4257. boolean refreshingPreviouslyEnabled = disableContentRefreshing();
  4258. ((Container.Sortable) c).sort(propertyId, ascending);
  4259. setCurrentPageFirstItemIndex(pageIndex);
  4260. if (refreshingPreviouslyEnabled) {
  4261. enableContentRefreshing(true);
  4262. }
  4263. if (propertyId.length > 0 && ascending.length > 0) {
  4264. // The first propertyId is the primary sorting criterion,
  4265. // therefore the sort indicator should be there
  4266. sortAscending = ascending[0];
  4267. sortContainerPropertyId = propertyId[0];
  4268. } else {
  4269. sortAscending = true;
  4270. sortContainerPropertyId = null;
  4271. }
  4272. } else if (c != null) {
  4273. throw new UnsupportedOperationException(
  4274. "Underlying Data does not allow sorting");
  4275. }
  4276. }
  4277. /**
  4278. * Sorts the table by currently selected sorting column.
  4279. *
  4280. * @throws UnsupportedOperationException
  4281. * if the container data source does not implement
  4282. * Container.Sortable
  4283. */
  4284. public void sort() {
  4285. if (getSortContainerPropertyId() == null) {
  4286. return;
  4287. }
  4288. sort(new Object[] { sortContainerPropertyId },
  4289. new boolean[] { sortAscending });
  4290. }
  4291. /**
  4292. * Gets the container property IDs, which can be used to sort the item.
  4293. * <p>
  4294. * Note that the {@link #isSortEnabled()} state affects what this method
  4295. * returns. Disabling sorting causes this method to always return an empty
  4296. * collection.
  4297. * </p>
  4298. *
  4299. * @see Container.Sortable#getSortableContainerPropertyIds()
  4300. */
  4301. @Override
  4302. public Collection<?> getSortableContainerPropertyIds() {
  4303. final Container c = getContainerDataSource();
  4304. if (c instanceof Container.Sortable && isSortEnabled()) {
  4305. return ((Container.Sortable) c).getSortableContainerPropertyIds();
  4306. } else {
  4307. return Collections.EMPTY_LIST;
  4308. }
  4309. }
  4310. /**
  4311. * Gets the currently sorted column property ID.
  4312. *
  4313. * @return the Container property id of the currently sorted column.
  4314. */
  4315. public Object getSortContainerPropertyId() {
  4316. return sortContainerPropertyId;
  4317. }
  4318. /**
  4319. * Sets the currently sorted column property id.
  4320. *
  4321. * @param propertyId
  4322. * the Container property id of the currently sorted column.
  4323. */
  4324. public void setSortContainerPropertyId(Object propertyId) {
  4325. setSortContainerPropertyId(propertyId, true);
  4326. }
  4327. /**
  4328. * Internal method to set currently sorted column property id. With doSort
  4329. * flag actual sorting may be bypassed.
  4330. *
  4331. * @param propertyId
  4332. * @param doSort
  4333. */
  4334. private void setSortContainerPropertyId(Object propertyId, boolean doSort) {
  4335. if ((sortContainerPropertyId != null
  4336. && !sortContainerPropertyId.equals(propertyId))
  4337. || (sortContainerPropertyId == null && propertyId != null)) {
  4338. sortContainerPropertyId = propertyId;
  4339. if (doSort) {
  4340. sort();
  4341. // Assures the visual refresh. This should not be necessary as
  4342. // sort() calls refreshRowCache
  4343. refreshRenderedCells();
  4344. }
  4345. }
  4346. }
  4347. /**
  4348. * Is the table currently sorted in ascending order.
  4349. *
  4350. * @return <code>true</code> if ascending, <code>false</code> if descending.
  4351. */
  4352. public boolean isSortAscending() {
  4353. return sortAscending;
  4354. }
  4355. /**
  4356. * Sets the table in ascending order.
  4357. *
  4358. * @param ascending
  4359. * <code>true</code> if ascending, <code>false</code> if
  4360. * descending.
  4361. */
  4362. public void setSortAscending(boolean ascending) {
  4363. setSortAscending(ascending, true);
  4364. }
  4365. /**
  4366. * Internal method to set sort ascending. With doSort flag actual sort can
  4367. * be bypassed.
  4368. *
  4369. * @param ascending
  4370. * @param doSort
  4371. */
  4372. private void setSortAscending(boolean ascending, boolean doSort) {
  4373. if (sortAscending != ascending) {
  4374. sortAscending = ascending;
  4375. if (doSort) {
  4376. sort();
  4377. // Assures the visual refresh. This should not be necessary as
  4378. // sort() calls refreshRowCache
  4379. refreshRenderedCells();
  4380. }
  4381. }
  4382. }
  4383. /**
  4384. * Is sorting disabled altogether.
  4385. *
  4386. * True if no sortable columns are given even in the case where data source
  4387. * would support this.
  4388. *
  4389. * @return True if sorting is disabled.
  4390. * @deprecated As of 7.0, use {@link #isSortEnabled()} instead
  4391. */
  4392. @Deprecated
  4393. public boolean isSortDisabled() {
  4394. return !isSortEnabled();
  4395. }
  4396. /**
  4397. * Checks if sorting is enabled.
  4398. *
  4399. * @return true if sorting by the user is allowed, false otherwise
  4400. */
  4401. public boolean isSortEnabled() {
  4402. return sortEnabled;
  4403. }
  4404. /**
  4405. * Disables the sorting by the user altogether.
  4406. *
  4407. * @param sortDisabled
  4408. * True if sorting is disabled.
  4409. * @deprecated As of 7.0, use {@link #setSortEnabled(boolean)} instead
  4410. */
  4411. @Deprecated
  4412. public void setSortDisabled(boolean sortDisabled) {
  4413. setSortEnabled(!sortDisabled);
  4414. }
  4415. /**
  4416. * Enables or disables sorting.
  4417. * <p>
  4418. * Setting this to false disallows sorting by the user. It is still possible
  4419. * to call {@link #sort()}.
  4420. * </p>
  4421. *
  4422. * @param sortEnabled
  4423. * true to allow the user to sort the table, false to disallow it
  4424. */
  4425. public void setSortEnabled(boolean sortEnabled) {
  4426. if (this.sortEnabled != sortEnabled) {
  4427. this.sortEnabled = sortEnabled;
  4428. markAsDirty();
  4429. }
  4430. }
  4431. /**
  4432. * Used to create "generated columns"; columns that exist only in the Table,
  4433. * not in the underlying Container. Implement this interface and pass it to
  4434. * Table.addGeneratedColumn along with an id for the column to be generated.
  4435. *
  4436. */
  4437. @Deprecated
  4438. public interface ColumnGenerator extends Serializable {
  4439. /**
  4440. * Called by Table when a cell in a generated column needs to be
  4441. * generated.
  4442. *
  4443. * @param source
  4444. * the source Table
  4445. * @param itemId
  4446. * the itemId (aka rowId) for the of the cell to be generated
  4447. * @param columnId
  4448. * the id for the generated column (as specified in
  4449. * addGeneratedColumn)
  4450. * @return A {@link Component} that should be rendered in the cell or a
  4451. * {@link String} that should be displayed in the cell. Other
  4452. * return values are not supported.
  4453. */
  4454. public abstract Object generateCell(Table source, Object itemId,
  4455. Object columnId);
  4456. }
  4457. /**
  4458. * Set cell style generator for Table.
  4459. *
  4460. * @param cellStyleGenerator
  4461. * New cell style generator or null to remove generator.
  4462. */
  4463. public void setCellStyleGenerator(CellStyleGenerator cellStyleGenerator) {
  4464. this.cellStyleGenerator = cellStyleGenerator;
  4465. // Assures the visual refresh. No need to reset the page buffer
  4466. // before as the content has not changed, only the style generators
  4467. refreshRenderedCells();
  4468. }
  4469. /**
  4470. * Get the current cell style generator.
  4471. *
  4472. */
  4473. public CellStyleGenerator getCellStyleGenerator() {
  4474. return cellStyleGenerator;
  4475. }
  4476. /**
  4477. * Allow to define specific style on cells (and rows) contents. Implements
  4478. * this interface and pass it to Table.setCellStyleGenerator. Row styles are
  4479. * generated when porpertyId is null. The CSS class name that will be added
  4480. * to the cell content is <tt>v-table-cell-content-[style name]</tt>, and
  4481. * the row style will be <tt>v-table-row-[style name]</tt>.
  4482. */
  4483. @Deprecated
  4484. public interface CellStyleGenerator extends Serializable {
  4485. /**
  4486. * Called by Table when a cell (and row) is painted.
  4487. *
  4488. * @param source
  4489. * the source Table
  4490. * @param itemId
  4491. * The itemId of the painted cell
  4492. * @param propertyId
  4493. * The propertyId of the cell, null when getting row style
  4494. * @return The style name to add to this cell or row. (the CSS class
  4495. * name will be v-table-cell-content-[style name], or
  4496. * v-table-row-[style name] for rows)
  4497. */
  4498. public abstract String getStyle(Table source, Object itemId,
  4499. Object propertyId);
  4500. }
  4501. @Override
  4502. public void addItemClickListener(ItemClickListener listener) {
  4503. addListener(TableConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  4504. listener, ItemClickEvent.ITEM_CLICK_METHOD);
  4505. }
  4506. /**
  4507. * @deprecated As of 7.0, replaced by
  4508. * {@link #addItemClickListener(ItemClickListener)}
  4509. */
  4510. @Override
  4511. @Deprecated
  4512. public void addListener(ItemClickListener listener) {
  4513. addItemClickListener(listener);
  4514. }
  4515. @Override
  4516. public void removeItemClickListener(ItemClickListener listener) {
  4517. removeListener(TableConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  4518. listener);
  4519. }
  4520. /**
  4521. * @deprecated As of 7.0, replaced by
  4522. * {@link #removeItemClickListener(ItemClickListener)}
  4523. */
  4524. @Override
  4525. @Deprecated
  4526. public void removeListener(ItemClickListener listener) {
  4527. removeItemClickListener(listener);
  4528. }
  4529. // Identical to AbstractCompoenentContainer.setEnabled();
  4530. @Override
  4531. public void setEnabled(boolean enabled) {
  4532. super.setEnabled(enabled);
  4533. if (getParent() != null && !getParent().isEnabled()) {
  4534. // some ancestor still disabled, don't update children
  4535. return;
  4536. } else {
  4537. markAsDirtyRecursive();
  4538. }
  4539. }
  4540. /**
  4541. * Sets the drag start mode of the Table. Drag start mode controls how Table
  4542. * behaves as a drag source.
  4543. *
  4544. * @param newDragMode
  4545. */
  4546. public void setDragMode(TableDragMode newDragMode) {
  4547. dragMode = newDragMode;
  4548. markAsDirty();
  4549. }
  4550. /**
  4551. * @return the current start mode of the Table. Drag start mode controls how
  4552. * Table behaves as a drag source.
  4553. */
  4554. public TableDragMode getDragMode() {
  4555. return dragMode;
  4556. }
  4557. /**
  4558. * Concrete implementation of {@link DataBoundTransferable} for data
  4559. * transferred from a table.
  4560. *
  4561. * @see DataBoundTransferable
  4562. *
  4563. * @since 6.3
  4564. */
  4565. @Deprecated
  4566. public class TableTransferable extends DataBoundTransferable {
  4567. protected TableTransferable(Map<String, Object> rawVariables) {
  4568. super(Table.this, rawVariables);
  4569. Object object = rawVariables.get("itemId");
  4570. if (object != null) {
  4571. setData("itemId", itemIdMapper.get((String) object));
  4572. }
  4573. object = rawVariables.get("propertyId");
  4574. if (object != null) {
  4575. setData("propertyId", columnIdMap.get((String) object));
  4576. }
  4577. }
  4578. @Override
  4579. public Object getItemId() {
  4580. return getData("itemId");
  4581. }
  4582. @Override
  4583. public Object getPropertyId() {
  4584. return getData("propertyId");
  4585. }
  4586. @Override
  4587. public Table getSourceComponent() {
  4588. return (Table) super.getSourceComponent();
  4589. }
  4590. }
  4591. @Override
  4592. public TableTransferable getTransferable(Map<String, Object> rawVariables) {
  4593. TableTransferable transferable = new TableTransferable(rawVariables);
  4594. return transferable;
  4595. }
  4596. @Override
  4597. public DropHandler getDropHandler() {
  4598. return dropHandler;
  4599. }
  4600. public void setDropHandler(DropHandler dropHandler) {
  4601. this.dropHandler = dropHandler;
  4602. }
  4603. @Override
  4604. public AbstractSelectTargetDetails translateDropTargetDetails(
  4605. Map<String, Object> clientVariables) {
  4606. return new AbstractSelectTargetDetails(clientVariables);
  4607. }
  4608. /**
  4609. * Sets the behavior of how the multi-select mode should behave when the
  4610. * table is both selectable and in multi-select mode.
  4611. * <p>
  4612. * Note, that on some clients the mode may not be respected. E.g. on touch
  4613. * based devices CTRL/SHIFT base selection method is invalid, so touch based
  4614. * browsers always use the {@link MultiSelectMode#SIMPLE} unless touch multi
  4615. * select is explicitly disabled.
  4616. *
  4617. * @see #setMultiSelectTouchDetectionEnabled(boolean)
  4618. *
  4619. * @param mode
  4620. * The select mode of the table
  4621. */
  4622. public void setMultiSelectMode(MultiSelectMode mode) {
  4623. multiSelectMode = mode;
  4624. markAsDirty();
  4625. }
  4626. /**
  4627. * Returns the select mode in which multi-select is used.
  4628. *
  4629. * @return The multi select mode
  4630. */
  4631. public MultiSelectMode getMultiSelectMode() {
  4632. return multiSelectMode;
  4633. }
  4634. /**
  4635. * Default behavior on touch-reporting devices is to switch from CTRL/SHIFT
  4636. * based multi-selection to simple mode, but you can use this method to
  4637. * explicitly disable the touch device detection. Thus you can keep using
  4638. * keyboard-based multi selection on hybrid devices that have both a touch
  4639. * screen and a keyboard.
  4640. *
  4641. * @param multiSelectTouchDetectionEnabled
  4642. * Whether to enable or disable touch screen detection
  4643. */
  4644. public void setMultiSelectTouchDetectionEnabled(
  4645. boolean multiSelectTouchDetectionEnabled) {
  4646. this.multiSelectTouchDetectionEnabled = multiSelectTouchDetectionEnabled;
  4647. markAsDirty();
  4648. }
  4649. /**
  4650. * Returns if touch screen detection is used to toggle multi select mode.
  4651. *
  4652. * @return If touch screen detection for multi select is enabled
  4653. */
  4654. public boolean isMultiSelectTouchDetectionEnabled() {
  4655. return multiSelectTouchDetectionEnabled;
  4656. }
  4657. /**
  4658. * Lazy loading accept criterion for Table. Accepted target rows are loaded
  4659. * from server once per drag and drop operation. Developer must override one
  4660. * method that decides on which rows the currently dragged data can be
  4661. * dropped.
  4662. *
  4663. * <p>
  4664. * Initially pretty much no data is sent to client. On first required
  4665. * criterion check (per drag request) the client side data structure is
  4666. * initialized from server and no subsequent requests requests are needed
  4667. * during that drag and drop operation.
  4668. */
  4669. @Deprecated
  4670. public abstract static class TableDropCriterion
  4671. extends ServerSideCriterion {
  4672. private Table table;
  4673. private Set<Object> allowedItemIds;
  4674. /*
  4675. * (non-Javadoc)
  4676. *
  4677. * @see
  4678. * com.vaadin.event.dd.acceptcriteria.ServerSideCriterion#getIdentifier
  4679. * ()
  4680. */
  4681. @Override
  4682. protected String getIdentifier() {
  4683. return TableDropCriterion.class.getCanonicalName();
  4684. }
  4685. /*
  4686. * (non-Javadoc)
  4687. *
  4688. * @see
  4689. * com.vaadin.event.dd.acceptcriteria.AcceptCriterion#accepts(com.vaadin
  4690. * .event.dd.DragAndDropEvent)
  4691. */
  4692. @Override
  4693. @SuppressWarnings("unchecked")
  4694. public boolean accept(DragAndDropEvent dragEvent) {
  4695. AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
  4696. .getTargetDetails();
  4697. table = (Table) dragEvent.getTargetDetails().getTarget();
  4698. Collection<?> visibleItemIds = table.getVisibleItemIds();
  4699. allowedItemIds = getAllowedItemIds(dragEvent, table,
  4700. (Collection<Object>) visibleItemIds);
  4701. return allowedItemIds.contains(dropTargetData.getItemIdOver());
  4702. }
  4703. /*
  4704. * (non-Javadoc)
  4705. *
  4706. * @see
  4707. * com.vaadin.event.dd.acceptcriteria.AcceptCriterion#paintResponse(
  4708. * com.vaadin.server.PaintTarget)
  4709. */
  4710. @Override
  4711. public void paintResponse(PaintTarget target) throws PaintException {
  4712. /*
  4713. * send allowed nodes to client so subsequent requests can be
  4714. * avoided
  4715. */
  4716. Object[] array = allowedItemIds.toArray();
  4717. for (int i = 0; i < array.length; i++) {
  4718. String key = table.itemIdMapper.key(array[i]);
  4719. array[i] = key;
  4720. }
  4721. target.addAttribute("allowedIds", array);
  4722. }
  4723. /**
  4724. * @param dragEvent
  4725. * @param table
  4726. * the table for which the allowed item identifiers are
  4727. * defined
  4728. * @param visibleItemIds
  4729. * the list of currently rendered item identifiers, accepted
  4730. * item id's need to be detected only for these visible items
  4731. * @return the set of identifiers for items on which the dragEvent will
  4732. * be accepted
  4733. */
  4734. protected abstract Set<Object> getAllowedItemIds(
  4735. DragAndDropEvent dragEvent, Table table,
  4736. Collection<Object> visibleItemIds);
  4737. }
  4738. /**
  4739. * Click event fired when clicking on the Table headers. The event includes
  4740. * a reference the the Table the event originated from, the property id of
  4741. * the column which header was pressed and details about the mouse event
  4742. * itself.
  4743. */
  4744. @Deprecated
  4745. public static class HeaderClickEvent extends ClickEvent {
  4746. public static final Method HEADER_CLICK_METHOD;
  4747. static {
  4748. try {
  4749. // Set the header click method
  4750. HEADER_CLICK_METHOD = HeaderClickListener.class
  4751. .getDeclaredMethod("headerClick",
  4752. new Class[] { HeaderClickEvent.class });
  4753. } catch (final NoSuchMethodException e) {
  4754. // This should never happen
  4755. throw new RuntimeException(e);
  4756. }
  4757. }
  4758. // The property id of the column which header was pressed
  4759. private final Object columnPropertyId;
  4760. public HeaderClickEvent(Component source, Object propertyId,
  4761. MouseEventDetails details) {
  4762. super(source, details);
  4763. columnPropertyId = propertyId;
  4764. }
  4765. /**
  4766. * Gets the property id of the column which header was pressed.
  4767. *
  4768. * @return The column property id
  4769. */
  4770. public Object getPropertyId() {
  4771. return columnPropertyId;
  4772. }
  4773. }
  4774. /**
  4775. * Click event fired when clicking on the Table footers. The event includes
  4776. * a reference the the Table the event originated from, the property id of
  4777. * the column which header was pressed and details about the mouse event
  4778. * itself.
  4779. */
  4780. @Deprecated
  4781. public static class FooterClickEvent extends ClickEvent {
  4782. public static final Method FOOTER_CLICK_METHOD;
  4783. static {
  4784. try {
  4785. // Set the header click method
  4786. FOOTER_CLICK_METHOD = FooterClickListener.class
  4787. .getDeclaredMethod("footerClick",
  4788. new Class[] { FooterClickEvent.class });
  4789. } catch (final NoSuchMethodException e) {
  4790. // This should never happen
  4791. throw new RuntimeException(e);
  4792. }
  4793. }
  4794. // The property id of the column which header was pressed
  4795. private final Object columnPropertyId;
  4796. /**
  4797. * Constructor.
  4798. *
  4799. * @param source
  4800. * The source of the component
  4801. * @param propertyId
  4802. * The propertyId of the column
  4803. * @param details
  4804. * The mouse details of the click
  4805. */
  4806. public FooterClickEvent(Component source, Object propertyId,
  4807. MouseEventDetails details) {
  4808. super(source, details);
  4809. columnPropertyId = propertyId;
  4810. }
  4811. /**
  4812. * Gets the property id of the column which header was pressed.
  4813. *
  4814. * @return The column property id
  4815. */
  4816. public Object getPropertyId() {
  4817. return columnPropertyId;
  4818. }
  4819. }
  4820. /**
  4821. * Interface for the listener for column header mouse click events. The
  4822. * headerClick method is called when the user presses a header column cell.
  4823. */
  4824. @Deprecated
  4825. public interface HeaderClickListener extends Serializable {
  4826. /**
  4827. * Called when a user clicks a header column cell.
  4828. *
  4829. * @param event
  4830. * The event which contains information about the column and
  4831. * the mouse click event
  4832. */
  4833. public void headerClick(HeaderClickEvent event);
  4834. }
  4835. /**
  4836. * Interface for the listener for column footer mouse click events. The
  4837. * footerClick method is called when the user presses a footer column cell.
  4838. */
  4839. @Deprecated
  4840. public interface FooterClickListener extends Serializable {
  4841. /**
  4842. * Called when a user clicks a footer column cell.
  4843. *
  4844. * @param event
  4845. * The event which contains information about the column and
  4846. * the mouse click event
  4847. */
  4848. public void footerClick(FooterClickEvent event);
  4849. }
  4850. /**
  4851. * Adds a header click listener which handles the click events when the user
  4852. * clicks on a column header cell in the Table.
  4853. * <p>
  4854. * The listener will receive events which contain information about which
  4855. * column was clicked and some details about the mouse event.
  4856. * </p>
  4857. *
  4858. * @param listener
  4859. * The handler which should handle the header click events.
  4860. */
  4861. public void addHeaderClickListener(HeaderClickListener listener) {
  4862. addListener(TableConstants.HEADER_CLICK_EVENT_ID,
  4863. HeaderClickEvent.class, listener,
  4864. HeaderClickEvent.HEADER_CLICK_METHOD);
  4865. }
  4866. /**
  4867. * @deprecated As of 7.0, replaced by
  4868. * {@link #addHeaderClickListener(HeaderClickListener)}
  4869. */
  4870. @Deprecated
  4871. public void addListener(HeaderClickListener listener) {
  4872. addHeaderClickListener(listener);
  4873. }
  4874. /**
  4875. * Removes a header click listener.
  4876. *
  4877. * @param listener
  4878. * The listener to remove.
  4879. */
  4880. public void removeHeaderClickListener(HeaderClickListener listener) {
  4881. removeListener(TableConstants.HEADER_CLICK_EVENT_ID,
  4882. HeaderClickEvent.class, listener);
  4883. }
  4884. /**
  4885. * @deprecated As of 7.0, replaced by
  4886. * {@link #removeHeaderClickListener(HeaderClickListener)}
  4887. */
  4888. @Deprecated
  4889. public void removeListener(HeaderClickListener listener) {
  4890. removeHeaderClickListener(listener);
  4891. }
  4892. /**
  4893. * Adds a footer click listener which handles the click events when the user
  4894. * clicks on a column footer cell in the Table.
  4895. * <p>
  4896. * The listener will receive events which contain information about which
  4897. * column was clicked and some details about the mouse event.
  4898. * </p>
  4899. *
  4900. * @param listener
  4901. * The handler which should handle the footer click events.
  4902. */
  4903. public void addFooterClickListener(FooterClickListener listener) {
  4904. addListener(TableConstants.FOOTER_CLICK_EVENT_ID,
  4905. FooterClickEvent.class, listener,
  4906. FooterClickEvent.FOOTER_CLICK_METHOD);
  4907. }
  4908. /**
  4909. * @deprecated As of 7.0, replaced by
  4910. * {@link #addFooterClickListener(FooterClickListener)}
  4911. */
  4912. @Deprecated
  4913. public void addListener(FooterClickListener listener) {
  4914. addFooterClickListener(listener);
  4915. }
  4916. /**
  4917. * Removes a footer click listener.
  4918. *
  4919. * @param listener
  4920. * The listener to remove.
  4921. */
  4922. public void removeFooterClickListener(FooterClickListener listener) {
  4923. removeListener(TableConstants.FOOTER_CLICK_EVENT_ID,
  4924. FooterClickEvent.class, listener);
  4925. }
  4926. /**
  4927. * @deprecated As of 7.0, replaced by
  4928. * {@link #removeFooterClickListener(FooterClickListener)}
  4929. */
  4930. @Deprecated
  4931. public void removeListener(FooterClickListener listener) {
  4932. removeFooterClickListener(listener);
  4933. }
  4934. /**
  4935. * Gets the footer caption beneath the rows.
  4936. *
  4937. * @param propertyId
  4938. * The propertyId of the column *
  4939. * @return The caption of the footer or NULL if not set
  4940. */
  4941. public String getColumnFooter(Object propertyId) {
  4942. return columnFooters.get(propertyId);
  4943. }
  4944. /**
  4945. * Sets the column footer caption. The column footer caption is the text
  4946. * displayed beneath the column if footers have been set visible.
  4947. *
  4948. * @param propertyId
  4949. * The properyId of the column
  4950. *
  4951. * @param footer
  4952. * The caption of the footer
  4953. */
  4954. public void setColumnFooter(Object propertyId, String footer) {
  4955. if (footer == null) {
  4956. columnFooters.remove(propertyId);
  4957. } else {
  4958. columnFooters.put(propertyId, footer);
  4959. }
  4960. markAsDirty();
  4961. }
  4962. /**
  4963. * Sets the footer visible in the bottom of the table.
  4964. * <p>
  4965. * The footer can be used to add column related data like sums to the bottom
  4966. * of the Table using setColumnFooter(Object propertyId, String footer).
  4967. * </p>
  4968. *
  4969. * @param visible
  4970. * Should the footer be visible
  4971. */
  4972. public void setFooterVisible(boolean visible) {
  4973. if (visible != columnFootersVisible) {
  4974. columnFootersVisible = visible;
  4975. markAsDirty();
  4976. }
  4977. }
  4978. /**
  4979. * Is the footer currently visible?
  4980. *
  4981. * @return Returns true if visible else false
  4982. */
  4983. public boolean isFooterVisible() {
  4984. return columnFootersVisible;
  4985. }
  4986. /**
  4987. * This event is fired when a column is resized. The event contains the
  4988. * columns property id which was fired, the previous width of the column and
  4989. * the width of the column after the resize.
  4990. */
  4991. @Deprecated
  4992. public static class ColumnResizeEvent extends Component.Event {
  4993. public static final Method COLUMN_RESIZE_METHOD;
  4994. static {
  4995. try {
  4996. COLUMN_RESIZE_METHOD = ColumnResizeListener.class
  4997. .getDeclaredMethod("columnResize",
  4998. new Class[] { ColumnResizeEvent.class });
  4999. } catch (final NoSuchMethodException e) {
  5000. // This should never happen
  5001. throw new RuntimeException(e);
  5002. }
  5003. }
  5004. private final int previousWidth;
  5005. private final int currentWidth;
  5006. private final Object columnPropertyId;
  5007. /**
  5008. * Constructor.
  5009. *
  5010. * @param source
  5011. * The source of the event
  5012. * @param propertyId
  5013. * The columns property id
  5014. * @param previous
  5015. * The width in pixels of the column before the resize event
  5016. * @param current
  5017. * The width in pixels of the column after the resize event
  5018. */
  5019. public ColumnResizeEvent(Component source, Object propertyId,
  5020. int previous, int current) {
  5021. super(source);
  5022. previousWidth = previous;
  5023. currentWidth = current;
  5024. columnPropertyId = propertyId;
  5025. }
  5026. /**
  5027. * Get the column property id of the column that was resized.
  5028. *
  5029. * @return The column property id
  5030. */
  5031. public Object getPropertyId() {
  5032. return columnPropertyId;
  5033. }
  5034. /**
  5035. * Get the width in pixels of the column before the resize event.
  5036. *
  5037. * @return Width in pixels
  5038. */
  5039. public int getPreviousWidth() {
  5040. return previousWidth;
  5041. }
  5042. /**
  5043. * Get the width in pixels of the column after the resize event.
  5044. *
  5045. * @return Width in pixels
  5046. */
  5047. public int getCurrentWidth() {
  5048. return currentWidth;
  5049. }
  5050. }
  5051. /**
  5052. * Interface for listening to column resize events.
  5053. */
  5054. @Deprecated
  5055. public interface ColumnResizeListener extends Serializable {
  5056. /**
  5057. * This method is triggered when the column has been resized.
  5058. *
  5059. * @param event
  5060. * The event which contains the column property id, the
  5061. * previous width of the column and the current width of the
  5062. * column
  5063. */
  5064. public void columnResize(ColumnResizeEvent event);
  5065. }
  5066. /**
  5067. * Adds a column resize listener to the Table. A column resize listener is
  5068. * called when a user resizes a columns width.
  5069. *
  5070. * @param listener
  5071. * The listener to attach to the Table
  5072. */
  5073. public void addColumnResizeListener(ColumnResizeListener listener) {
  5074. addListener(TableConstants.COLUMN_RESIZE_EVENT_ID,
  5075. ColumnResizeEvent.class, listener,
  5076. ColumnResizeEvent.COLUMN_RESIZE_METHOD);
  5077. }
  5078. /**
  5079. * @deprecated As of 7.0, replaced by
  5080. * {@link #addColumnResizeListener(ColumnResizeListener)}
  5081. */
  5082. @Deprecated
  5083. public void addListener(ColumnResizeListener listener) {
  5084. addColumnResizeListener(listener);
  5085. }
  5086. /**
  5087. * Removes a column resize listener from the Table.
  5088. *
  5089. * @param listener
  5090. * The listener to remove
  5091. */
  5092. public void removeColumnResizeListener(ColumnResizeListener listener) {
  5093. removeListener(TableConstants.COLUMN_RESIZE_EVENT_ID,
  5094. ColumnResizeEvent.class, listener);
  5095. }
  5096. /**
  5097. * @deprecated As of 7.0, replaced by
  5098. * {@link #removeColumnResizeListener(ColumnResizeListener)}
  5099. */
  5100. @Deprecated
  5101. public void removeListener(ColumnResizeListener listener) {
  5102. removeColumnResizeListener(listener);
  5103. }
  5104. /**
  5105. * This event is fired when a columns are reordered by the end user user.
  5106. */
  5107. @Deprecated
  5108. public static class ColumnReorderEvent extends Component.Event {
  5109. public static final Method METHOD;
  5110. static {
  5111. try {
  5112. METHOD = ColumnReorderListener.class.getDeclaredMethod(
  5113. "columnReorder",
  5114. new Class[] { ColumnReorderEvent.class });
  5115. } catch (final NoSuchMethodException e) {
  5116. // This should never happen
  5117. throw new RuntimeException(e);
  5118. }
  5119. }
  5120. /**
  5121. * Constructor.
  5122. *
  5123. * @param source
  5124. * The source of the event
  5125. */
  5126. public ColumnReorderEvent(Component source) {
  5127. super(source);
  5128. }
  5129. }
  5130. /**
  5131. * Interface for listening to column reorder events.
  5132. */
  5133. @Deprecated
  5134. public interface ColumnReorderListener extends Serializable {
  5135. /**
  5136. * This method is triggered when the column has been reordered.
  5137. *
  5138. * @param event
  5139. */
  5140. public void columnReorder(ColumnReorderEvent event);
  5141. }
  5142. /**
  5143. * This event is fired when the collapse state of a column changes.
  5144. *
  5145. * @since 7.6
  5146. */
  5147. @Deprecated
  5148. public static class ColumnCollapseEvent extends Component.Event {
  5149. public static final Method METHOD = ReflectTools.findMethod(
  5150. ColumnCollapseListener.class, "columnCollapseStateChange",
  5151. ColumnCollapseEvent.class);
  5152. private Object propertyId;
  5153. /**
  5154. * Constructor.
  5155. *
  5156. * @param source
  5157. * The source of the event
  5158. * @param propertyId
  5159. * The id of the column
  5160. */
  5161. public ColumnCollapseEvent(Component source, Object propertyId) {
  5162. super(source);
  5163. this.propertyId = propertyId;
  5164. }
  5165. /**
  5166. * Gets the id of the column whose collapse state changed.
  5167. *
  5168. * @return the property id of the column
  5169. */
  5170. public Object getPropertyId() {
  5171. return propertyId;
  5172. }
  5173. }
  5174. /**
  5175. * Interface for listening to column collapse events.
  5176. *
  5177. * @since 7.6
  5178. */
  5179. @Deprecated
  5180. public interface ColumnCollapseListener extends Serializable {
  5181. /**
  5182. * This method is triggered when the collapse state for a column has
  5183. * changed.
  5184. *
  5185. * @param event
  5186. */
  5187. public void columnCollapseStateChange(ColumnCollapseEvent event);
  5188. }
  5189. /**
  5190. * Adds a column reorder listener to the Table. A column reorder listener is
  5191. * called when a user reorders columns.
  5192. *
  5193. * @param listener
  5194. * The listener to attach to the Table
  5195. */
  5196. public void addColumnReorderListener(ColumnReorderListener listener) {
  5197. addListener(TableConstants.COLUMN_REORDER_EVENT_ID,
  5198. ColumnReorderEvent.class, listener, ColumnReorderEvent.METHOD);
  5199. }
  5200. /**
  5201. * @deprecated As of 7.0, replaced by
  5202. * {@link #addColumnReorderListener(ColumnReorderListener)}
  5203. */
  5204. @Deprecated
  5205. public void addListener(ColumnReorderListener listener) {
  5206. addColumnReorderListener(listener);
  5207. }
  5208. /**
  5209. * Removes a column reorder listener from the Table.
  5210. *
  5211. * @param listener
  5212. * The listener to remove
  5213. */
  5214. public void removeColumnReorderListener(ColumnReorderListener listener) {
  5215. removeListener(TableConstants.COLUMN_REORDER_EVENT_ID,
  5216. ColumnReorderEvent.class, listener);
  5217. }
  5218. /**
  5219. * @deprecated As of 7.0, replaced by
  5220. * {@link #removeColumnReorderListener(ColumnReorderListener)}
  5221. */
  5222. @Deprecated
  5223. public void removeListener(ColumnReorderListener listener) {
  5224. removeColumnReorderListener(listener);
  5225. }
  5226. /**
  5227. * Adds a column collapse listener to the Table. A column collapse listener
  5228. * is called when the collapsed state of a column changes.
  5229. *
  5230. * @since 7.6
  5231. *
  5232. * @param listener
  5233. * The listener to attach
  5234. */
  5235. public void addColumnCollapseListener(ColumnCollapseListener listener) {
  5236. addListener(TableConstants.COLUMN_COLLAPSE_EVENT_ID,
  5237. ColumnCollapseEvent.class, listener,
  5238. ColumnCollapseEvent.METHOD);
  5239. }
  5240. /**
  5241. * Removes a column reorder listener from the Table.
  5242. *
  5243. * @since 7.6
  5244. * @param listener
  5245. * The listener to remove
  5246. */
  5247. public void removeColumnCollapseListener(ColumnCollapseListener listener) {
  5248. removeListener(TableConstants.COLUMN_COLLAPSE_EVENT_ID,
  5249. ColumnCollapseEvent.class, listener);
  5250. }
  5251. /**
  5252. * Set the item description generator which generates tooltips for cells and
  5253. * rows in the Table.
  5254. *
  5255. * @param generator
  5256. * The generator to use or null to disable
  5257. */
  5258. public void setItemDescriptionGenerator(
  5259. ItemDescriptionGenerator generator) {
  5260. if (generator != itemDescriptionGenerator) {
  5261. itemDescriptionGenerator = generator;
  5262. // Assures the visual refresh. No need to reset the page buffer
  5263. // before as the content has not changed, only the descriptions
  5264. refreshRenderedCells();
  5265. }
  5266. }
  5267. /**
  5268. * Get the item description generator which generates tooltips for cells and
  5269. * rows in the Table.
  5270. */
  5271. public ItemDescriptionGenerator getItemDescriptionGenerator() {
  5272. return itemDescriptionGenerator;
  5273. }
  5274. /**
  5275. * Row generators can be used to replace certain items in a table with a
  5276. * generated string. The generator is called each time the table is
  5277. * rendered, which means that new strings can be generated each time.
  5278. *
  5279. * Row generators can be used for e.g. summary rows or grouping of items.
  5280. */
  5281. @Deprecated
  5282. public interface RowGenerator extends Serializable {
  5283. /**
  5284. * Called for every row that is painted in the Table. Returning a
  5285. * GeneratedRow object will cause the row to be painted based on the
  5286. * contents of the GeneratedRow. A generated row is by default styled
  5287. * similarly to a header or footer row.
  5288. * <p>
  5289. * The GeneratedRow data object contains the text that should be
  5290. * rendered in the row. The itemId in the container thus works only as a
  5291. * placeholder.
  5292. * <p>
  5293. * If GeneratedRow.setSpanColumns(true) is used, there will be one
  5294. * String spanning all columns (use setText("Spanning text")). Otherwise
  5295. * you can define one String per visible column.
  5296. * <p>
  5297. * If GeneratedRow.setRenderAsHtml(true) is used, the strings can
  5298. * contain HTML markup, otherwise all strings will be rendered as text
  5299. * (the default).
  5300. * <p>
  5301. * A "v-table-generated-row" CSS class is added to all generated rows.
  5302. * For custom styling of a generated row you can combine a RowGenerator
  5303. * with a CellStyleGenerator.
  5304. * <p>
  5305. *
  5306. * @param table
  5307. * The Table that is being painted
  5308. * @param itemId
  5309. * The itemId for the row
  5310. * @return A GeneratedRow describing how the row should be painted or
  5311. * null to paint the row with the contents from the container
  5312. */
  5313. public GeneratedRow generateRow(Table table, Object itemId);
  5314. }
  5315. @Deprecated
  5316. public static class GeneratedRow implements Serializable {
  5317. private boolean htmlContentAllowed = false;
  5318. private boolean spanColumns = false;
  5319. private String[] text = null;
  5320. /**
  5321. * Creates a new generated row. If only one string is passed in, columns
  5322. * are automatically spanned.
  5323. *
  5324. * @param text
  5325. */
  5326. public GeneratedRow(String... text) {
  5327. setHtmlContentAllowed(false);
  5328. setSpanColumns(text == null || text.length == 1);
  5329. setText(text);
  5330. }
  5331. /**
  5332. * Pass one String if spanColumns is used, one String for each visible
  5333. * column otherwise.
  5334. */
  5335. public void setText(String... text) {
  5336. if (text == null || (text.length == 1 && text[0] == null)) {
  5337. text = new String[] { "" };
  5338. }
  5339. this.text = text;
  5340. }
  5341. protected String[] getText() {
  5342. return text;
  5343. }
  5344. protected Object getValue() {
  5345. return getText();
  5346. }
  5347. protected boolean isHtmlContentAllowed() {
  5348. return htmlContentAllowed;
  5349. }
  5350. /**
  5351. * If set to true, all strings passed to {@link #setText(String...)}
  5352. * will be rendered as HTML.
  5353. *
  5354. * @param htmlContentAllowed
  5355. */
  5356. public void setHtmlContentAllowed(boolean htmlContentAllowed) {
  5357. this.htmlContentAllowed = htmlContentAllowed;
  5358. }
  5359. protected boolean isSpanColumns() {
  5360. return spanColumns;
  5361. }
  5362. /**
  5363. * If set to true, only one string will be rendered, spanning the entire
  5364. * row.
  5365. *
  5366. * @param spanColumns
  5367. */
  5368. public void setSpanColumns(boolean spanColumns) {
  5369. this.spanColumns = spanColumns;
  5370. }
  5371. }
  5372. /**
  5373. * Assigns a row generator to the table. The row generator will be able to
  5374. * replace rows in the table when it is rendered.
  5375. *
  5376. * @param generator
  5377. * the new row generator
  5378. */
  5379. public void setRowGenerator(RowGenerator generator) {
  5380. rowGenerator = generator;
  5381. refreshRowCache();
  5382. }
  5383. /**
  5384. * @return the current row generator
  5385. */
  5386. public RowGenerator getRowGenerator() {
  5387. return rowGenerator;
  5388. }
  5389. /**
  5390. * Sets a converter for a property id.
  5391. * <p>
  5392. * The converter is used to format the the data for the given property id
  5393. * before displaying it in the table.
  5394. * </p>
  5395. *
  5396. * @param propertyId
  5397. * The propertyId to format using the converter
  5398. * @param converter
  5399. * The converter to use for the property id
  5400. */
  5401. public void setConverter(Object propertyId,
  5402. Converter<String, ?> converter) {
  5403. if (!getContainerPropertyIds().contains(propertyId)) {
  5404. throw new IllegalArgumentException(
  5405. "PropertyId " + propertyId + " must be in the container");
  5406. }
  5407. if (!typeIsCompatible(converter.getModelType(), getType(propertyId))) {
  5408. throw new IllegalArgumentException(
  5409. "Property type (" + getType(propertyId)
  5410. + ") must match converter source type ("
  5411. + converter.getModelType() + ")");
  5412. }
  5413. propertyValueConverters.put(propertyId,
  5414. (Converter<String, Object>) converter);
  5415. refreshRowCache();
  5416. }
  5417. /**
  5418. * Checks if there is a converter set explicitly for the given property id.
  5419. *
  5420. * @param propertyId
  5421. * The propertyId to check
  5422. * @return true if a converter has been set for the property id, false
  5423. * otherwise
  5424. */
  5425. protected boolean hasConverter(Object propertyId) {
  5426. return propertyValueConverters.containsKey(propertyId);
  5427. }
  5428. /**
  5429. * Returns the converter used to format the given propertyId.
  5430. *
  5431. * @param propertyId
  5432. * The propertyId to check
  5433. * @return The converter used to format the propertyId or null if no
  5434. * converter has been set
  5435. */
  5436. public Converter<String, Object> getConverter(Object propertyId) {
  5437. return propertyValueConverters.get(propertyId);
  5438. }
  5439. @Override
  5440. public void setVisible(boolean visible) {
  5441. if (visible) {
  5442. // We need to ensure that the rows are sent to the client when the
  5443. // Table is made visible if it has been rendered as invisible.
  5444. setRowCacheInvalidated(true);
  5445. }
  5446. super.setVisible(visible);
  5447. }
  5448. @Override
  5449. public Iterator<Component> iterator() {
  5450. if (visibleComponents == null) {
  5451. Collection<Component> empty = Collections.emptyList();
  5452. return empty.iterator();
  5453. }
  5454. return visibleComponents.iterator();
  5455. }
  5456. /**
  5457. * @deprecated As of 7.0, use {@link #iterator()} instead.
  5458. */
  5459. @Deprecated
  5460. public Iterator<Component> getComponentIterator() {
  5461. return iterator();
  5462. }
  5463. @Override
  5464. public void readDesign(Element design, DesignContext context) {
  5465. super.readDesign(design, context);
  5466. if (design.hasAttr("sortable")) {
  5467. setSortEnabled(DesignAttributeHandler.readAttribute("sortable",
  5468. design.attributes(), boolean.class));
  5469. }
  5470. readColumns(design);
  5471. readHeader(design);
  5472. readBody(design, context);
  5473. readFooter(design);
  5474. }
  5475. private void readColumns(Element design) {
  5476. Element colgroup = design.select("> table > colgroup").first();
  5477. if (colgroup != null) {
  5478. int i = 0;
  5479. List<Object> pIds = new ArrayList<Object>();
  5480. for (Element col : colgroup.children()) {
  5481. if (!col.tagName().equals("col")) {
  5482. throw new DesignException("invalid column");
  5483. }
  5484. String id = DesignAttributeHandler.readAttribute("property-id",
  5485. col.attributes(), "property-" + i++, String.class);
  5486. pIds.add(id);
  5487. addContainerProperty(id, String.class, null);
  5488. if (col.hasAttr("width")) {
  5489. setColumnWidth(id, DesignAttributeHandler.readAttribute(
  5490. "width", col.attributes(), Integer.class));
  5491. }
  5492. if (col.hasAttr("center")) {
  5493. setColumnAlignment(id, Align.CENTER);
  5494. } else if (col.hasAttr("right")) {
  5495. setColumnAlignment(id, Align.RIGHT);
  5496. }
  5497. if (col.hasAttr("expand")) {
  5498. if (col.attr("expand").isEmpty()) {
  5499. setColumnExpandRatio(id, 1);
  5500. } else {
  5501. setColumnExpandRatio(id,
  5502. DesignAttributeHandler.readAttribute("expand",
  5503. col.attributes(), float.class));
  5504. }
  5505. }
  5506. if (col.hasAttr("collapsible")) {
  5507. setColumnCollapsible(id,
  5508. DesignAttributeHandler.readAttribute("collapsible",
  5509. col.attributes(), boolean.class));
  5510. }
  5511. if (col.hasAttr("collapsed")) {
  5512. setColumnCollapsed(id, DesignAttributeHandler.readAttribute(
  5513. "collapsed", col.attributes(), boolean.class));
  5514. }
  5515. }
  5516. setVisibleColumns(pIds.toArray());
  5517. }
  5518. }
  5519. private void readFooter(Element design) {
  5520. readHeaderOrFooter(design, false);
  5521. }
  5522. private void readHeader(Element design) {
  5523. readHeaderOrFooter(design, true);
  5524. }
  5525. @Override
  5526. protected void readItems(Element design, DesignContext context) {
  5527. // Do nothing - header/footer and inline data must be handled after
  5528. // colgroup.
  5529. }
  5530. private void readHeaderOrFooter(Element design, boolean header) {
  5531. String selector = header ? "> table > thead" : "> table > tfoot";
  5532. Element elem = design.select(selector).first();
  5533. if (elem != null) {
  5534. if (!header) {
  5535. setFooterVisible(true);
  5536. }
  5537. if (elem.children().size() != 1) {
  5538. throw new DesignException(
  5539. "Table header and footer should contain exactly one <tr> element");
  5540. }
  5541. Element tr = elem.child(0);
  5542. Elements elems = tr.children();
  5543. Collection<?> propertyIds = visibleColumns;
  5544. if (elems.size() != propertyIds.size()) {
  5545. throw new DesignException(
  5546. "Table header and footer should contain as many items as there"
  5547. + " are columns in the Table.");
  5548. }
  5549. Iterator<?> propertyIt = propertyIds.iterator();
  5550. for (Element e : elems) {
  5551. String columnValue = DesignFormatter
  5552. .decodeFromTextNode(e.html());
  5553. Object propertyId = propertyIt.next();
  5554. if (header) {
  5555. setColumnHeader(propertyId, columnValue);
  5556. if (e.hasAttr("icon")) {
  5557. setColumnIcon(propertyId,
  5558. DesignAttributeHandler.readAttribute("icon",
  5559. e.attributes(), Resource.class));
  5560. }
  5561. } else {
  5562. setColumnFooter(propertyId, columnValue);
  5563. }
  5564. }
  5565. }
  5566. }
  5567. protected void readBody(Element design, DesignContext context) {
  5568. Element tbody = design.select("> table > tbody").first();
  5569. if (tbody == null) {
  5570. return;
  5571. }
  5572. Set<String> selected = new HashSet<String>();
  5573. for (Element tr : tbody.children()) {
  5574. readItem(tr, selected, context);
  5575. }
  5576. }
  5577. @Override
  5578. protected Object readItem(Element tr, Set<String> selected,
  5579. DesignContext context) {
  5580. Elements cells = tr.children();
  5581. if (visibleColumns.size() != cells.size()) {
  5582. throw new DesignException(
  5583. "Wrong number of columns in a Table row. Expected "
  5584. + visibleColumns.size() + ", was " + cells.size()
  5585. + ".");
  5586. }
  5587. Object[] data = new String[cells.size()];
  5588. for (int c = 0; c < cells.size(); ++c) {
  5589. data[c] = DesignFormatter.decodeFromTextNode(cells.get(c).html());
  5590. }
  5591. Object itemId = addItem(data,
  5592. tr.hasAttr("item-id") ? tr.attr("item-id") : null);
  5593. if (itemId == null) {
  5594. throw new DesignException("Failed to add a Table row: " + data);
  5595. }
  5596. return itemId;
  5597. }
  5598. @Override
  5599. public void writeDesign(Element design, DesignContext context) {
  5600. Table def = context.getDefaultInstance(this);
  5601. DesignAttributeHandler.writeAttribute("sortable", design.attributes(),
  5602. isSortEnabled(), def.isSortEnabled(), boolean.class, context);
  5603. Element table = null;
  5604. boolean hasColumns = getVisibleColumns().length != 0;
  5605. if (hasColumns) {
  5606. table = design.appendElement("table");
  5607. writeColumns(table, def, context);
  5608. writeHeader(table, def, context);
  5609. }
  5610. super.writeDesign(design, context);
  5611. if (hasColumns) {
  5612. writeFooter(table);
  5613. }
  5614. }
  5615. private void writeColumns(Element table, Table def, DesignContext context) {
  5616. Object[] columns = getVisibleColumns();
  5617. if (columns.length == 0) {
  5618. return;
  5619. }
  5620. Element colgroup = table.appendElement("colgroup");
  5621. for (Object id : columns) {
  5622. Element col = colgroup.appendElement("col");
  5623. col.attr("property-id", id.toString());
  5624. if (getColumnAlignment(id) == Align.CENTER) {
  5625. col.attr("center", true);
  5626. } else if (getColumnAlignment(id) == Align.RIGHT) {
  5627. col.attr("right", true);
  5628. }
  5629. DesignAttributeHandler.writeAttribute("width", col.attributes(),
  5630. getColumnWidth(id), def.getColumnWidth(null), int.class,
  5631. context);
  5632. DesignAttributeHandler.writeAttribute("expand", col.attributes(),
  5633. getColumnExpandRatio(id), def.getColumnExpandRatio(null),
  5634. float.class, context);
  5635. DesignAttributeHandler.writeAttribute("collapsible",
  5636. col.attributes(), isColumnCollapsible(id),
  5637. def.isColumnCollapsible(null), boolean.class, context);
  5638. DesignAttributeHandler.writeAttribute("collapsed", col.attributes(),
  5639. isColumnCollapsed(id), def.isColumnCollapsed(null),
  5640. boolean.class, context);
  5641. }
  5642. }
  5643. private void writeHeader(Element table, Table def, DesignContext context) {
  5644. Object[] columns = getVisibleColumns();
  5645. if (columns.length == 0
  5646. || (columnIcons.isEmpty() && columnHeaders.isEmpty())) {
  5647. return;
  5648. }
  5649. Element header = table.appendElement("thead").appendElement("tr");
  5650. for (Object id : columns) {
  5651. Element th = header.appendElement("th");
  5652. th.html(getColumnHeader(id));
  5653. DesignAttributeHandler.writeAttribute("icon", th.attributes(),
  5654. getColumnIcon(id), def.getColumnIcon(null), Resource.class,
  5655. context);
  5656. }
  5657. }
  5658. private void writeFooter(Element table) {
  5659. Object[] columns = getVisibleColumns();
  5660. if (columns.length == 0 || columnFooters.isEmpty()) {
  5661. return;
  5662. }
  5663. Element footer = table.appendElement("tfoot").appendElement("tr");
  5664. for (Object id : columns) {
  5665. footer.appendElement("td").text(getColumnFooter(id));
  5666. }
  5667. }
  5668. @Override
  5669. protected void writeItems(Element design, DesignContext context) {
  5670. if (getVisibleColumns().length == 0) {
  5671. return;
  5672. }
  5673. Element tbody = design.child(0).appendElement("tbody");
  5674. super.writeItems(tbody, context);
  5675. }
  5676. @Override
  5677. protected Element writeItem(Element tbody, Object itemId,
  5678. DesignContext context) {
  5679. Element tr = tbody.appendElement("tr");
  5680. tr.attr("item-id", String.valueOf(itemId));
  5681. Item item = getItem(itemId);
  5682. for (Object id : getVisibleColumns()) {
  5683. Element td = tr.appendElement("td");
  5684. Object value = item.getItemProperty(id).getValue();
  5685. td.html(value != null ? value.toString() : "");
  5686. }
  5687. return tr;
  5688. }
  5689. @Override
  5690. protected Collection<String> getCustomAttributes() {
  5691. Collection<String> result = super.getCustomAttributes();
  5692. result.add("sortable");
  5693. result.add("sort-enabled");
  5694. result.add("sort-disabled");
  5695. result.add("footer-visible");
  5696. result.add("item-caption-mode");
  5697. result.add("current-page-first-item-id");
  5698. result.add("current-page-first-item-index");
  5699. return result;
  5700. }
  5701. /**
  5702. * ContextClickEvent for the Table Component.
  5703. *
  5704. * @since 7.6
  5705. */
  5706. @Deprecated
  5707. public static class TableContextClickEvent extends ContextClickEvent {
  5708. private final Object itemId;
  5709. private final Object propertyId;
  5710. private final Section section;
  5711. public TableContextClickEvent(Table source,
  5712. MouseEventDetails mouseEventDetails, Object itemId,
  5713. Object propertyId, Section section) {
  5714. super(source, mouseEventDetails);
  5715. this.itemId = itemId;
  5716. this.propertyId = propertyId;
  5717. this.section = section;
  5718. }
  5719. /**
  5720. * Returns the item id of context clicked row.
  5721. *
  5722. * @return item id of clicked row; <code>null</code> if header, footer
  5723. * or empty area of Table
  5724. */
  5725. public Object getItemId() {
  5726. return itemId;
  5727. }
  5728. /**
  5729. * Returns the property id of context clicked column.
  5730. *
  5731. * @return property id; or <code>null</code> if we've clicked on the
  5732. * empty area of the Table
  5733. */
  5734. public Object getPropertyId() {
  5735. return propertyId;
  5736. }
  5737. /**
  5738. * Returns the clicked section of Table.
  5739. *
  5740. * @return section of Table
  5741. */
  5742. public Section getSection() {
  5743. return section;
  5744. }
  5745. @Override
  5746. public Table getComponent() {
  5747. return (Table) super.getComponent();
  5748. }
  5749. }
  5750. @Override
  5751. protected TableState getState() {
  5752. return getState(true);
  5753. }
  5754. @Override
  5755. protected TableState getState(boolean markAsDirty) {
  5756. return (TableState) super.getState(markAsDirty);
  5757. }
  5758. private final Logger getLogger() {
  5759. if (logger == null) {
  5760. logger = Logger.getLogger(Table.class.getName());
  5761. }
  5762. return logger;
  5763. }
  5764. @Override
  5765. public void setChildMeasurementHint(ChildMeasurementHint hint) {
  5766. if (hint == null) {
  5767. childMeasurementHint = ChildMeasurementHint.MEASURE_ALWAYS;
  5768. } else {
  5769. childMeasurementHint = hint;
  5770. }
  5771. }
  5772. @Override
  5773. public ChildMeasurementHint getChildMeasurementHint() {
  5774. return childMeasurementHint;
  5775. }
  5776. /**
  5777. * Sets whether only collapsible columns should be shown to the user in the
  5778. * column collapse menu. The default is
  5779. * {@link CollapseMenuContent#ALL_COLUMNS}.
  5780. *
  5781. *
  5782. * @since 7.6
  5783. * @param content
  5784. * the desired collapsible menu content setting
  5785. */
  5786. public void setCollapseMenuContent(CollapseMenuContent content) {
  5787. getState().collapseMenuContent = content;
  5788. }
  5789. /**
  5790. * Checks whether only collapsible columns are shown to the user in the
  5791. * column collapse menu. The default is
  5792. * {@link CollapseMenuContent#ALL_COLUMNS} .
  5793. *
  5794. * @since 7.6
  5795. * @return the current collapsible menu content setting
  5796. */
  5797. public CollapseMenuContent getCollapseMenuContent() {
  5798. return getState(false).collapseMenuContent;
  5799. }
  5800. }