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

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