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.

VScrollTable.java 285KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724
  1. /*
  2. * Copyright 2000-2013 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.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import com.google.gwt.core.client.JavaScriptObject;
  27. import com.google.gwt.core.client.Scheduler;
  28. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  29. import com.google.gwt.dom.client.Document;
  30. import com.google.gwt.dom.client.NativeEvent;
  31. import com.google.gwt.dom.client.Node;
  32. import com.google.gwt.dom.client.NodeList;
  33. import com.google.gwt.dom.client.Style;
  34. import com.google.gwt.dom.client.Style.Display;
  35. import com.google.gwt.dom.client.Style.Overflow;
  36. import com.google.gwt.dom.client.Style.Position;
  37. import com.google.gwt.dom.client.Style.Unit;
  38. import com.google.gwt.dom.client.Style.Visibility;
  39. import com.google.gwt.dom.client.TableCellElement;
  40. import com.google.gwt.dom.client.TableRowElement;
  41. import com.google.gwt.dom.client.TableSectionElement;
  42. import com.google.gwt.dom.client.Touch;
  43. import com.google.gwt.event.dom.client.BlurEvent;
  44. import com.google.gwt.event.dom.client.BlurHandler;
  45. import com.google.gwt.event.dom.client.ContextMenuEvent;
  46. import com.google.gwt.event.dom.client.ContextMenuHandler;
  47. import com.google.gwt.event.dom.client.FocusEvent;
  48. import com.google.gwt.event.dom.client.FocusHandler;
  49. import com.google.gwt.event.dom.client.KeyCodes;
  50. import com.google.gwt.event.dom.client.KeyDownEvent;
  51. import com.google.gwt.event.dom.client.KeyDownHandler;
  52. import com.google.gwt.event.dom.client.KeyPressEvent;
  53. import com.google.gwt.event.dom.client.KeyPressHandler;
  54. import com.google.gwt.event.dom.client.KeyUpEvent;
  55. import com.google.gwt.event.dom.client.KeyUpHandler;
  56. import com.google.gwt.event.dom.client.ScrollEvent;
  57. import com.google.gwt.event.dom.client.ScrollHandler;
  58. import com.google.gwt.event.logical.shared.CloseEvent;
  59. import com.google.gwt.event.logical.shared.CloseHandler;
  60. import com.google.gwt.event.shared.HandlerRegistration;
  61. import com.google.gwt.user.client.Command;
  62. import com.google.gwt.user.client.DOM;
  63. import com.google.gwt.user.client.Element;
  64. import com.google.gwt.user.client.Event;
  65. import com.google.gwt.user.client.Timer;
  66. import com.google.gwt.user.client.Window;
  67. import com.google.gwt.user.client.ui.FlowPanel;
  68. import com.google.gwt.user.client.ui.HasWidgets;
  69. import com.google.gwt.user.client.ui.Panel;
  70. import com.google.gwt.user.client.ui.PopupPanel;
  71. import com.google.gwt.user.client.ui.RootPanel;
  72. import com.google.gwt.user.client.ui.UIObject;
  73. import com.google.gwt.user.client.ui.Widget;
  74. import com.vaadin.client.ApplicationConnection;
  75. import com.vaadin.client.BrowserInfo;
  76. import com.vaadin.client.ComponentConnector;
  77. import com.vaadin.client.ConnectorMap;
  78. import com.vaadin.client.Focusable;
  79. import com.vaadin.client.MouseEventDetailsBuilder;
  80. import com.vaadin.client.TooltipInfo;
  81. import com.vaadin.client.UIDL;
  82. import com.vaadin.client.Util;
  83. import com.vaadin.client.VConsole;
  84. import com.vaadin.client.VTooltip;
  85. import com.vaadin.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
  86. import com.vaadin.client.ui.dd.DDUtil;
  87. import com.vaadin.client.ui.dd.VAbstractDropHandler;
  88. import com.vaadin.client.ui.dd.VAcceptCallback;
  89. import com.vaadin.client.ui.dd.VDragAndDropManager;
  90. import com.vaadin.client.ui.dd.VDragEvent;
  91. import com.vaadin.client.ui.dd.VHasDropHandler;
  92. import com.vaadin.client.ui.dd.VTransferable;
  93. import com.vaadin.shared.AbstractComponentState;
  94. import com.vaadin.shared.MouseEventDetails;
  95. import com.vaadin.shared.ui.dd.VerticalDropLocation;
  96. import com.vaadin.shared.ui.table.TableConstants;
  97. /**
  98. * VScrollTable
  99. *
  100. * VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
  101. * ScrollPanel
  102. *
  103. * TableHead contains table's header and widgets + logic for resizing,
  104. * reordering and hiding columns.
  105. *
  106. * ScrollPanel contains VScrollTableBody object which handles content. To save
  107. * some bandwidth and to improve clients responsiveness with loads of data, in
  108. * VScrollTableBody all rows are not necessary rendered. There are "spacers" in
  109. * VScrollTableBody to use the exact same space as non-rendered rows would use.
  110. * This way we can use seamlessly traditional scrollbars and scrolling to fetch
  111. * more rows instead of "paging".
  112. *
  113. * In VScrollTable we listen to scroll events. On horizontal scrolling we also
  114. * update TableHeads scroll position which has its scrollbars hidden. On
  115. * vertical scroll events we will check if we are reaching the end of area where
  116. * we have rows rendered and
  117. *
  118. * TODO implement unregistering for child components in Cells
  119. */
  120. public class VScrollTable extends FlowPanel implements HasWidgets,
  121. ScrollHandler, VHasDropHandler, FocusHandler, BlurHandler, Focusable,
  122. ActionOwner {
  123. public static final String STYLENAME = "v-table";
  124. public enum SelectMode {
  125. NONE(0), SINGLE(1), MULTI(2);
  126. private int id;
  127. private SelectMode(int id) {
  128. this.id = id;
  129. }
  130. public int getId() {
  131. return id;
  132. }
  133. }
  134. private static final String ROW_HEADER_COLUMN_KEY = "0";
  135. private static final double CACHE_RATE_DEFAULT = 2;
  136. /**
  137. * The default multi select mode where simple left clicks only selects one
  138. * item, CTRL+left click selects multiple items and SHIFT-left click selects
  139. * a range of items.
  140. */
  141. private static final int MULTISELECT_MODE_DEFAULT = 0;
  142. /**
  143. * The simple multiselect mode is what the table used to have before
  144. * ctrl/shift selections were added. That is that when this is set clicking
  145. * on an item selects/deselects the item and no ctrl/shift selections are
  146. * available.
  147. */
  148. private static final int MULTISELECT_MODE_SIMPLE = 1;
  149. /**
  150. * multiple of pagelength which component will cache when requesting more
  151. * rows
  152. */
  153. private double cache_rate = CACHE_RATE_DEFAULT;
  154. /**
  155. * fraction of pageLenght which can be scrolled without making new request
  156. */
  157. private double cache_react_rate = 0.75 * cache_rate;
  158. public static final char ALIGN_CENTER = 'c';
  159. public static final char ALIGN_LEFT = 'b';
  160. public static final char ALIGN_RIGHT = 'e';
  161. private static final int CHARCODE_SPACE = 32;
  162. private int firstRowInViewPort = 0;
  163. private int pageLength = 15;
  164. private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
  165. /** For internal use only. May be removed or replaced in the future. */
  166. public boolean showRowHeaders = false;
  167. private String[] columnOrder;
  168. protected ApplicationConnection client;
  169. /** For internal use only. May be removed or replaced in the future. */
  170. public String paintableId;
  171. /** For internal use only. May be removed or replaced in the future. */
  172. public boolean immediate;
  173. private boolean nullSelectionAllowed = true;
  174. private SelectMode selectMode = SelectMode.NONE;
  175. public final HashSet<String> selectedRowKeys = new HashSet<String>();
  176. /*
  177. * When scrolling and selecting at the same time, the selections are not in
  178. * sync with the server while retrieving new rows (until key is released).
  179. */
  180. private HashSet<Object> unSyncedselectionsBeforeRowFetch;
  181. /*
  182. * These are used when jumping between pages when pressing Home and End
  183. */
  184. /** For internal use only. May be removed or replaced in the future. */
  185. public boolean selectLastItemInNextRender = false;
  186. /** For internal use only. May be removed or replaced in the future. */
  187. public boolean selectFirstItemInNextRender = false;
  188. /** For internal use only. May be removed or replaced in the future. */
  189. public boolean focusFirstItemInNextRender = false;
  190. /** For internal use only. May be removed or replaced in the future. */
  191. public boolean focusLastItemInNextRender = false;
  192. /**
  193. * The currently focused row.
  194. * <p>
  195. * For internal use only. May be removed or replaced in the future.
  196. */
  197. public VScrollTableRow focusedRow;
  198. /**
  199. * Helper to store selection range start in when using the keyboard
  200. * <p>
  201. * For internal use only. May be removed or replaced in the future.
  202. */
  203. public VScrollTableRow selectionRangeStart;
  204. /**
  205. * Flag for notifying when the selection has changed and should be sent to
  206. * the server
  207. * <p>
  208. * For internal use only. May be removed or replaced in the future.
  209. */
  210. public boolean selectionChanged = false;
  211. /*
  212. * The speed (in pixels) which the scrolling scrolls vertically/horizontally
  213. */
  214. private int scrollingVelocity = 10;
  215. private Timer scrollingVelocityTimer = null;
  216. /** For internal use only. May be removed or replaced in the future. */
  217. public String[] bodyActionKeys;
  218. private boolean enableDebug = false;
  219. private static final boolean hasNativeTouchScrolling = BrowserInfo.get()
  220. .isTouchDevice()
  221. && !BrowserInfo.get().requiresTouchScrollDelegate();
  222. private Set<String> noncollapsibleColumns;
  223. /**
  224. * The last known row height used to preserve the height of a table with
  225. * custom row heights and a fixed page length after removing the last row
  226. * from the table.
  227. *
  228. * A new VScrollTableBody instance is created every time the number of rows
  229. * changes causing {@link VScrollTableBody#rowHeight} to be discarded and
  230. * the height recalculated by {@link VScrollTableBody#getRowHeight(boolean)}
  231. * to avoid some rounding problems, e.g. round(2 * 19.8) / 2 = 20 but
  232. * round(3 * 19.8) / 3 = 19.66.
  233. */
  234. private double lastKnownRowHeight = Double.NaN;
  235. /**
  236. * Remember scroll position when getting detached to properly scroll back to
  237. * the location that there is data for if getting attached again.
  238. */
  239. private int detachedScrollPosition = 0;
  240. /**
  241. * Represents a select range of rows
  242. */
  243. private class SelectionRange {
  244. private VScrollTableRow startRow;
  245. private final int length;
  246. /**
  247. * Constuctor.
  248. */
  249. public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
  250. VScrollTableRow endRow;
  251. if (row2.isBefore(row1)) {
  252. startRow = row2;
  253. endRow = row1;
  254. } else {
  255. startRow = row1;
  256. endRow = row2;
  257. }
  258. length = endRow.getIndex() - startRow.getIndex() + 1;
  259. }
  260. public SelectionRange(VScrollTableRow row, int length) {
  261. startRow = row;
  262. this.length = length;
  263. }
  264. /*
  265. * (non-Javadoc)
  266. *
  267. * @see java.lang.Object#toString()
  268. */
  269. @Override
  270. public String toString() {
  271. return startRow.getKey() + "-" + length;
  272. }
  273. private boolean inRange(VScrollTableRow row) {
  274. return row.getIndex() >= startRow.getIndex()
  275. && row.getIndex() < startRow.getIndex() + length;
  276. }
  277. public Collection<SelectionRange> split(VScrollTableRow row) {
  278. assert row.isAttached();
  279. ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
  280. int endOfFirstRange = row.getIndex() - 1;
  281. if (!(endOfFirstRange - startRow.getIndex() < 0)) {
  282. // create range of first part unless its length is < 1
  283. ranges.add(new SelectionRange(startRow, endOfFirstRange
  284. - startRow.getIndex() + 1));
  285. }
  286. int startOfSecondRange = row.getIndex() + 1;
  287. if (!(getEndIndex() - startOfSecondRange < 0)) {
  288. // create range of second part unless its length is < 1
  289. VScrollTableRow startOfRange = scrollBody
  290. .getRowByRowIndex(startOfSecondRange);
  291. if (startOfRange != null) {
  292. ranges.add(new SelectionRange(startOfRange, getEndIndex()
  293. - startOfSecondRange + 1));
  294. }
  295. }
  296. return ranges;
  297. }
  298. private int getEndIndex() {
  299. return startRow.getIndex() + length - 1;
  300. }
  301. };
  302. private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
  303. /** For internal use only. May be removed or replaced in the future. */
  304. public boolean initializedAndAttached = false;
  305. /**
  306. * Flag to indicate if a column width recalculation is needed due update.
  307. * <p>
  308. * For internal use only. May be removed or replaced in the future.
  309. */
  310. public boolean headerChangedDuringUpdate = false;
  311. /** For internal use only. May be removed or replaced in the future. */
  312. public final TableHead tHead = new TableHead();
  313. /** For internal use only. May be removed or replaced in the future. */
  314. public final TableFooter tFoot = new TableFooter();
  315. /** For internal use only. May be removed or replaced in the future. */
  316. public final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
  317. true);
  318. private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
  319. @Override
  320. public void onKeyPress(KeyPressEvent keyPressEvent) {
  321. // This is used for Firefox only, since Firefox auto-repeat
  322. // works correctly only if we use a key press handler, other
  323. // browsers handle it correctly when using a key down handler
  324. if (!BrowserInfo.get().isGecko()) {
  325. return;
  326. }
  327. NativeEvent event = keyPressEvent.getNativeEvent();
  328. if (!enabled) {
  329. // Cancel default keyboard events on a disabled Table
  330. // (prevents scrolling)
  331. event.preventDefault();
  332. } else if (hasFocus) {
  333. // Key code in Firefox/onKeyPress is present only for
  334. // special keys, otherwise 0 is returned
  335. int keyCode = event.getKeyCode();
  336. if (keyCode == 0 && event.getCharCode() == ' ') {
  337. // Provide a keyCode for space to be compatible with
  338. // FireFox keypress event
  339. keyCode = CHARCODE_SPACE;
  340. }
  341. if (handleNavigation(keyCode,
  342. event.getCtrlKey() || event.getMetaKey(),
  343. event.getShiftKey())) {
  344. event.preventDefault();
  345. }
  346. startScrollingVelocityTimer();
  347. }
  348. }
  349. };
  350. private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
  351. @Override
  352. public void onKeyUp(KeyUpEvent keyUpEvent) {
  353. NativeEvent event = keyUpEvent.getNativeEvent();
  354. int keyCode = event.getKeyCode();
  355. if (!isFocusable()) {
  356. cancelScrollingVelocityTimer();
  357. } else if (isNavigationKey(keyCode)) {
  358. if (keyCode == getNavigationDownKey()
  359. || keyCode == getNavigationUpKey()) {
  360. /*
  361. * in multiselect mode the server may still have value from
  362. * previous page. Clear it unless doing multiselection or
  363. * just moving focus.
  364. */
  365. if (!event.getShiftKey() && !event.getCtrlKey()) {
  366. instructServerToForgetPreviousSelections();
  367. }
  368. sendSelectedRows();
  369. }
  370. cancelScrollingVelocityTimer();
  371. navKeyDown = false;
  372. }
  373. }
  374. };
  375. private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
  376. @Override
  377. public void onKeyDown(KeyDownEvent keyDownEvent) {
  378. NativeEvent event = keyDownEvent.getNativeEvent();
  379. // This is not used for Firefox
  380. if (BrowserInfo.get().isGecko()) {
  381. return;
  382. }
  383. if (!enabled) {
  384. // Cancel default keyboard events on a disabled Table
  385. // (prevents scrolling)
  386. event.preventDefault();
  387. } else if (hasFocus) {
  388. if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
  389. || event.getMetaKey(), event.getShiftKey())) {
  390. navKeyDown = true;
  391. event.preventDefault();
  392. }
  393. startScrollingVelocityTimer();
  394. }
  395. }
  396. };
  397. /** For internal use only. May be removed or replaced in the future. */
  398. public int totalRows;
  399. private Set<String> collapsedColumns;
  400. /** For internal use only. May be removed or replaced in the future. */
  401. public final RowRequestHandler rowRequestHandler;
  402. /** For internal use only. May be removed or replaced in the future. */
  403. public VScrollTableBody scrollBody;
  404. private int firstvisible = 0;
  405. private boolean sortAscending;
  406. private String sortColumn;
  407. private String oldSortColumn;
  408. private boolean columnReordering;
  409. /**
  410. * This map contains captions and icon urls for actions like: * "33_c" ->
  411. * "Edit" * "33_i" -> "http://dom.com/edit.png"
  412. */
  413. private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
  414. private String[] visibleColOrder;
  415. private boolean initialContentReceived = false;
  416. private Element scrollPositionElement;
  417. /** For internal use only. May be removed or replaced in the future. */
  418. public boolean enabled;
  419. /** For internal use only. May be removed or replaced in the future. */
  420. public boolean showColHeaders;
  421. /** For internal use only. May be removed or replaced in the future. */
  422. public boolean showColFooters;
  423. /** flag to indicate that table body has changed */
  424. private boolean isNewBody = true;
  425. /**
  426. * Read from the "recalcWidths" -attribute. When it is true, the table will
  427. * recalculate the widths for columns - desirable in some cases. For #1983,
  428. * marked experimental. See also variable <code>refreshContentWidths</code>
  429. * in method {@link TableHead#updateCellsFromUIDL(UIDL)}.
  430. * <p>
  431. * For internal use only. May be removed or replaced in the future.
  432. */
  433. public boolean recalcWidths = false;
  434. /** For internal use only. May be removed or replaced in the future. */
  435. public boolean rendering = false;
  436. private boolean hasFocus = false;
  437. private int dragmode;
  438. private int multiselectmode;
  439. /** For internal use only. May be removed or replaced in the future. */
  440. public int tabIndex;
  441. private TouchScrollDelegate touchScrollDelegate;
  442. /** For internal use only. May be removed or replaced in the future. */
  443. public int lastRenderedHeight;
  444. /**
  445. * Values (serverCacheFirst+serverCacheLast) sent by server that tells which
  446. * rows (indexes) are in the server side cache (page buffer). -1 means
  447. * unknown. The server side cache row MUST MATCH the client side cache rows.
  448. *
  449. * If the client side cache contains additional rows with e.g. buttons, it
  450. * will cause out of sync when such a button is pressed.
  451. *
  452. * If the server side cache contains additional rows with e.g. buttons,
  453. * scrolling in the client will cause empty buttons to be rendered
  454. * (cached=true request for non-existing components)
  455. *
  456. * For internal use only. May be removed or replaced in the future.
  457. */
  458. public int serverCacheFirst = -1;
  459. public int serverCacheLast = -1;
  460. /**
  461. * In several cases TreeTable depends on the scrollBody.lastRendered being
  462. * 'out of sync' while the update is being done. In those cases the sanity
  463. * check must be performed afterwards.
  464. */
  465. public boolean postponeSanityCheckForLastRendered;
  466. /** For internal use only. May be removed or replaced in the future. */
  467. public boolean sizeNeedsInit = true;
  468. /**
  469. * Used to recall the position of an open context menu if we need to close
  470. * and reopen it during a row update.
  471. * <p>
  472. * For internal use only. May be removed or replaced in the future.
  473. */
  474. public class ContextMenuDetails implements CloseHandler<PopupPanel> {
  475. public String rowKey;
  476. public int left;
  477. public int top;
  478. HandlerRegistration closeRegistration;
  479. public ContextMenuDetails(VContextMenu menu, String rowKey, int left,
  480. int top) {
  481. this.rowKey = rowKey;
  482. this.left = left;
  483. this.top = top;
  484. closeRegistration = menu.addCloseHandler(this);
  485. }
  486. @Override
  487. public void onClose(CloseEvent<PopupPanel> event) {
  488. contextMenu = null;
  489. closeRegistration.removeHandler();
  490. }
  491. }
  492. /** For internal use only. May be removed or replaced in the future. */
  493. public ContextMenuDetails contextMenu = null;
  494. private boolean hadScrollBars = false;
  495. public VScrollTable() {
  496. setMultiSelectMode(MULTISELECT_MODE_DEFAULT);
  497. scrollBodyPanel.addFocusHandler(this);
  498. scrollBodyPanel.addBlurHandler(this);
  499. scrollBodyPanel.addScrollHandler(this);
  500. /*
  501. * Firefox auto-repeat works correctly only if we use a key press
  502. * handler, other browsers handle it correctly when using a key down
  503. * handler
  504. */
  505. if (BrowserInfo.get().isGecko()) {
  506. scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
  507. } else {
  508. scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
  509. }
  510. scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
  511. scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
  512. scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
  513. scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
  514. @Override
  515. public void onContextMenu(ContextMenuEvent event) {
  516. handleBodyContextMenu(event);
  517. }
  518. }, ContextMenuEvent.getType());
  519. setStyleName(STYLENAME);
  520. add(tHead);
  521. add(scrollBodyPanel);
  522. add(tFoot);
  523. rowRequestHandler = new RowRequestHandler();
  524. }
  525. @Override
  526. public void setStyleName(String style) {
  527. updateStyleNames(style, false);
  528. }
  529. @Override
  530. public void setStylePrimaryName(String style) {
  531. updateStyleNames(style, true);
  532. }
  533. private void updateStyleNames(String newStyle, boolean isPrimary) {
  534. scrollBodyPanel
  535. .removeStyleName(getStylePrimaryName() + "-body-wrapper");
  536. scrollBodyPanel.removeStyleName(getStylePrimaryName() + "-body");
  537. if (scrollBody != null) {
  538. scrollBody.removeStyleName(getStylePrimaryName()
  539. + "-body-noselection");
  540. }
  541. if (isPrimary) {
  542. super.setStylePrimaryName(newStyle);
  543. } else {
  544. super.setStyleName(newStyle);
  545. }
  546. scrollBodyPanel.addStyleName(getStylePrimaryName() + "-body-wrapper");
  547. scrollBodyPanel.addStyleName(getStylePrimaryName() + "-body");
  548. tHead.updateStyleNames(getStylePrimaryName());
  549. tFoot.updateStyleNames(getStylePrimaryName());
  550. if (scrollBody != null) {
  551. scrollBody.updateStyleNames(getStylePrimaryName());
  552. }
  553. }
  554. public void init(ApplicationConnection client) {
  555. this.client = client;
  556. // Add a handler to clear saved context menu details when the menu
  557. // closes. See #8526.
  558. client.getContextMenu().addCloseHandler(new CloseHandler<PopupPanel>() {
  559. @Override
  560. public void onClose(CloseEvent<PopupPanel> event) {
  561. contextMenu = null;
  562. }
  563. });
  564. }
  565. private void handleBodyContextMenu(ContextMenuEvent event) {
  566. if (enabled && bodyActionKeys != null) {
  567. int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
  568. int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
  569. top += Window.getScrollTop();
  570. left += Window.getScrollLeft();
  571. client.getContextMenu().showAt(this, left, top);
  572. // Only prevent browser context menu if there are action handlers
  573. // registered
  574. event.stopPropagation();
  575. event.preventDefault();
  576. }
  577. }
  578. /**
  579. * Fires a column resize event which sends the resize information to the
  580. * server.
  581. *
  582. * @param columnId
  583. * The columnId of the column which was resized
  584. * @param originalWidth
  585. * The width in pixels of the column before the resize event
  586. * @param newWidth
  587. * The width in pixels of the column after the resize event
  588. */
  589. private void fireColumnResizeEvent(String columnId, int originalWidth,
  590. int newWidth) {
  591. client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
  592. false);
  593. client.updateVariable(paintableId, "columnResizeEventPrev",
  594. originalWidth, false);
  595. client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
  596. immediate);
  597. }
  598. /**
  599. * Non-immediate variable update of column widths for a collection of
  600. * columns.
  601. *
  602. * @param columns
  603. * the columns to trigger the events for.
  604. */
  605. private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
  606. String[] newSizes = new String[columns.size()];
  607. int ix = 0;
  608. for (HeaderCell cell : columns) {
  609. newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
  610. }
  611. client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
  612. false);
  613. }
  614. /**
  615. * Moves the focus one step down
  616. *
  617. * @return Returns true if succeeded
  618. */
  619. private boolean moveFocusDown() {
  620. return moveFocusDown(0);
  621. }
  622. /**
  623. * Moves the focus down by 1+offset rows
  624. *
  625. * @return Returns true if succeeded, else false if the selection could not
  626. * be move downwards
  627. */
  628. private boolean moveFocusDown(int offset) {
  629. if (isSelectable()) {
  630. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  631. // FIXME should focus first visible from top, not first rendered
  632. // ??
  633. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  634. .next());
  635. } else {
  636. VScrollTableRow next = getNextRow(focusedRow, offset);
  637. if (next != null) {
  638. return setRowFocus(next);
  639. }
  640. }
  641. }
  642. return false;
  643. }
  644. /**
  645. * Moves the selection one step up
  646. *
  647. * @return Returns true if succeeded
  648. */
  649. private boolean moveFocusUp() {
  650. return moveFocusUp(0);
  651. }
  652. /**
  653. * Moves the focus row upwards
  654. *
  655. * @return Returns true if succeeded, else false if the selection could not
  656. * be move upwards
  657. *
  658. */
  659. private boolean moveFocusUp(int offset) {
  660. if (isSelectable()) {
  661. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  662. // FIXME logic is exactly the same as in moveFocusDown, should
  663. // be the opposite??
  664. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  665. .next());
  666. } else {
  667. VScrollTableRow prev = getPreviousRow(focusedRow, offset);
  668. if (prev != null) {
  669. return setRowFocus(prev);
  670. } else {
  671. VConsole.log("no previous available");
  672. }
  673. }
  674. }
  675. return false;
  676. }
  677. /**
  678. * Selects a row where the current selection head is
  679. *
  680. * @param ctrlSelect
  681. * Is the selection a ctrl+selection
  682. * @param shiftSelect
  683. * Is the selection a shift+selection
  684. * @return Returns truw
  685. */
  686. private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
  687. if (focusedRow != null) {
  688. // Arrows moves the selection and clears previous selections
  689. if (isSelectable() && !ctrlSelect && !shiftSelect) {
  690. deselectAll();
  691. focusedRow.toggleSelection();
  692. selectionRangeStart = focusedRow;
  693. } else if (isSelectable() && ctrlSelect && !shiftSelect) {
  694. // Ctrl+arrows moves selection head
  695. selectionRangeStart = focusedRow;
  696. // No selection, only selection head is moved
  697. } else if (isMultiSelectModeAny() && !ctrlSelect && shiftSelect) {
  698. // Shift+arrows selection selects a range
  699. focusedRow.toggleShiftSelection(shiftSelect);
  700. }
  701. }
  702. }
  703. /**
  704. * Sends the selection to the server if changed since the last update/visit.
  705. */
  706. protected void sendSelectedRows() {
  707. sendSelectedRows(immediate);
  708. }
  709. /**
  710. * Sends the selection to the server if it has been changed since the last
  711. * update/visit.
  712. *
  713. * @param immediately
  714. * set to true to immediately send the rows
  715. */
  716. protected void sendSelectedRows(boolean immediately) {
  717. // Don't send anything if selection has not changed
  718. if (!selectionChanged) {
  719. return;
  720. }
  721. // Reset selection changed flag
  722. selectionChanged = false;
  723. // Note: changing the immediateness of this might require changes to
  724. // "clickEvent" immediateness also.
  725. if (isMultiSelectModeDefault()) {
  726. // Convert ranges to a set of strings
  727. Set<String> ranges = new HashSet<String>();
  728. for (SelectionRange range : selectedRowRanges) {
  729. ranges.add(range.toString());
  730. }
  731. // Send the selected row ranges
  732. client.updateVariable(paintableId, "selectedRanges",
  733. ranges.toArray(new String[selectedRowRanges.size()]), false);
  734. // clean selectedRowKeys so that they don't contain excess values
  735. for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
  736. .hasNext();) {
  737. String key = iterator.next();
  738. VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
  739. if (renderedRowByKey != null) {
  740. for (SelectionRange range : selectedRowRanges) {
  741. if (range.inRange(renderedRowByKey)) {
  742. iterator.remove();
  743. }
  744. }
  745. } else {
  746. // orphaned selected key, must be in a range, ignore
  747. iterator.remove();
  748. }
  749. }
  750. }
  751. // Send the selected rows
  752. client.updateVariable(paintableId, "selected",
  753. selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
  754. immediately);
  755. }
  756. /**
  757. * Get the key that moves the selection head upwards. By default it is the
  758. * up arrow key but by overriding this you can change the key to whatever
  759. * you want.
  760. *
  761. * @return The keycode of the key
  762. */
  763. protected int getNavigationUpKey() {
  764. return KeyCodes.KEY_UP;
  765. }
  766. /**
  767. * Get the key that moves the selection head downwards. By default it is the
  768. * down arrow key but by overriding this you can change the key to whatever
  769. * you want.
  770. *
  771. * @return The keycode of the key
  772. */
  773. protected int getNavigationDownKey() {
  774. return KeyCodes.KEY_DOWN;
  775. }
  776. /**
  777. * Get the key that scrolls to the left in the table. By default it is the
  778. * left arrow key but by overriding this you can change the key to whatever
  779. * you want.
  780. *
  781. * @return The keycode of the key
  782. */
  783. protected int getNavigationLeftKey() {
  784. return KeyCodes.KEY_LEFT;
  785. }
  786. /**
  787. * Get the key that scroll to the right on the table. By default it is the
  788. * right arrow key but by overriding this you can change the key to whatever
  789. * you want.
  790. *
  791. * @return The keycode of the key
  792. */
  793. protected int getNavigationRightKey() {
  794. return KeyCodes.KEY_RIGHT;
  795. }
  796. /**
  797. * Get the key that selects an item in the table. By default it is the space
  798. * bar key but by overriding this you can change the key to whatever you
  799. * want.
  800. *
  801. * @return
  802. */
  803. protected int getNavigationSelectKey() {
  804. return CHARCODE_SPACE;
  805. }
  806. /**
  807. * Get the key the moves the selection one page up in the table. By default
  808. * this is the Page Up key but by overriding this you can change the key to
  809. * whatever you want.
  810. *
  811. * @return
  812. */
  813. protected int getNavigationPageUpKey() {
  814. return KeyCodes.KEY_PAGEUP;
  815. }
  816. /**
  817. * Get the key the moves the selection one page down in the table. By
  818. * default this is the Page Down key but by overriding this you can change
  819. * the key to whatever you want.
  820. *
  821. * @return
  822. */
  823. protected int getNavigationPageDownKey() {
  824. return KeyCodes.KEY_PAGEDOWN;
  825. }
  826. /**
  827. * Get the key the moves the selection to the beginning of the table. By
  828. * default this is the Home key but by overriding this you can change the
  829. * key to whatever you want.
  830. *
  831. * @return
  832. */
  833. protected int getNavigationStartKey() {
  834. return KeyCodes.KEY_HOME;
  835. }
  836. /**
  837. * Get the key the moves the selection to the end of the table. By default
  838. * this is the End key but by overriding this you can change the key to
  839. * whatever you want.
  840. *
  841. * @return
  842. */
  843. protected int getNavigationEndKey() {
  844. return KeyCodes.KEY_END;
  845. }
  846. /** For internal use only. May be removed or replaced in the future. */
  847. public void initializeRows(UIDL uidl, UIDL rowData) {
  848. if (scrollBody != null) {
  849. scrollBody.removeFromParent();
  850. }
  851. scrollBody = createScrollBody();
  852. scrollBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"),
  853. uidl.getIntAttribute("rows"));
  854. scrollBodyPanel.add(scrollBody);
  855. // New body starts scrolled to the left, make sure the header and footer
  856. // are also scrolled to the left
  857. tHead.setHorizontalScrollPosition(0);
  858. tFoot.setHorizontalScrollPosition(0);
  859. initialContentReceived = true;
  860. sizeNeedsInit = true;
  861. scrollBody.restoreRowVisibility();
  862. }
  863. /** For internal use only. May be removed or replaced in the future. */
  864. public void updateColumnProperties(UIDL uidl) {
  865. updateColumnOrder(uidl);
  866. updateCollapsedColumns(uidl);
  867. UIDL vc = uidl.getChildByTagName("visiblecolumns");
  868. if (vc != null) {
  869. tHead.updateCellsFromUIDL(vc);
  870. tFoot.updateCellsFromUIDL(vc);
  871. }
  872. updateHeader(uidl.getStringArrayAttribute("vcolorder"));
  873. updateFooter(uidl.getStringArrayAttribute("vcolorder"));
  874. if (uidl.hasVariable("noncollapsiblecolumns")) {
  875. noncollapsibleColumns = uidl
  876. .getStringArrayVariableAsSet("noncollapsiblecolumns");
  877. }
  878. }
  879. private void updateCollapsedColumns(UIDL uidl) {
  880. if (uidl.hasVariable("collapsedcolumns")) {
  881. tHead.setColumnCollapsingAllowed(true);
  882. collapsedColumns = uidl
  883. .getStringArrayVariableAsSet("collapsedcolumns");
  884. } else {
  885. tHead.setColumnCollapsingAllowed(false);
  886. }
  887. }
  888. private void updateColumnOrder(UIDL uidl) {
  889. if (uidl.hasVariable("columnorder")) {
  890. columnReordering = true;
  891. columnOrder = uidl.getStringArrayVariable("columnorder");
  892. } else {
  893. columnReordering = false;
  894. columnOrder = null;
  895. }
  896. }
  897. /** For internal use only. May be removed or replaced in the future. */
  898. public boolean selectSelectedRows(UIDL uidl) {
  899. boolean keyboardSelectionOverRowFetchInProgress = false;
  900. if (uidl.hasVariable("selected")) {
  901. final Set<String> selectedKeys = uidl
  902. .getStringArrayVariableAsSet("selected");
  903. if (scrollBody != null) {
  904. Iterator<Widget> iterator = scrollBody.iterator();
  905. while (iterator.hasNext()) {
  906. /*
  907. * Make the focus reflect to the server side state unless we
  908. * are currently selecting multiple rows with keyboard.
  909. */
  910. VScrollTableRow row = (VScrollTableRow) iterator.next();
  911. boolean selected = selectedKeys.contains(row.getKey());
  912. if (!selected
  913. && unSyncedselectionsBeforeRowFetch != null
  914. && unSyncedselectionsBeforeRowFetch.contains(row
  915. .getKey())) {
  916. selected = true;
  917. keyboardSelectionOverRowFetchInProgress = true;
  918. }
  919. if (selected != row.isSelected()) {
  920. row.toggleSelection();
  921. if (!isSingleSelectMode() && !selected) {
  922. // Update selection range in case a row is
  923. // unselected from the middle of a range - #8076
  924. removeRowFromUnsentSelectionRanges(row);
  925. }
  926. }
  927. }
  928. }
  929. }
  930. unSyncedselectionsBeforeRowFetch = null;
  931. return keyboardSelectionOverRowFetchInProgress;
  932. }
  933. /** For internal use only. May be removed or replaced in the future. */
  934. public void updateSortingProperties(UIDL uidl) {
  935. oldSortColumn = sortColumn;
  936. if (uidl.hasVariable("sortascending")) {
  937. sortAscending = uidl.getBooleanVariable("sortascending");
  938. sortColumn = uidl.getStringVariable("sortcolumn");
  939. }
  940. }
  941. /** For internal use only. May be removed or replaced in the future. */
  942. public void resizeSortedColumnForSortIndicator() {
  943. // Force recalculation of the captionContainer element inside the header
  944. // cell to accomodate for the size of the sort arrow.
  945. HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
  946. if (sortedHeader != null) {
  947. tHead.resizeCaptionContainer(sortedHeader);
  948. }
  949. // Also recalculate the width of the captionContainer element in the
  950. // previously sorted header, since this now has more room.
  951. HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
  952. if (oldSortedHeader != null) {
  953. tHead.resizeCaptionContainer(oldSortedHeader);
  954. }
  955. }
  956. private ScheduledCommand lazyScroller = new ScheduledCommand() {
  957. @Override
  958. public void execute() {
  959. int offsetTop = measureRowHeightOffset(firstvisible);
  960. scrollBodyPanel.setScrollPosition(offsetTop);
  961. }
  962. };
  963. /** For internal use only. May be removed or replaced in the future. */
  964. public void updateFirstVisibleAndScrollIfNeeded(UIDL uidl) {
  965. firstvisible = uidl.hasVariable("firstvisible") ? uidl
  966. .getIntVariable("firstvisible") : 0;
  967. if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
  968. // received 'surprising' firstvisible from server: scroll there
  969. firstRowInViewPort = firstvisible;
  970. /*
  971. * Schedule the scrolling to be executed last so no updates to the
  972. * rows affect scrolling measurements.
  973. */
  974. Scheduler.get().scheduleFinally(lazyScroller);
  975. }
  976. }
  977. protected int measureRowHeightOffset(int rowIx) {
  978. return (int) (rowIx * scrollBody.getRowHeight());
  979. }
  980. /** For internal use only. May be removed or replaced in the future. */
  981. public void updatePageLength(UIDL uidl) {
  982. int oldPageLength = pageLength;
  983. if (uidl.hasAttribute("pagelength")) {
  984. pageLength = uidl.getIntAttribute("pagelength");
  985. } else {
  986. // pagelenght is "0" meaning scrolling is turned off
  987. pageLength = totalRows;
  988. }
  989. if (oldPageLength != pageLength && initializedAndAttached) {
  990. // page length changed, need to update size
  991. sizeNeedsInit = true;
  992. }
  993. }
  994. /** For internal use only. May be removed or replaced in the future. */
  995. public void updateSelectionProperties(UIDL uidl,
  996. AbstractComponentState state, boolean readOnly) {
  997. setMultiSelectMode(uidl.hasAttribute("multiselectmode") ? uidl
  998. .getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT);
  999. nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
  1000. .getBooleanAttribute("nsa") : true;
  1001. if (uidl.hasAttribute("selectmode")) {
  1002. if (readOnly) {
  1003. selectMode = SelectMode.NONE;
  1004. } else if (uidl.getStringAttribute("selectmode").equals("multi")) {
  1005. selectMode = SelectMode.MULTI;
  1006. } else if (uidl.getStringAttribute("selectmode").equals("single")) {
  1007. selectMode = SelectMode.SINGLE;
  1008. } else {
  1009. selectMode = SelectMode.NONE;
  1010. }
  1011. }
  1012. }
  1013. /** For internal use only. May be removed or replaced in the future. */
  1014. public void updateDragMode(UIDL uidl) {
  1015. dragmode = uidl.hasAttribute("dragmode") ? uidl
  1016. .getIntAttribute("dragmode") : 0;
  1017. if (BrowserInfo.get().isIE()) {
  1018. if (dragmode > 0) {
  1019. getElement().setPropertyJSO("onselectstart",
  1020. getPreventTextSelectionIEHack());
  1021. } else {
  1022. getElement().setPropertyJSO("onselectstart", null);
  1023. }
  1024. }
  1025. }
  1026. /** For internal use only. May be removed or replaced in the future. */
  1027. public void updateTotalRows(UIDL uidl) {
  1028. int newTotalRows = uidl.getIntAttribute("totalrows");
  1029. if (newTotalRows != getTotalRows()) {
  1030. if (scrollBody != null) {
  1031. if (getTotalRows() == 0) {
  1032. tHead.clear();
  1033. tFoot.clear();
  1034. }
  1035. initializedAndAttached = false;
  1036. initialContentReceived = false;
  1037. isNewBody = true;
  1038. }
  1039. setTotalRows(newTotalRows);
  1040. }
  1041. }
  1042. protected void setTotalRows(int newTotalRows) {
  1043. totalRows = newTotalRows;
  1044. }
  1045. public int getTotalRows() {
  1046. return totalRows;
  1047. }
  1048. /**
  1049. * Returns the extra space that is given to the header column when column
  1050. * width is determined by header text.
  1051. *
  1052. * @return extra space in pixels
  1053. */
  1054. private int getHeaderPadding() {
  1055. return scrollBody.getCellExtraWidth();
  1056. }
  1057. /**
  1058. * This method exists for the needs of {@link VTreeTable} only. Not part of
  1059. * the official API, <b>extend at your own risk</b>. May be removed or
  1060. * replaced in the future.
  1061. *
  1062. * @return index of TreeTable's hierarchy column, or -1 if not applicable
  1063. */
  1064. protected int getHierarchyColumnIndex() {
  1065. return -1;
  1066. }
  1067. /**
  1068. * For internal use only. May be removed or replaced in the future.
  1069. */
  1070. public void updateMaxIndent() {
  1071. int oldIndent = scrollBody.getMaxIndent();
  1072. scrollBody.calculateMaxIndent();
  1073. if (oldIndent != scrollBody.getMaxIndent()) {
  1074. // indent updated, headers might need adjusting
  1075. triggerLazyColumnAdjustment(true);
  1076. }
  1077. }
  1078. /** For internal use only. May be removed or replaced in the future. */
  1079. public void focusRowFromBody() {
  1080. if (selectedRowKeys.size() == 1) {
  1081. // try to focus a row currently selected and in viewport
  1082. String selectedRowKey = selectedRowKeys.iterator().next();
  1083. if (selectedRowKey != null) {
  1084. VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
  1085. if (renderedRow == null || !renderedRow.isInViewPort()) {
  1086. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1087. } else {
  1088. setRowFocus(renderedRow);
  1089. }
  1090. }
  1091. } else {
  1092. // multiselect mode
  1093. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1094. }
  1095. }
  1096. protected VScrollTableBody createScrollBody() {
  1097. return new VScrollTableBody();
  1098. }
  1099. /**
  1100. * Selects the last row visible in the table
  1101. * <p>
  1102. * For internal use only. May be removed or replaced in the future.
  1103. *
  1104. * @param focusOnly
  1105. * Should the focus only be moved to the last row
  1106. */
  1107. public void selectLastRenderedRowInViewPort(boolean focusOnly) {
  1108. int index = firstRowInViewPort + getFullyVisibleRowCount();
  1109. VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
  1110. if (lastRowInViewport == null) {
  1111. // this should not happen in normal situations (white space at the
  1112. // end of viewport). Select the last rendered as a fallback.
  1113. lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
  1114. .getLastRendered());
  1115. if (lastRowInViewport == null) {
  1116. return; // empty table
  1117. }
  1118. }
  1119. setRowFocus(lastRowInViewport);
  1120. if (!focusOnly) {
  1121. selectFocusedRow(false, multiselectPending);
  1122. sendSelectedRows();
  1123. }
  1124. }
  1125. /**
  1126. * Selects the first row visible in the table
  1127. * <p>
  1128. * For internal use only. May be removed or replaced in the future.
  1129. *
  1130. * @param focusOnly
  1131. * Should the focus only be moved to the first row
  1132. */
  1133. public void selectFirstRenderedRowInViewPort(boolean focusOnly) {
  1134. int index = firstRowInViewPort;
  1135. VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
  1136. if (firstInViewport == null) {
  1137. // this should not happen in normal situations
  1138. return;
  1139. }
  1140. setRowFocus(firstInViewport);
  1141. if (!focusOnly) {
  1142. selectFocusedRow(false, multiselectPending);
  1143. sendSelectedRows();
  1144. }
  1145. }
  1146. /** For internal use only. May be removed or replaced in the future. */
  1147. public void setCacheRateFromUIDL(UIDL uidl) {
  1148. setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
  1149. : CACHE_RATE_DEFAULT);
  1150. }
  1151. private void setCacheRate(double d) {
  1152. if (cache_rate != d) {
  1153. cache_rate = d;
  1154. cache_react_rate = 0.75 * d;
  1155. }
  1156. }
  1157. /** For internal use only. May be removed or replaced in the future. */
  1158. public void updateActionMap(UIDL mainUidl) {
  1159. UIDL actionsUidl = mainUidl.getChildByTagName("actions");
  1160. if (actionsUidl == null) {
  1161. return;
  1162. }
  1163. final Iterator<?> it = actionsUidl.getChildIterator();
  1164. while (it.hasNext()) {
  1165. final UIDL action = (UIDL) it.next();
  1166. final String key = action.getStringAttribute("key");
  1167. final String caption = action.getStringAttribute("caption");
  1168. actionMap.put(key + "_c", caption);
  1169. if (action.hasAttribute("icon")) {
  1170. // TODO need some uri handling ??
  1171. actionMap.put(key + "_i", client.translateVaadinUri(action
  1172. .getStringAttribute("icon")));
  1173. } else {
  1174. actionMap.remove(key + "_i");
  1175. }
  1176. }
  1177. }
  1178. public String getActionCaption(String actionKey) {
  1179. return actionMap.get(actionKey + "_c");
  1180. }
  1181. public String getActionIcon(String actionKey) {
  1182. return actionMap.get(actionKey + "_i");
  1183. }
  1184. private void updateHeader(String[] strings) {
  1185. if (strings == null) {
  1186. return;
  1187. }
  1188. int visibleCols = strings.length;
  1189. int colIndex = 0;
  1190. if (showRowHeaders) {
  1191. tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1192. visibleCols++;
  1193. visibleColOrder = new String[visibleCols];
  1194. visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
  1195. colIndex++;
  1196. } else {
  1197. visibleColOrder = new String[visibleCols];
  1198. tHead.removeCell(ROW_HEADER_COLUMN_KEY);
  1199. }
  1200. int i;
  1201. for (i = 0; i < strings.length; i++) {
  1202. final String cid = strings[i];
  1203. visibleColOrder[colIndex] = cid;
  1204. tHead.enableColumn(cid, colIndex);
  1205. colIndex++;
  1206. }
  1207. tHead.setVisible(showColHeaders);
  1208. setContainerHeight();
  1209. }
  1210. /**
  1211. * Updates footers.
  1212. * <p>
  1213. * Update headers whould be called before this method is called!
  1214. * </p>
  1215. *
  1216. * @param strings
  1217. */
  1218. private void updateFooter(String[] strings) {
  1219. if (strings == null) {
  1220. return;
  1221. }
  1222. // Add dummy column if row headers are present
  1223. int colIndex = 0;
  1224. if (showRowHeaders) {
  1225. tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1226. colIndex++;
  1227. } else {
  1228. tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
  1229. }
  1230. int i;
  1231. for (i = 0; i < strings.length; i++) {
  1232. final String cid = strings[i];
  1233. tFoot.enableColumn(cid, colIndex);
  1234. colIndex++;
  1235. }
  1236. tFoot.setVisible(showColFooters);
  1237. }
  1238. /**
  1239. * For internal use only. May be removed or replaced in the future.
  1240. *
  1241. * @param uidl
  1242. * which contains row data
  1243. * @param firstRow
  1244. * first row in data set
  1245. * @param reqRows
  1246. * amount of rows in data set
  1247. */
  1248. public void updateBody(UIDL uidl, int firstRow, int reqRows) {
  1249. int oldIndent = scrollBody.getMaxIndent();
  1250. if (uidl == null || reqRows < 1) {
  1251. // container is empty, remove possibly existing rows
  1252. if (firstRow <= 0) {
  1253. postponeSanityCheckForLastRendered = true;
  1254. while (scrollBody.getLastRendered() > scrollBody
  1255. .getFirstRendered()) {
  1256. scrollBody.unlinkRow(false);
  1257. }
  1258. postponeSanityCheckForLastRendered = false;
  1259. scrollBody.unlinkRow(false);
  1260. }
  1261. return;
  1262. }
  1263. scrollBody.renderRows(uidl, firstRow, reqRows);
  1264. discardRowsOutsideCacheWindow();
  1265. scrollBody.calculateMaxIndent();
  1266. if (oldIndent != scrollBody.getMaxIndent()) {
  1267. // indent updated, headers might need adjusting
  1268. headerChangedDuringUpdate = true;
  1269. }
  1270. }
  1271. /** For internal use only. May be removed or replaced in the future. */
  1272. public void updateRowsInBody(UIDL partialRowUpdates) {
  1273. if (partialRowUpdates == null) {
  1274. return;
  1275. }
  1276. int firstRowIx = partialRowUpdates.getIntAttribute("firsturowix");
  1277. int count = partialRowUpdates.getIntAttribute("numurows");
  1278. scrollBody.unlinkRows(firstRowIx, count);
  1279. scrollBody.insertRows(partialRowUpdates, firstRowIx, count);
  1280. }
  1281. /**
  1282. * Updates the internal cache by unlinking rows that fall outside of the
  1283. * caching window.
  1284. */
  1285. protected void discardRowsOutsideCacheWindow() {
  1286. int firstRowToKeep = (int) (firstRowInViewPort - pageLength
  1287. * cache_rate);
  1288. int lastRowToKeep = (int) (firstRowInViewPort + pageLength + pageLength
  1289. * cache_rate);
  1290. // sanity checks:
  1291. if (firstRowToKeep < 0) {
  1292. firstRowToKeep = 0;
  1293. }
  1294. if (lastRowToKeep > totalRows) {
  1295. lastRowToKeep = totalRows - 1;
  1296. }
  1297. debug("Client side calculated cache rows to keep: " + firstRowToKeep
  1298. + "-" + lastRowToKeep);
  1299. if (serverCacheFirst != -1) {
  1300. firstRowToKeep = serverCacheFirst;
  1301. lastRowToKeep = serverCacheLast;
  1302. debug("Server cache rows that override: " + serverCacheFirst + "-"
  1303. + serverCacheLast);
  1304. if (firstRowToKeep < scrollBody.getFirstRendered()
  1305. || lastRowToKeep > scrollBody.getLastRendered()) {
  1306. debug("*** Server wants us to keep " + serverCacheFirst + "-"
  1307. + serverCacheLast + " but we only have rows "
  1308. + scrollBody.getFirstRendered() + "-"
  1309. + scrollBody.getLastRendered() + " rendered!");
  1310. }
  1311. }
  1312. discardRowsOutsideOf(firstRowToKeep, lastRowToKeep);
  1313. scrollBody.fixSpacers();
  1314. scrollBody.restoreRowVisibility();
  1315. }
  1316. private void discardRowsOutsideOf(int optimalFirstRow, int optimalLastRow) {
  1317. /*
  1318. * firstDiscarded and lastDiscarded are only calculated for debug
  1319. * purposes
  1320. */
  1321. int firstDiscarded = -1, lastDiscarded = -1;
  1322. boolean cont = true;
  1323. while (cont && scrollBody.getLastRendered() > optimalFirstRow
  1324. && scrollBody.getFirstRendered() < optimalFirstRow) {
  1325. if (firstDiscarded == -1) {
  1326. firstDiscarded = scrollBody.getFirstRendered();
  1327. }
  1328. // removing row from start
  1329. cont = scrollBody.unlinkRow(true);
  1330. }
  1331. if (firstDiscarded != -1) {
  1332. lastDiscarded = scrollBody.getFirstRendered() - 1;
  1333. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1334. }
  1335. firstDiscarded = lastDiscarded = -1;
  1336. cont = true;
  1337. while (cont && scrollBody.getLastRendered() > optimalLastRow) {
  1338. if (lastDiscarded == -1) {
  1339. lastDiscarded = scrollBody.getLastRendered();
  1340. }
  1341. // removing row from the end
  1342. cont = scrollBody.unlinkRow(false);
  1343. }
  1344. if (lastDiscarded != -1) {
  1345. firstDiscarded = scrollBody.getLastRendered() + 1;
  1346. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1347. }
  1348. debug("Now in cache: " + scrollBody.getFirstRendered() + "-"
  1349. + scrollBody.getLastRendered());
  1350. }
  1351. /**
  1352. * Inserts rows in the table body or removes them from the table body based
  1353. * on the commands in the UIDL.
  1354. * <p>
  1355. * For internal use only. May be removed or replaced in the future.
  1356. *
  1357. * @param partialRowAdditions
  1358. * the UIDL containing row updates.
  1359. */
  1360. public void addAndRemoveRows(UIDL partialRowAdditions) {
  1361. if (partialRowAdditions == null) {
  1362. return;
  1363. }
  1364. if (partialRowAdditions.hasAttribute("hide")) {
  1365. scrollBody.unlinkAndReindexRows(
  1366. partialRowAdditions.getIntAttribute("firstprowix"),
  1367. partialRowAdditions.getIntAttribute("numprows"));
  1368. scrollBody.ensureCacheFilled();
  1369. } else {
  1370. if (partialRowAdditions.hasAttribute("delbelow")) {
  1371. scrollBody.insertRowsDeleteBelow(partialRowAdditions,
  1372. partialRowAdditions.getIntAttribute("firstprowix"),
  1373. partialRowAdditions.getIntAttribute("numprows"));
  1374. } else {
  1375. scrollBody.insertAndReindexRows(partialRowAdditions,
  1376. partialRowAdditions.getIntAttribute("firstprowix"),
  1377. partialRowAdditions.getIntAttribute("numprows"));
  1378. }
  1379. }
  1380. discardRowsOutsideCacheWindow();
  1381. }
  1382. /**
  1383. * Gives correct column index for given column key ("cid" in UIDL).
  1384. *
  1385. * @param colKey
  1386. * @return column index of visible columns, -1 if column not visible
  1387. */
  1388. private int getColIndexByKey(String colKey) {
  1389. // return 0 if asked for rowHeaders
  1390. if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
  1391. return 0;
  1392. }
  1393. for (int i = 0; i < visibleColOrder.length; i++) {
  1394. if (visibleColOrder[i].equals(colKey)) {
  1395. return i;
  1396. }
  1397. }
  1398. return -1;
  1399. }
  1400. private boolean isMultiSelectModeSimple() {
  1401. return selectMode == SelectMode.MULTI
  1402. && multiselectmode == MULTISELECT_MODE_SIMPLE;
  1403. }
  1404. private boolean isSingleSelectMode() {
  1405. return selectMode == SelectMode.SINGLE;
  1406. }
  1407. private boolean isMultiSelectModeAny() {
  1408. return selectMode == SelectMode.MULTI;
  1409. }
  1410. private boolean isMultiSelectModeDefault() {
  1411. return selectMode == SelectMode.MULTI
  1412. && multiselectmode == MULTISELECT_MODE_DEFAULT;
  1413. }
  1414. private void setMultiSelectMode(int multiselectmode) {
  1415. if (BrowserInfo.get().isTouchDevice()) {
  1416. // Always use the simple mode for touch devices that do not have
  1417. // shift/ctrl keys
  1418. this.multiselectmode = MULTISELECT_MODE_SIMPLE;
  1419. } else {
  1420. this.multiselectmode = multiselectmode;
  1421. }
  1422. }
  1423. /** For internal use only. May be removed or replaced in the future. */
  1424. public boolean isSelectable() {
  1425. return selectMode.getId() > SelectMode.NONE.getId();
  1426. }
  1427. private boolean isCollapsedColumn(String colKey) {
  1428. if (collapsedColumns == null) {
  1429. return false;
  1430. }
  1431. if (collapsedColumns.contains(colKey)) {
  1432. return true;
  1433. }
  1434. return false;
  1435. }
  1436. private String getColKeyByIndex(int index) {
  1437. return tHead.getHeaderCell(index).getColKey();
  1438. }
  1439. /**
  1440. * Note: not part of the official API, extend at your own risk. May be
  1441. * removed or replaced in the future.
  1442. *
  1443. * Sets the indicated column's width for headers and scrollBody alike.
  1444. *
  1445. * @param colIndex
  1446. * index of the modified column
  1447. * @param w
  1448. * new width (may be subject to modifications if doesn't meet
  1449. * minimum requirements)
  1450. * @param isDefinedWidth
  1451. * disables expand ratio if set true
  1452. */
  1453. protected void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
  1454. final HeaderCell hcell = tHead.getHeaderCell(colIndex);
  1455. // Make sure that the column grows to accommodate the sort indicator if
  1456. // necessary.
  1457. // get min width with no indent or padding
  1458. int minWidth = hcell.getMinWidth(false, false);
  1459. if (w < minWidth) {
  1460. w = minWidth;
  1461. }
  1462. // Set header column width WITHOUT INDENT
  1463. hcell.setWidth(w, isDefinedWidth);
  1464. // Set footer column width likewise
  1465. FooterCell fcell = tFoot.getFooterCell(colIndex);
  1466. fcell.setWidth(w, isDefinedWidth);
  1467. // Ensure indicators have been taken into account
  1468. tHead.resizeCaptionContainer(hcell);
  1469. // Make sure that the body column grows to accommodate the indent if
  1470. // necessary.
  1471. // get min width with indent, no padding
  1472. minWidth = hcell.getMinWidth(true, false);
  1473. if (w < minWidth) {
  1474. w = minWidth;
  1475. }
  1476. // Set body column width
  1477. scrollBody.setColWidth(colIndex, w);
  1478. }
  1479. private int getColWidth(String colKey) {
  1480. return tHead.getHeaderCell(colKey).getWidthWithIndent();
  1481. }
  1482. /**
  1483. * Get a rendered row by its key
  1484. *
  1485. * @param key
  1486. * The key to search with
  1487. * @return
  1488. */
  1489. public VScrollTableRow getRenderedRowByKey(String key) {
  1490. if (scrollBody != null) {
  1491. final Iterator<Widget> it = scrollBody.iterator();
  1492. VScrollTableRow r = null;
  1493. while (it.hasNext()) {
  1494. r = (VScrollTableRow) it.next();
  1495. if (r.getKey().equals(key)) {
  1496. return r;
  1497. }
  1498. }
  1499. }
  1500. return null;
  1501. }
  1502. /**
  1503. * Returns the next row to the given row
  1504. *
  1505. * @param row
  1506. * The row to calculate from
  1507. *
  1508. * @return The next row or null if no row exists
  1509. */
  1510. private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
  1511. final Iterator<Widget> it = scrollBody.iterator();
  1512. VScrollTableRow r = null;
  1513. while (it.hasNext()) {
  1514. r = (VScrollTableRow) it.next();
  1515. if (r == row) {
  1516. r = null;
  1517. while (offset >= 0 && it.hasNext()) {
  1518. r = (VScrollTableRow) it.next();
  1519. offset--;
  1520. }
  1521. return r;
  1522. }
  1523. }
  1524. return null;
  1525. }
  1526. /**
  1527. * Returns the previous row from the given row
  1528. *
  1529. * @param row
  1530. * The row to calculate from
  1531. * @return The previous row or null if no row exists
  1532. */
  1533. private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
  1534. final Iterator<Widget> it = scrollBody.iterator();
  1535. final Iterator<Widget> offsetIt = scrollBody.iterator();
  1536. VScrollTableRow r = null;
  1537. VScrollTableRow prev = null;
  1538. while (it.hasNext()) {
  1539. r = (VScrollTableRow) it.next();
  1540. if (offset < 0) {
  1541. prev = (VScrollTableRow) offsetIt.next();
  1542. }
  1543. if (r == row) {
  1544. return prev;
  1545. }
  1546. offset--;
  1547. }
  1548. return null;
  1549. }
  1550. protected void reOrderColumn(String columnKey, int newIndex) {
  1551. final int oldIndex = getColIndexByKey(columnKey);
  1552. // Change header order
  1553. tHead.moveCell(oldIndex, newIndex);
  1554. // Change body order
  1555. scrollBody.moveCol(oldIndex, newIndex);
  1556. // Change footer order
  1557. tFoot.moveCell(oldIndex, newIndex);
  1558. /*
  1559. * Build new columnOrder and update it to server Note that columnOrder
  1560. * also contains collapsed columns so we cannot directly build it from
  1561. * cells vector Loop the old columnOrder and append in order to new
  1562. * array unless on moved columnKey. On new index also put the moved key
  1563. * i == index on columnOrder, j == index on newOrder
  1564. */
  1565. final String oldKeyOnNewIndex = visibleColOrder[newIndex];
  1566. if (showRowHeaders) {
  1567. newIndex--; // columnOrder don't have rowHeader
  1568. }
  1569. // add back hidden rows,
  1570. for (int i = 0; i < columnOrder.length; i++) {
  1571. if (columnOrder[i].equals(oldKeyOnNewIndex)) {
  1572. break; // break loop at target
  1573. }
  1574. if (isCollapsedColumn(columnOrder[i])) {
  1575. newIndex++;
  1576. }
  1577. }
  1578. // finally we can build the new columnOrder for server
  1579. final String[] newOrder = new String[columnOrder.length];
  1580. for (int i = 0, j = 0; j < newOrder.length; i++) {
  1581. if (j == newIndex) {
  1582. newOrder[j] = columnKey;
  1583. j++;
  1584. }
  1585. if (i == columnOrder.length) {
  1586. break;
  1587. }
  1588. if (columnOrder[i].equals(columnKey)) {
  1589. continue;
  1590. }
  1591. newOrder[j] = columnOrder[i];
  1592. j++;
  1593. }
  1594. columnOrder = newOrder;
  1595. // also update visibleColumnOrder
  1596. int i = showRowHeaders ? 1 : 0;
  1597. for (int j = 0; j < newOrder.length; j++) {
  1598. final String cid = newOrder[j];
  1599. if (!isCollapsedColumn(cid)) {
  1600. visibleColOrder[i++] = cid;
  1601. }
  1602. }
  1603. client.updateVariable(paintableId, "columnorder", columnOrder, false);
  1604. if (client.hasEventListeners(this,
  1605. TableConstants.COLUMN_REORDER_EVENT_ID)) {
  1606. client.sendPendingVariableChanges();
  1607. }
  1608. }
  1609. @Override
  1610. protected void onDetach() {
  1611. detachedScrollPosition = scrollBodyPanel.getScrollPosition();
  1612. rowRequestHandler.cancel();
  1613. super.onDetach();
  1614. // ensure that scrollPosElement will be detached
  1615. if (scrollPositionElement != null) {
  1616. final Element parent = DOM.getParent(scrollPositionElement);
  1617. if (parent != null) {
  1618. DOM.removeChild(parent, scrollPositionElement);
  1619. }
  1620. }
  1621. }
  1622. @Override
  1623. public void onAttach() {
  1624. super.onAttach();
  1625. scrollBodyPanel.setScrollPosition(detachedScrollPosition);
  1626. }
  1627. /**
  1628. * Run only once when component is attached and received its initial
  1629. * content. This function:
  1630. *
  1631. * * Syncs headers and bodys "natural widths and saves the values.
  1632. *
  1633. * * Sets proper width and height
  1634. *
  1635. * * Makes deferred request to get some cache rows
  1636. *
  1637. * For internal use only. May be removed or replaced in the future.
  1638. */
  1639. public void sizeInit() {
  1640. sizeNeedsInit = false;
  1641. scrollBody.setContainerHeight();
  1642. /*
  1643. * We will use browsers table rendering algorithm to find proper column
  1644. * widths. If content and header take less space than available, we will
  1645. * divide extra space relatively to each column which has not width set.
  1646. *
  1647. * Overflow pixels are added to last column.
  1648. */
  1649. Iterator<Widget> headCells = tHead.iterator();
  1650. Iterator<Widget> footCells = tFoot.iterator();
  1651. int i = 0;
  1652. int totalExplicitColumnsWidths = 0;
  1653. int total = 0;
  1654. float expandRatioDivider = 0;
  1655. final int[] widths = new int[tHead.visibleCells.size()];
  1656. tHead.enableBrowserIntelligence();
  1657. tFoot.enableBrowserIntelligence();
  1658. int hierarchyColumnIndent = scrollBody != null ? scrollBody
  1659. .getMaxIndent() : 0;
  1660. HeaderCell hierarchyHeaderWithExpandRatio = null;
  1661. // first loop: collect natural widths
  1662. while (headCells.hasNext()) {
  1663. final HeaderCell hCell = (HeaderCell) headCells.next();
  1664. final FooterCell fCell = (FooterCell) footCells.next();
  1665. boolean needsIndent = hierarchyColumnIndent > 0
  1666. && hCell.isHierarchyColumn();
  1667. int w = hCell.getWidth();
  1668. if (hCell.isDefinedWidth()) {
  1669. // server has defined column width explicitly
  1670. if (needsIndent && w < hierarchyColumnIndent) {
  1671. // hierarchy indent overrides explicitly set width
  1672. w = hierarchyColumnIndent;
  1673. }
  1674. totalExplicitColumnsWidths += w;
  1675. } else {
  1676. if (hCell.getExpandRatio() > 0) {
  1677. expandRatioDivider += hCell.getExpandRatio();
  1678. w = 0;
  1679. if (needsIndent && w < hierarchyColumnIndent) {
  1680. hierarchyHeaderWithExpandRatio = hCell;
  1681. // don't add to widths here, because will be included in
  1682. // the expand ratio space if there's enough of it
  1683. }
  1684. } else {
  1685. // get and store greater of header width and column width,
  1686. // and store it as a minimum natural column width (these
  1687. // already contain the indent if any)
  1688. int headerWidth = hCell.getNaturalColumnWidth(i);
  1689. int footerWidth = fCell.getNaturalColumnWidth(i);
  1690. w = headerWidth > footerWidth ? headerWidth : footerWidth;
  1691. }
  1692. hCell.setNaturalMinimumColumnWidth(w);
  1693. fCell.setNaturalMinimumColumnWidth(w);
  1694. }
  1695. widths[i] = w;
  1696. total += w;
  1697. i++;
  1698. }
  1699. if (hierarchyHeaderWithExpandRatio != null) {
  1700. total += hierarchyColumnIndent;
  1701. }
  1702. tHead.disableBrowserIntelligence();
  1703. tFoot.disableBrowserIntelligence();
  1704. boolean willHaveScrollbarz = willHaveScrollbars();
  1705. // fix "natural" width if width not set
  1706. if (isDynamicWidth()) {
  1707. int w = total;
  1708. w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1709. if (willHaveScrollbarz) {
  1710. w += Util.getNativeScrollbarSize();
  1711. }
  1712. setContentWidth(w);
  1713. }
  1714. int availW = scrollBody.getAvailableWidth();
  1715. if (BrowserInfo.get().isIE()) {
  1716. // Hey IE, are you really sure about this?
  1717. availW = scrollBody.getAvailableWidth();
  1718. }
  1719. availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1720. if (willHaveScrollbarz) {
  1721. availW -= Util.getNativeScrollbarSize();
  1722. }
  1723. // TODO refactor this code to be the same as in resize timer
  1724. if (availW > total) {
  1725. // natural size is smaller than available space
  1726. int extraSpace = availW - total;
  1727. if (hierarchyHeaderWithExpandRatio != null) {
  1728. /*
  1729. * add the indent's space back to ensure each column gets an
  1730. * even share according to the expand ratios (note: if the
  1731. * allocated space isn't enough for the hierarchy column it
  1732. * shall be treated like a defined width column and the indent
  1733. * space gets removed from the extra space again)
  1734. */
  1735. extraSpace += hierarchyColumnIndent;
  1736. }
  1737. final int totalWidthR = total - totalExplicitColumnsWidths;
  1738. int checksum = 0;
  1739. if (extraSpace == 1) {
  1740. // We cannot divide one single pixel so we give it the first
  1741. // undefined column
  1742. // no need to worry about indent here
  1743. headCells = tHead.iterator();
  1744. i = 0;
  1745. checksum = availW;
  1746. while (headCells.hasNext()) {
  1747. HeaderCell hc = (HeaderCell) headCells.next();
  1748. if (!hc.isDefinedWidth()) {
  1749. widths[i]++;
  1750. break;
  1751. }
  1752. i++;
  1753. }
  1754. } else if (expandRatioDivider > 0) {
  1755. boolean setIndentToHierarchyHeader = false;
  1756. if (hierarchyHeaderWithExpandRatio != null) {
  1757. // ensure first that the hierarchyColumn gets at least the
  1758. // space allocated for indent
  1759. final int newSpace = Math
  1760. .round((extraSpace * (hierarchyHeaderWithExpandRatio
  1761. .getExpandRatio() / expandRatioDivider)));
  1762. if (newSpace < hierarchyColumnIndent) {
  1763. // not enough space for indent, remove indent from the
  1764. // extraSpace again and handle hierarchy column's header
  1765. // separately
  1766. setIndentToHierarchyHeader = true;
  1767. extraSpace -= hierarchyColumnIndent;
  1768. }
  1769. }
  1770. // visible columns have some active expand ratios, excess
  1771. // space is divided according to them
  1772. headCells = tHead.iterator();
  1773. i = 0;
  1774. while (headCells.hasNext()) {
  1775. HeaderCell hCell = (HeaderCell) headCells.next();
  1776. if (hCell.getExpandRatio() > 0) {
  1777. int w = widths[i];
  1778. if (setIndentToHierarchyHeader
  1779. && hierarchyHeaderWithExpandRatio.equals(hCell)) {
  1780. // hierarchy column's header is no longer part of
  1781. // the expansion divide and only gets indent
  1782. w += hierarchyColumnIndent;
  1783. } else {
  1784. final int newSpace = Math
  1785. .round((extraSpace * (hCell
  1786. .getExpandRatio() / expandRatioDivider)));
  1787. w += newSpace;
  1788. }
  1789. widths[i] = w;
  1790. }
  1791. checksum += widths[i];
  1792. i++;
  1793. }
  1794. } else if (totalWidthR > 0) {
  1795. // no expand ratios defined, we will share extra space
  1796. // relatively to "natural widths" among those without
  1797. // explicit width
  1798. // no need to worry about indent here, it's already included
  1799. headCells = tHead.iterator();
  1800. i = 0;
  1801. while (headCells.hasNext()) {
  1802. HeaderCell hCell = (HeaderCell) headCells.next();
  1803. if (!hCell.isDefinedWidth()) {
  1804. int w = widths[i];
  1805. final int newSpace = Math.round((float) extraSpace
  1806. * (float) w / totalWidthR);
  1807. w += newSpace;
  1808. widths[i] = w;
  1809. }
  1810. checksum += widths[i];
  1811. i++;
  1812. }
  1813. }
  1814. if (extraSpace > 0 && checksum != availW) {
  1815. /*
  1816. * There might be in some cases a rounding error of 1px when
  1817. * extra space is divided so if there is one then we give the
  1818. * first undefined column 1 more pixel
  1819. */
  1820. headCells = tHead.iterator();
  1821. i = 0;
  1822. while (headCells.hasNext()) {
  1823. HeaderCell hc = (HeaderCell) headCells.next();
  1824. if (!hc.isDefinedWidth()) {
  1825. widths[i] += availW - checksum;
  1826. break;
  1827. }
  1828. i++;
  1829. }
  1830. }
  1831. } else {
  1832. // body's size will be more than available and scrollbar will appear
  1833. }
  1834. // last loop: set possibly modified values or reset if new tBody
  1835. i = 0;
  1836. headCells = tHead.iterator();
  1837. while (headCells.hasNext()) {
  1838. final HeaderCell hCell = (HeaderCell) headCells.next();
  1839. if (isNewBody || hCell.getWidth() == -1) {
  1840. final int w = widths[i];
  1841. setColWidth(i, w, false);
  1842. }
  1843. i++;
  1844. }
  1845. initializedAndAttached = true;
  1846. updatePageLength();
  1847. /*
  1848. * Fix "natural" height if height is not set. This must be after width
  1849. * fixing so the components' widths have been adjusted.
  1850. */
  1851. if (isDynamicHeight()) {
  1852. /*
  1853. * We must force an update of the row height as this point as it
  1854. * might have been (incorrectly) calculated earlier
  1855. */
  1856. /*
  1857. * TreeTable updates stuff in a funky order, so we must set the
  1858. * height as zero here before doing the real update to make it
  1859. * realize that there is no content,
  1860. */
  1861. if (pageLength == totalRows && pageLength == 0) {
  1862. scrollBody.setHeight("0px");
  1863. }
  1864. int bodyHeight;
  1865. if (pageLength == totalRows) {
  1866. /*
  1867. * A hack to support variable height rows when paging is off.
  1868. * Generally this is not supported by scrolltable. We want to
  1869. * show all rows so the bodyHeight should be equal to the table
  1870. * height.
  1871. */
  1872. // int bodyHeight = scrollBody.getOffsetHeight();
  1873. bodyHeight = scrollBody.getRequiredHeight();
  1874. } else {
  1875. bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
  1876. * pageLength);
  1877. }
  1878. boolean needsSpaceForHorizontalSrollbar = (total > availW);
  1879. if (needsSpaceForHorizontalSrollbar) {
  1880. bodyHeight += Util.getNativeScrollbarSize();
  1881. }
  1882. scrollBodyPanel.setHeight(bodyHeight + "px");
  1883. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  1884. }
  1885. isNewBody = false;
  1886. if (firstvisible > 0) {
  1887. // Deferred due to some Firefox oddities
  1888. Scheduler.get().scheduleDeferred(new Command() {
  1889. @Override
  1890. public void execute() {
  1891. scrollBodyPanel
  1892. .setScrollPosition(measureRowHeightOffset(firstvisible));
  1893. firstRowInViewPort = firstvisible;
  1894. }
  1895. });
  1896. }
  1897. if (enabled) {
  1898. // Do we need cache rows
  1899. if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
  1900. + pageLength + (int) cache_react_rate * pageLength) {
  1901. if (totalRows - 1 > scrollBody.getLastRendered()) {
  1902. // fetch cache rows
  1903. int firstInNewSet = scrollBody.getLastRendered() + 1;
  1904. int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
  1905. * pageLength);
  1906. if (lastInNewSet > totalRows - 1) {
  1907. lastInNewSet = totalRows - 1;
  1908. }
  1909. rowRequestHandler.triggerRowFetch(firstInNewSet,
  1910. lastInNewSet - firstInNewSet + 1, 1);
  1911. }
  1912. }
  1913. }
  1914. /*
  1915. * Ensures the column alignments are correct at initial loading. <br/>
  1916. * (child components widths are correct)
  1917. */
  1918. Scheduler.get().scheduleDeferred(new Command() {
  1919. @Override
  1920. public void execute() {
  1921. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  1922. }
  1923. });
  1924. hadScrollBars = willHaveScrollbarz;
  1925. }
  1926. /**
  1927. * Note: this method is not part of official API although declared as
  1928. * protected. Extend at your own risk.
  1929. *
  1930. * @return true if content area will have scrollbars visible.
  1931. */
  1932. protected boolean willHaveScrollbars() {
  1933. if (isDynamicHeight()) {
  1934. if (pageLength < totalRows) {
  1935. return true;
  1936. }
  1937. } else {
  1938. int fakeheight = (int) Math.round(scrollBody.getRowHeight()
  1939. * totalRows);
  1940. int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
  1941. "clientHeight");
  1942. if (fakeheight > availableHeight) {
  1943. return true;
  1944. }
  1945. }
  1946. return false;
  1947. }
  1948. private void announceScrollPosition() {
  1949. if (scrollPositionElement == null) {
  1950. scrollPositionElement = DOM.createDiv();
  1951. scrollPositionElement.setClassName(getStylePrimaryName()
  1952. + "-scrollposition");
  1953. scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
  1954. scrollPositionElement.getStyle().setDisplay(Display.NONE);
  1955. getElement().appendChild(scrollPositionElement);
  1956. }
  1957. Style style = scrollPositionElement.getStyle();
  1958. style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
  1959. style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
  1960. // indexes go from 1-totalRows, as rowheaders in index-mode indicate
  1961. int last = (firstRowInViewPort + pageLength);
  1962. if (last > totalRows) {
  1963. last = totalRows;
  1964. }
  1965. scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
  1966. + " &ndash; " + (last) + "..." + "</span>");
  1967. style.setDisplay(Display.BLOCK);
  1968. }
  1969. /** For internal use only. May be removed or replaced in the future. */
  1970. public void hideScrollPositionAnnotation() {
  1971. if (scrollPositionElement != null) {
  1972. DOM.setStyleAttribute(scrollPositionElement, "display", "none");
  1973. }
  1974. }
  1975. /** For internal use only. May be removed or replaced in the future. */
  1976. public boolean isScrollPositionVisible() {
  1977. return scrollPositionElement != null
  1978. && !scrollPositionElement.getStyle().getDisplay()
  1979. .equals(Display.NONE.toString());
  1980. }
  1981. /** For internal use only. May be removed or replaced in the future. */
  1982. public class RowRequestHandler extends Timer {
  1983. private int reqFirstRow = 0;
  1984. private int reqRows = 0;
  1985. private boolean isRunning = false;
  1986. public void triggerRowFetch(int first, int rows) {
  1987. setReqFirstRow(first);
  1988. setReqRows(rows);
  1989. deferRowFetch();
  1990. }
  1991. public void triggerRowFetch(int first, int rows, int delay) {
  1992. setReqFirstRow(first);
  1993. setReqRows(rows);
  1994. deferRowFetch(delay);
  1995. }
  1996. public void deferRowFetch() {
  1997. deferRowFetch(250);
  1998. }
  1999. public boolean isRunning() {
  2000. return isRunning;
  2001. }
  2002. public void deferRowFetch(int msec) {
  2003. isRunning = true;
  2004. if (reqRows > 0 && reqFirstRow < totalRows) {
  2005. schedule(msec);
  2006. // tell scroll position to user if currently "visible" rows are
  2007. // not rendered
  2008. if (totalRows > pageLength
  2009. && ((firstRowInViewPort + pageLength > scrollBody
  2010. .getLastRendered()) || (firstRowInViewPort < scrollBody
  2011. .getFirstRendered()))) {
  2012. announceScrollPosition();
  2013. } else {
  2014. hideScrollPositionAnnotation();
  2015. }
  2016. }
  2017. }
  2018. public int getReqFirstRow() {
  2019. return reqFirstRow;
  2020. }
  2021. public void setReqFirstRow(int reqFirstRow) {
  2022. if (reqFirstRow < 0) {
  2023. this.reqFirstRow = 0;
  2024. } else if (reqFirstRow >= totalRows) {
  2025. this.reqFirstRow = totalRows - 1;
  2026. } else {
  2027. this.reqFirstRow = reqFirstRow;
  2028. }
  2029. }
  2030. public void setReqRows(int reqRows) {
  2031. if (reqRows < 0) {
  2032. this.reqRows = 0;
  2033. } else if (reqFirstRow + reqRows > totalRows) {
  2034. this.reqRows = totalRows - reqFirstRow;
  2035. } else {
  2036. this.reqRows = reqRows;
  2037. }
  2038. }
  2039. @Override
  2040. public void run() {
  2041. if (client.hasActiveRequest() || navKeyDown) {
  2042. // if client connection is busy, don't bother loading it more
  2043. VConsole.log("Postponed rowfetch");
  2044. schedule(250);
  2045. } else {
  2046. int firstRendered = scrollBody.getFirstRendered();
  2047. int lastRendered = scrollBody.getLastRendered();
  2048. if (lastRendered > totalRows) {
  2049. lastRendered = totalRows - 1;
  2050. }
  2051. boolean rendered = firstRendered >= 0 && lastRendered >= 0;
  2052. int firstToBeRendered = firstRendered;
  2053. if (reqFirstRow < firstToBeRendered) {
  2054. firstToBeRendered = reqFirstRow;
  2055. } else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
  2056. firstToBeRendered = firstRowInViewPort
  2057. - (int) (cache_rate * pageLength);
  2058. if (firstToBeRendered < 0) {
  2059. firstToBeRendered = 0;
  2060. }
  2061. } else if (rendered && firstRendered + 1 < reqFirstRow
  2062. && lastRendered + 1 < reqFirstRow) {
  2063. // requested rows must fall within the requested rendering
  2064. // area
  2065. firstToBeRendered = reqFirstRow;
  2066. }
  2067. if (firstToBeRendered + reqRows < firstRendered) {
  2068. // must increase the required row count accordingly,
  2069. // otherwise may leave a gap and the rows beyond will get
  2070. // removed
  2071. setReqRows(firstRendered - firstToBeRendered);
  2072. }
  2073. int lastToBeRendered = lastRendered;
  2074. int lastReqRow = reqFirstRow + reqRows - 1;
  2075. if (lastReqRow > lastToBeRendered) {
  2076. lastToBeRendered = lastReqRow;
  2077. } else if (firstRowInViewPort + pageLength + pageLength
  2078. * cache_rate < lastToBeRendered) {
  2079. lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
  2080. if (lastToBeRendered >= totalRows) {
  2081. lastToBeRendered = totalRows - 1;
  2082. }
  2083. // due Safari 3.1 bug (see #2607), verify reqrows, original
  2084. // problem unknown, but this should catch the issue
  2085. if (lastReqRow > lastToBeRendered) {
  2086. setReqRows(lastToBeRendered - reqFirstRow);
  2087. }
  2088. } else if (rendered && lastRendered - 1 > lastReqRow
  2089. && firstRendered - 1 > lastReqRow) {
  2090. // requested rows must fall within the requested rendering
  2091. // area
  2092. lastToBeRendered = lastReqRow;
  2093. }
  2094. if (lastToBeRendered > totalRows) {
  2095. lastToBeRendered = totalRows - 1;
  2096. }
  2097. if (reqFirstRow < firstToBeRendered
  2098. || (reqFirstRow > firstToBeRendered && (reqFirstRow < firstRendered || reqFirstRow > lastRendered + 1))) {
  2099. setReqFirstRow(firstToBeRendered);
  2100. }
  2101. if (lastRendered < lastToBeRendered
  2102. && lastRendered + reqRows < lastToBeRendered) {
  2103. // must increase the required row count accordingly,
  2104. // otherwise may leave a gap and the rows after will get
  2105. // removed
  2106. setReqRows(lastToBeRendered - lastRendered);
  2107. } else if (lastToBeRendered >= firstRendered
  2108. && reqFirstRow + reqRows < firstRendered) {
  2109. setReqRows(lastToBeRendered - lastRendered);
  2110. }
  2111. client.updateVariable(paintableId, "firstToBeRendered",
  2112. firstToBeRendered, false);
  2113. client.updateVariable(paintableId, "lastToBeRendered",
  2114. lastToBeRendered, false);
  2115. // remember which firstvisible we requested, in case the server
  2116. // has
  2117. // a differing opinion
  2118. lastRequestedFirstvisible = firstRowInViewPort;
  2119. client.updateVariable(paintableId, "firstvisible",
  2120. firstRowInViewPort, false);
  2121. client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
  2122. false);
  2123. client.updateVariable(paintableId, "reqrows", reqRows, true);
  2124. if (selectionChanged) {
  2125. unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
  2126. selectedRowKeys);
  2127. }
  2128. isRunning = false;
  2129. }
  2130. }
  2131. /**
  2132. * Sends request to refresh content at this position.
  2133. */
  2134. public void refreshContent() {
  2135. isRunning = true;
  2136. int first = (int) (firstRowInViewPort - pageLength * cache_rate);
  2137. int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
  2138. if (first < 0) {
  2139. reqRows = reqRows + first;
  2140. first = 0;
  2141. }
  2142. setReqFirstRow(first);
  2143. setReqRows(reqRows);
  2144. run();
  2145. }
  2146. }
  2147. public class HeaderCell extends Widget {
  2148. Element td = DOM.createTD();
  2149. Element captionContainer = DOM.createDiv();
  2150. Element sortIndicator = DOM.createDiv();
  2151. Element colResizeWidget = DOM.createDiv();
  2152. Element floatingCopyOfHeaderCell;
  2153. private boolean sortable = false;
  2154. private final String cid;
  2155. private boolean dragging;
  2156. private int dragStartX;
  2157. private int colIndex;
  2158. private int originalWidth;
  2159. private boolean isResizing;
  2160. private int headerX;
  2161. private boolean moved;
  2162. private int closestSlot;
  2163. private int width = -1;
  2164. private int naturalWidth = -1;
  2165. private char align = ALIGN_LEFT;
  2166. boolean definedWidth = false;
  2167. private float expandRatio = 0;
  2168. private boolean sorted;
  2169. public void setSortable(boolean b) {
  2170. sortable = b;
  2171. }
  2172. /**
  2173. * Makes room for the sorting indicator in case the column that the
  2174. * header cell belongs to is sorted. This is done by resizing the width
  2175. * of the caption container element by the correct amount
  2176. */
  2177. public void resizeCaptionContainer(int rightSpacing) {
  2178. int captionContainerWidth = width
  2179. - colResizeWidget.getOffsetWidth() - rightSpacing;
  2180. if (td.getClassName().contains("-asc")
  2181. || td.getClassName().contains("-desc")) {
  2182. // Leave room for the sort indicator
  2183. captionContainerWidth -= sortIndicator.getOffsetWidth();
  2184. }
  2185. if (captionContainerWidth < 0) {
  2186. rightSpacing += captionContainerWidth;
  2187. captionContainerWidth = 0;
  2188. }
  2189. captionContainer.getStyle().setPropertyPx("width",
  2190. captionContainerWidth);
  2191. // Apply/Remove spacing if defined
  2192. if (rightSpacing > 0) {
  2193. colResizeWidget.getStyle().setMarginLeft(rightSpacing, Unit.PX);
  2194. } else {
  2195. colResizeWidget.getStyle().clearMarginLeft();
  2196. }
  2197. }
  2198. public void setNaturalMinimumColumnWidth(int w) {
  2199. naturalWidth = w;
  2200. }
  2201. public HeaderCell(String colId, String headerText) {
  2202. cid = colId;
  2203. setText(headerText);
  2204. td.appendChild(colResizeWidget);
  2205. // ensure no clipping initially (problem on column additions)
  2206. captionContainer.getStyle().setOverflow(Overflow.VISIBLE);
  2207. td.appendChild(sortIndicator);
  2208. td.appendChild(captionContainer);
  2209. DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
  2210. | Event.ONCONTEXTMENU | Event.TOUCHEVENTS);
  2211. setElement(td);
  2212. setAlign(ALIGN_LEFT);
  2213. }
  2214. protected void updateStyleNames(String primaryStyleName) {
  2215. colResizeWidget.setClassName(primaryStyleName + "-resizer");
  2216. sortIndicator.setClassName(primaryStyleName + "-sort-indicator");
  2217. captionContainer.setClassName(primaryStyleName
  2218. + "-caption-container");
  2219. if (sorted) {
  2220. if (sortAscending) {
  2221. setStyleName(primaryStyleName + "-header-cell-asc");
  2222. } else {
  2223. setStyleName(primaryStyleName + "-header-cell-desc");
  2224. }
  2225. } else {
  2226. setStyleName(primaryStyleName + "-header-cell");
  2227. }
  2228. final String ALIGN_PREFIX = primaryStyleName
  2229. + "-caption-container-align-";
  2230. switch (align) {
  2231. case ALIGN_CENTER:
  2232. captionContainer.addClassName(ALIGN_PREFIX + "center");
  2233. break;
  2234. case ALIGN_RIGHT:
  2235. captionContainer.addClassName(ALIGN_PREFIX + "right");
  2236. break;
  2237. default:
  2238. captionContainer.addClassName(ALIGN_PREFIX + "left");
  2239. break;
  2240. }
  2241. }
  2242. public void disableAutoWidthCalculation() {
  2243. definedWidth = true;
  2244. expandRatio = 0;
  2245. }
  2246. /**
  2247. * Sets width to the header cell. This width should not include any
  2248. * possible indent modifications that are present in
  2249. * {@link VScrollTableBody#getMaxIndent()}.
  2250. *
  2251. * @param w
  2252. * required width of the cell sans indentations
  2253. * @param ensureDefinedWidth
  2254. * disables expand ratio if required
  2255. */
  2256. public void setWidth(int w, boolean ensureDefinedWidth) {
  2257. if (ensureDefinedWidth) {
  2258. definedWidth = true;
  2259. // on column resize expand ratio becomes zero
  2260. expandRatio = 0;
  2261. }
  2262. if (width == -1) {
  2263. // go to default mode, clip content if necessary
  2264. DOM.setStyleAttribute(captionContainer, "overflow", "");
  2265. }
  2266. width = w;
  2267. if (w == -1) {
  2268. DOM.setStyleAttribute(captionContainer, "width", "");
  2269. setWidth("");
  2270. } else {
  2271. tHead.resizeCaptionContainer(this);
  2272. /*
  2273. * if we already have tBody, set the header width properly, if
  2274. * not defer it. IE will fail with complex float in table header
  2275. * unless TD width is not explicitly set.
  2276. */
  2277. if (scrollBody != null) {
  2278. int maxIndent = scrollBody.getMaxIndent();
  2279. if (w < maxIndent && isHierarchyColumn()) {
  2280. w = maxIndent;
  2281. }
  2282. int tdWidth = w + scrollBody.getCellExtraWidth();
  2283. setWidth(tdWidth + "px");
  2284. } else {
  2285. Scheduler.get().scheduleDeferred(new Command() {
  2286. @Override
  2287. public void execute() {
  2288. int maxIndent = scrollBody.getMaxIndent();
  2289. int tdWidth = width;
  2290. if (tdWidth < maxIndent && isHierarchyColumn()) {
  2291. tdWidth = maxIndent;
  2292. }
  2293. tdWidth += scrollBody.getCellExtraWidth();
  2294. setWidth(tdWidth + "px");
  2295. }
  2296. });
  2297. }
  2298. }
  2299. }
  2300. public void setUndefinedWidth() {
  2301. definedWidth = false;
  2302. setWidth(-1, false);
  2303. }
  2304. /**
  2305. * Detects if width is fixed by developer on server side or resized to
  2306. * current width by user.
  2307. *
  2308. * @return true if defined, false if "natural" width
  2309. */
  2310. public boolean isDefinedWidth() {
  2311. return definedWidth && width >= 0;
  2312. }
  2313. /**
  2314. * This method exists for the needs of {@link VTreeTable} only.
  2315. *
  2316. * Returns the pixels width of the header cell. This includes the
  2317. * indent, if applicable.
  2318. *
  2319. * @return The width in pixels
  2320. */
  2321. protected int getWidthWithIndent() {
  2322. if (scrollBody != null && isHierarchyColumn()) {
  2323. int maxIndent = scrollBody.getMaxIndent();
  2324. if (maxIndent > width) {
  2325. return maxIndent;
  2326. }
  2327. }
  2328. return width;
  2329. }
  2330. /**
  2331. * Returns the pixels width of the header cell.
  2332. *
  2333. * @return The width in pixels
  2334. */
  2335. public int getWidth() {
  2336. return width;
  2337. }
  2338. /**
  2339. * This method exists for the needs of {@link VTreeTable} only.
  2340. *
  2341. * @return <code>true</code> if this is hierarcyColumn's header cell,
  2342. * <code>false</code> otherwise
  2343. */
  2344. private boolean isHierarchyColumn() {
  2345. int hierarchyColumnIndex = getHierarchyColumnIndex();
  2346. return hierarchyColumnIndex >= 0
  2347. && tHead.visibleCells.indexOf(this) == hierarchyColumnIndex;
  2348. }
  2349. public void setText(String headerText) {
  2350. DOM.setInnerHTML(captionContainer, headerText);
  2351. }
  2352. public String getColKey() {
  2353. return cid;
  2354. }
  2355. private void setSorted(boolean sorted) {
  2356. this.sorted = sorted;
  2357. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  2358. }
  2359. /**
  2360. * Handle column reordering.
  2361. */
  2362. @Override
  2363. public void onBrowserEvent(Event event) {
  2364. if (enabled && event != null) {
  2365. if (isResizing
  2366. || event.getEventTarget().cast() == colResizeWidget) {
  2367. if (dragging
  2368. && (event.getTypeInt() == Event.ONMOUSEUP || event
  2369. .getTypeInt() == Event.ONTOUCHEND)) {
  2370. // Handle releasing column header on spacer #5318
  2371. handleCaptionEvent(event);
  2372. } else {
  2373. onResizeEvent(event);
  2374. }
  2375. } else {
  2376. /*
  2377. * Ensure focus before handling caption event. Otherwise
  2378. * variables changed from caption event may be before
  2379. * variables from other components that fire variables when
  2380. * they lose focus.
  2381. */
  2382. if (event.getTypeInt() == Event.ONMOUSEDOWN
  2383. || event.getTypeInt() == Event.ONTOUCHSTART) {
  2384. scrollBodyPanel.setFocus(true);
  2385. }
  2386. handleCaptionEvent(event);
  2387. boolean stopPropagation = true;
  2388. if (event.getTypeInt() == Event.ONCONTEXTMENU
  2389. && !client.hasEventListeners(VScrollTable.this,
  2390. TableConstants.HEADER_CLICK_EVENT_ID)) {
  2391. // Prevent showing the browser's context menu only when
  2392. // there is a header click listener.
  2393. stopPropagation = false;
  2394. }
  2395. if (stopPropagation) {
  2396. event.stopPropagation();
  2397. event.preventDefault();
  2398. }
  2399. }
  2400. }
  2401. }
  2402. private void createFloatingCopy() {
  2403. floatingCopyOfHeaderCell = DOM.createDiv();
  2404. DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
  2405. floatingCopyOfHeaderCell = DOM
  2406. .getChild(floatingCopyOfHeaderCell, 2);
  2407. DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
  2408. VScrollTable.this.getStylePrimaryName() + "-header-drag");
  2409. // otherwise might wrap or be cut if narrow column
  2410. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "width", "auto");
  2411. updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
  2412. DOM.getAbsoluteTop(td));
  2413. DOM.appendChild(RootPanel.get().getElement(),
  2414. floatingCopyOfHeaderCell);
  2415. }
  2416. private void updateFloatingCopysPosition(int x, int y) {
  2417. x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
  2418. "offsetWidth") / 2;
  2419. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
  2420. if (y > 0) {
  2421. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
  2422. + "px");
  2423. }
  2424. }
  2425. private void hideFloatingCopy() {
  2426. DOM.removeChild(RootPanel.get().getElement(),
  2427. floatingCopyOfHeaderCell);
  2428. floatingCopyOfHeaderCell = null;
  2429. }
  2430. /**
  2431. * Fires a header click event after the user has clicked a column header
  2432. * cell
  2433. *
  2434. * @param event
  2435. * The click event
  2436. */
  2437. private void fireHeaderClickedEvent(Event event) {
  2438. if (client.hasEventListeners(VScrollTable.this,
  2439. TableConstants.HEADER_CLICK_EVENT_ID)) {
  2440. MouseEventDetails details = MouseEventDetailsBuilder
  2441. .buildMouseEventDetails(event);
  2442. client.updateVariable(paintableId, "headerClickEvent",
  2443. details.toString(), false);
  2444. client.updateVariable(paintableId, "headerClickCID", cid, true);
  2445. }
  2446. }
  2447. protected void handleCaptionEvent(Event event) {
  2448. switch (DOM.eventGetType(event)) {
  2449. case Event.ONTOUCHSTART:
  2450. case Event.ONMOUSEDOWN:
  2451. if (columnReordering
  2452. && Util.isTouchEventOrLeftMouseButton(event)) {
  2453. if (event.getTypeInt() == Event.ONTOUCHSTART) {
  2454. /*
  2455. * prevent using this event in e.g. scrolling
  2456. */
  2457. event.stopPropagation();
  2458. }
  2459. dragging = true;
  2460. moved = false;
  2461. colIndex = getColIndexByKey(cid);
  2462. DOM.setCapture(getElement());
  2463. headerX = tHead.getAbsoluteLeft();
  2464. event.preventDefault(); // prevent selecting text &&
  2465. // generated touch events
  2466. }
  2467. break;
  2468. case Event.ONMOUSEUP:
  2469. case Event.ONTOUCHEND:
  2470. case Event.ONTOUCHCANCEL:
  2471. if (columnReordering
  2472. && Util.isTouchEventOrLeftMouseButton(event)) {
  2473. dragging = false;
  2474. DOM.releaseCapture(getElement());
  2475. if (moved) {
  2476. hideFloatingCopy();
  2477. tHead.removeSlotFocus();
  2478. if (closestSlot != colIndex
  2479. && closestSlot != (colIndex + 1)) {
  2480. if (closestSlot > colIndex) {
  2481. reOrderColumn(cid, closestSlot - 1);
  2482. } else {
  2483. reOrderColumn(cid, closestSlot);
  2484. }
  2485. }
  2486. }
  2487. if (Util.isTouchEvent(event)) {
  2488. /*
  2489. * Prevent using in e.g. scrolling and prevent generated
  2490. * events.
  2491. */
  2492. event.preventDefault();
  2493. event.stopPropagation();
  2494. }
  2495. }
  2496. if (!moved) {
  2497. // mouse event was a click to header -> sort column
  2498. if (sortable && Util.isTouchEventOrLeftMouseButton(event)) {
  2499. if (sortColumn.equals(cid)) {
  2500. // just toggle order
  2501. client.updateVariable(paintableId, "sortascending",
  2502. !sortAscending, false);
  2503. } else {
  2504. // set table sorted by this column
  2505. client.updateVariable(paintableId, "sortcolumn",
  2506. cid, false);
  2507. }
  2508. // get also cache columns at the same request
  2509. scrollBodyPanel.setScrollPosition(0);
  2510. firstvisible = 0;
  2511. rowRequestHandler.setReqFirstRow(0);
  2512. rowRequestHandler.setReqRows((int) (2 * pageLength
  2513. * cache_rate + pageLength));
  2514. rowRequestHandler.deferRowFetch(); // some validation +
  2515. // defer 250ms
  2516. rowRequestHandler.cancel(); // instead of waiting
  2517. rowRequestHandler.run(); // run immediately
  2518. }
  2519. fireHeaderClickedEvent(event);
  2520. if (Util.isTouchEvent(event)) {
  2521. /*
  2522. * Prevent using in e.g. scrolling and prevent generated
  2523. * events.
  2524. */
  2525. event.preventDefault();
  2526. event.stopPropagation();
  2527. }
  2528. break;
  2529. }
  2530. break;
  2531. case Event.ONDBLCLICK:
  2532. fireHeaderClickedEvent(event);
  2533. break;
  2534. case Event.ONTOUCHMOVE:
  2535. case Event.ONMOUSEMOVE:
  2536. if (dragging && Util.isTouchEventOrLeftMouseButton(event)) {
  2537. if (event.getTypeInt() == Event.ONTOUCHMOVE) {
  2538. /*
  2539. * prevent using this event in e.g. scrolling
  2540. */
  2541. event.stopPropagation();
  2542. }
  2543. if (!moved) {
  2544. createFloatingCopy();
  2545. moved = true;
  2546. }
  2547. final int clientX = Util.getTouchOrMouseClientX(event);
  2548. final int x = clientX + tHead.hTableWrapper.getScrollLeft();
  2549. int slotX = headerX;
  2550. closestSlot = colIndex;
  2551. int closestDistance = -1;
  2552. int start = 0;
  2553. if (showRowHeaders) {
  2554. start++;
  2555. }
  2556. final int visibleCellCount = tHead.getVisibleCellCount();
  2557. for (int i = start; i <= visibleCellCount; i++) {
  2558. if (i > 0) {
  2559. final String colKey = getColKeyByIndex(i - 1);
  2560. // getColWidth only returns the internal width
  2561. // without padding, not the offset width of the
  2562. // whole td (#10890)
  2563. slotX += getColWidth(colKey)
  2564. + scrollBody.getCellExtraWidth();
  2565. }
  2566. final int dist = Math.abs(x - slotX);
  2567. if (closestDistance == -1 || dist < closestDistance) {
  2568. closestDistance = dist;
  2569. closestSlot = i;
  2570. }
  2571. }
  2572. tHead.focusSlot(closestSlot);
  2573. updateFloatingCopysPosition(clientX, -1);
  2574. }
  2575. break;
  2576. default:
  2577. break;
  2578. }
  2579. }
  2580. private void onResizeEvent(Event event) {
  2581. switch (DOM.eventGetType(event)) {
  2582. case Event.ONMOUSEDOWN:
  2583. if (!Util.isTouchEventOrLeftMouseButton(event)) {
  2584. return;
  2585. }
  2586. isResizing = true;
  2587. DOM.setCapture(getElement());
  2588. dragStartX = DOM.eventGetClientX(event);
  2589. colIndex = getColIndexByKey(cid);
  2590. originalWidth = getWidthWithIndent();
  2591. DOM.eventPreventDefault(event);
  2592. break;
  2593. case Event.ONMOUSEUP:
  2594. if (!Util.isTouchEventOrLeftMouseButton(event)) {
  2595. return;
  2596. }
  2597. isResizing = false;
  2598. DOM.releaseCapture(getElement());
  2599. tHead.disableAutoColumnWidthCalculation(this);
  2600. // Ensure last header cell is taking into account possible
  2601. // column selector
  2602. HeaderCell lastCell = tHead.getHeaderCell(tHead
  2603. .getVisibleCellCount() - 1);
  2604. tHead.resizeCaptionContainer(lastCell);
  2605. triggerLazyColumnAdjustment(true);
  2606. fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
  2607. break;
  2608. case Event.ONMOUSEMOVE:
  2609. if (!Util.isTouchEventOrLeftMouseButton(event)) {
  2610. return;
  2611. }
  2612. if (isResizing) {
  2613. final int deltaX = DOM.eventGetClientX(event) - dragStartX;
  2614. if (deltaX == 0) {
  2615. return;
  2616. }
  2617. tHead.disableAutoColumnWidthCalculation(this);
  2618. int newWidth = originalWidth + deltaX;
  2619. // get min width with indent, no padding
  2620. int minWidth = getMinWidth(true, false);
  2621. if (newWidth < minWidth) {
  2622. // already includes indent if any
  2623. newWidth = minWidth;
  2624. }
  2625. setColWidth(colIndex, newWidth, true);
  2626. triggerLazyColumnAdjustment(false);
  2627. forceRealignColumnHeaders();
  2628. }
  2629. break;
  2630. default:
  2631. break;
  2632. }
  2633. }
  2634. /**
  2635. * Returns the smallest possible cell width in pixels.
  2636. *
  2637. * @param includeIndent
  2638. * - width should include hierarchy column indent if
  2639. * applicable (VTreeTable only)
  2640. * @param includeCellExtraWidth
  2641. * - width should include paddings etc.
  2642. * @return
  2643. */
  2644. private int getMinWidth(boolean includeIndent,
  2645. boolean includeCellExtraWidth) {
  2646. int minWidth = sortIndicator.getOffsetWidth();
  2647. if (scrollBody != null) {
  2648. // check the need for indent before adding paddings etc.
  2649. if (includeIndent && isHierarchyColumn()) {
  2650. int maxIndent = scrollBody.getMaxIndent();
  2651. if (minWidth < maxIndent) {
  2652. minWidth = maxIndent;
  2653. }
  2654. }
  2655. if (includeCellExtraWidth) {
  2656. minWidth += scrollBody.getCellExtraWidth();
  2657. }
  2658. }
  2659. return minWidth;
  2660. }
  2661. public int getMinWidth() {
  2662. // get min width with padding, no indent
  2663. return getMinWidth(false, true);
  2664. }
  2665. public String getCaption() {
  2666. return DOM.getInnerText(captionContainer);
  2667. }
  2668. public boolean isEnabled() {
  2669. return getParent() != null;
  2670. }
  2671. public void setAlign(char c) {
  2672. align = c;
  2673. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  2674. }
  2675. public char getAlign() {
  2676. return align;
  2677. }
  2678. /**
  2679. * Detects the natural minimum width for the column of this header cell.
  2680. * If column is resized by user or the width is defined by server the
  2681. * actual width is returned. Else the natural min width is returned.
  2682. *
  2683. * @param columnIndex
  2684. * column index hint, if -1 (unknown) it will be detected
  2685. *
  2686. * @return
  2687. */
  2688. public int getNaturalColumnWidth(int columnIndex) {
  2689. final int iw = columnIndex == getHierarchyColumnIndex() ? scrollBody
  2690. .getMaxIndent() : 0;
  2691. if (isDefinedWidth()) {
  2692. if (iw > width) {
  2693. return iw;
  2694. }
  2695. return width;
  2696. } else {
  2697. if (naturalWidth < 0) {
  2698. // This is recently revealed column. Try to detect a proper
  2699. // value (greater of header and data columns)
  2700. int hw = captionContainer.getOffsetWidth()
  2701. + getHeaderPadding();
  2702. if (BrowserInfo.get().isGecko()) {
  2703. hw += sortIndicator.getOffsetWidth();
  2704. }
  2705. if (columnIndex < 0) {
  2706. columnIndex = 0;
  2707. for (Iterator<Widget> it = tHead.iterator(); it
  2708. .hasNext(); columnIndex++) {
  2709. if (it.next() == this) {
  2710. break;
  2711. }
  2712. }
  2713. }
  2714. final int cw = scrollBody.getColWidth(columnIndex);
  2715. naturalWidth = (hw > cw ? hw : cw);
  2716. }
  2717. if (iw > naturalWidth) {
  2718. // indent is temporary value, naturalWidth shouldn't be
  2719. // updated
  2720. return iw;
  2721. } else {
  2722. return naturalWidth;
  2723. }
  2724. }
  2725. }
  2726. public void setExpandRatio(float floatAttribute) {
  2727. if (floatAttribute != expandRatio) {
  2728. triggerLazyColumnAdjustment(false);
  2729. }
  2730. expandRatio = floatAttribute;
  2731. }
  2732. public float getExpandRatio() {
  2733. return expandRatio;
  2734. }
  2735. public boolean isSorted() {
  2736. return sorted;
  2737. }
  2738. }
  2739. /**
  2740. * HeaderCell that is header cell for row headers.
  2741. *
  2742. * Reordering disabled and clicking on it resets sorting.
  2743. */
  2744. public class RowHeadersHeaderCell extends HeaderCell {
  2745. RowHeadersHeaderCell() {
  2746. super(ROW_HEADER_COLUMN_KEY, "");
  2747. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  2748. }
  2749. @Override
  2750. protected void updateStyleNames(String primaryStyleName) {
  2751. super.updateStyleNames(primaryStyleName);
  2752. setStyleName(primaryStyleName + "-header-cell-rowheader");
  2753. }
  2754. @Override
  2755. protected void handleCaptionEvent(Event event) {
  2756. // NOP: RowHeaders cannot be reordered
  2757. // TODO It'd be nice to reset sorting here
  2758. }
  2759. }
  2760. public class TableHead extends Panel implements ActionOwner {
  2761. private static final int WRAPPER_WIDTH = 900000;
  2762. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  2763. HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
  2764. Element div = DOM.createDiv();
  2765. Element hTableWrapper = DOM.createDiv();
  2766. Element hTableContainer = DOM.createDiv();
  2767. Element table = DOM.createTable();
  2768. Element headerTableBody = DOM.createTBody();
  2769. Element tr = DOM.createTR();
  2770. private final Element columnSelector = DOM.createDiv();
  2771. private int focusedSlot = -1;
  2772. public TableHead() {
  2773. if (BrowserInfo.get().isIE()) {
  2774. table.setPropertyInt("cellSpacing", 0);
  2775. }
  2776. DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
  2777. DOM.setStyleAttribute(columnSelector, "display", "none");
  2778. DOM.appendChild(table, headerTableBody);
  2779. DOM.appendChild(headerTableBody, tr);
  2780. DOM.appendChild(hTableContainer, table);
  2781. DOM.appendChild(hTableWrapper, hTableContainer);
  2782. DOM.appendChild(div, hTableWrapper);
  2783. DOM.appendChild(div, columnSelector);
  2784. setElement(div);
  2785. DOM.sinkEvents(columnSelector, Event.ONCLICK);
  2786. availableCells.put(ROW_HEADER_COLUMN_KEY,
  2787. new RowHeadersHeaderCell());
  2788. }
  2789. protected void updateStyleNames(String primaryStyleName) {
  2790. hTableWrapper.setClassName(primaryStyleName + "-header");
  2791. columnSelector.setClassName(primaryStyleName + "-column-selector");
  2792. setStyleName(primaryStyleName + "-header-wrap");
  2793. for (HeaderCell c : availableCells.values()) {
  2794. c.updateStyleNames(primaryStyleName);
  2795. }
  2796. }
  2797. public void resizeCaptionContainer(HeaderCell cell) {
  2798. HeaderCell lastcell = getHeaderCell(visibleCells.size() - 1);
  2799. int columnSelectorOffset = columnSelector.getOffsetWidth();
  2800. if (cell == lastcell && columnSelectorOffset > 0
  2801. && !hasVerticalScrollbar()) {
  2802. // Measure column widths
  2803. int columnTotalWidth = 0;
  2804. for (Widget w : visibleCells) {
  2805. int cellExtraWidth = w.getOffsetWidth();
  2806. if (scrollBody != null
  2807. && visibleCells.indexOf(w) == getHierarchyColumnIndex()
  2808. && cellExtraWidth < scrollBody.getMaxIndent()) {
  2809. // indent must be taken into consideration even if it
  2810. // hasn't been applied yet
  2811. columnTotalWidth += scrollBody.getMaxIndent();
  2812. } else {
  2813. columnTotalWidth += cellExtraWidth;
  2814. }
  2815. }
  2816. int divOffset = div.getOffsetWidth();
  2817. if (columnTotalWidth >= divOffset - columnSelectorOffset) {
  2818. /*
  2819. * Ensure column caption is visible when placed under the
  2820. * column selector widget by shifting and resizing the
  2821. * caption.
  2822. */
  2823. int offset = 0;
  2824. int diff = divOffset - columnTotalWidth;
  2825. if (diff < columnSelectorOffset && diff > 0) {
  2826. /*
  2827. * If the difference is less than the column selectors
  2828. * width then just offset by the difference
  2829. */
  2830. offset = columnSelectorOffset - diff;
  2831. } else {
  2832. // Else offset by the whole column selector
  2833. offset = columnSelectorOffset;
  2834. }
  2835. lastcell.resizeCaptionContainer(offset);
  2836. } else {
  2837. cell.resizeCaptionContainer(0);
  2838. }
  2839. } else {
  2840. cell.resizeCaptionContainer(0);
  2841. }
  2842. }
  2843. @Override
  2844. public void clear() {
  2845. for (String cid : availableCells.keySet()) {
  2846. removeCell(cid);
  2847. }
  2848. availableCells.clear();
  2849. availableCells.put(ROW_HEADER_COLUMN_KEY,
  2850. new RowHeadersHeaderCell());
  2851. }
  2852. public void updateCellsFromUIDL(UIDL uidl) {
  2853. Iterator<?> it = uidl.getChildIterator();
  2854. HashSet<String> updated = new HashSet<String>();
  2855. boolean refreshContentWidths = initializedAndAttached
  2856. && hadScrollBars != willHaveScrollbars();
  2857. while (it.hasNext()) {
  2858. final UIDL col = (UIDL) it.next();
  2859. final String cid = col.getStringAttribute("cid");
  2860. updated.add(cid);
  2861. String caption = buildCaptionHtmlSnippet(col);
  2862. HeaderCell c = getHeaderCell(cid);
  2863. if (c == null) {
  2864. c = new HeaderCell(cid, caption);
  2865. availableCells.put(cid, c);
  2866. if (initializedAndAttached) {
  2867. // we will need a column width recalculation
  2868. initializedAndAttached = false;
  2869. initialContentReceived = false;
  2870. isNewBody = true;
  2871. }
  2872. } else {
  2873. c.setText(caption);
  2874. }
  2875. if (col.hasAttribute("sortable")) {
  2876. c.setSortable(true);
  2877. if (cid.equals(sortColumn)) {
  2878. c.setSorted(true);
  2879. } else {
  2880. c.setSorted(false);
  2881. }
  2882. } else {
  2883. c.setSortable(false);
  2884. }
  2885. if (col.hasAttribute("align")) {
  2886. c.setAlign(col.getStringAttribute("align").charAt(0));
  2887. } else {
  2888. c.setAlign(ALIGN_LEFT);
  2889. }
  2890. if (col.hasAttribute("width")) {
  2891. // Make sure to accomodate for the sort indicator if
  2892. // necessary.
  2893. int width = col.getIntAttribute("width");
  2894. int widthWithoutAddedIndent = width;
  2895. // get min width with indent, no padding
  2896. int minWidth = c.getMinWidth(true, false);
  2897. if (width < minWidth) {
  2898. width = minWidth;
  2899. }
  2900. if (scrollBody != null && width != c.getWidthWithIndent()) {
  2901. // Do a more thorough update if a column is resized from
  2902. // the server *after* the header has been properly
  2903. // initialized
  2904. final int colIx = getColIndexByKey(c.cid);
  2905. final int newWidth = width;
  2906. Scheduler.get().scheduleDeferred(
  2907. new ScheduledCommand() {
  2908. @Override
  2909. public void execute() {
  2910. setColWidth(colIx, newWidth, true);
  2911. }
  2912. });
  2913. refreshContentWidths = true;
  2914. } else {
  2915. // get min width with no indent or padding
  2916. minWidth = c.getMinWidth(false, false);
  2917. if (widthWithoutAddedIndent < minWidth) {
  2918. widthWithoutAddedIndent = minWidth;
  2919. }
  2920. // save min width without indent
  2921. c.setWidth(widthWithoutAddedIndent, true);
  2922. }
  2923. } else if (col.hasAttribute("er")) {
  2924. c.setExpandRatio(col.getFloatAttribute("er"));
  2925. } else if (recalcWidths) {
  2926. c.setUndefinedWidth();
  2927. } else {
  2928. boolean hadExpandRatio = c.getExpandRatio() > 0;
  2929. boolean hadDefinedWidth = c.isDefinedWidth();
  2930. if (hadExpandRatio || hadDefinedWidth) {
  2931. // Someone has removed a expand width or the defined
  2932. // width on the server side (setting it to -1), make the
  2933. // column undefined again and measure columns again.
  2934. c.setUndefinedWidth();
  2935. c.setExpandRatio(0);
  2936. refreshContentWidths = true;
  2937. }
  2938. }
  2939. if (col.hasAttribute("collapsed")) {
  2940. // ensure header is properly removed from parent (case when
  2941. // collapsing happens via servers side api)
  2942. if (c.isAttached()) {
  2943. c.removeFromParent();
  2944. headerChangedDuringUpdate = true;
  2945. }
  2946. }
  2947. }
  2948. if (refreshContentWidths) {
  2949. // Recalculate the column sizings if any column has changed
  2950. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  2951. @Override
  2952. public void execute() {
  2953. triggerLazyColumnAdjustment(true);
  2954. }
  2955. });
  2956. }
  2957. // check for orphaned header cells
  2958. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  2959. .hasNext();) {
  2960. String cid = cit.next();
  2961. if (!updated.contains(cid)) {
  2962. removeCell(cid);
  2963. cit.remove();
  2964. // we will need a column width recalculation, since columns
  2965. // with expand ratios should expand to fill the void.
  2966. initializedAndAttached = false;
  2967. initialContentReceived = false;
  2968. isNewBody = true;
  2969. }
  2970. }
  2971. }
  2972. public void enableColumn(String cid, int index) {
  2973. final HeaderCell c = getHeaderCell(cid);
  2974. if (!c.isEnabled() || getHeaderCell(index) != c) {
  2975. setHeaderCell(index, c);
  2976. if (initializedAndAttached) {
  2977. headerChangedDuringUpdate = true;
  2978. }
  2979. }
  2980. }
  2981. public int getVisibleCellCount() {
  2982. return visibleCells.size();
  2983. }
  2984. public void setHorizontalScrollPosition(int scrollLeft) {
  2985. hTableWrapper.setScrollLeft(scrollLeft);
  2986. }
  2987. public void setColumnCollapsingAllowed(boolean cc) {
  2988. if (cc) {
  2989. columnSelector.getStyle().setDisplay(Display.BLOCK);
  2990. } else {
  2991. columnSelector.getStyle().setDisplay(Display.NONE);
  2992. }
  2993. }
  2994. public void disableBrowserIntelligence() {
  2995. hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
  2996. }
  2997. public void enableBrowserIntelligence() {
  2998. hTableContainer.getStyle().clearWidth();
  2999. }
  3000. public void setHeaderCell(int index, HeaderCell cell) {
  3001. if (cell.isEnabled()) {
  3002. // we're moving the cell
  3003. DOM.removeChild(tr, cell.getElement());
  3004. orphan(cell);
  3005. visibleCells.remove(cell);
  3006. }
  3007. if (index < visibleCells.size()) {
  3008. // insert to right slot
  3009. DOM.insertChild(tr, cell.getElement(), index);
  3010. adopt(cell);
  3011. visibleCells.add(index, cell);
  3012. } else if (index == visibleCells.size()) {
  3013. // simply append
  3014. DOM.appendChild(tr, cell.getElement());
  3015. adopt(cell);
  3016. visibleCells.add(cell);
  3017. } else {
  3018. throw new RuntimeException(
  3019. "Header cells must be appended in order");
  3020. }
  3021. }
  3022. public HeaderCell getHeaderCell(int index) {
  3023. if (index >= 0 && index < visibleCells.size()) {
  3024. return (HeaderCell) visibleCells.get(index);
  3025. } else {
  3026. return null;
  3027. }
  3028. }
  3029. /**
  3030. * Get's HeaderCell by it's column Key.
  3031. *
  3032. * Note that this returns HeaderCell even if it is currently collapsed.
  3033. *
  3034. * @param cid
  3035. * Column key of accessed HeaderCell
  3036. * @return HeaderCell
  3037. */
  3038. public HeaderCell getHeaderCell(String cid) {
  3039. return availableCells.get(cid);
  3040. }
  3041. public void moveCell(int oldIndex, int newIndex) {
  3042. final HeaderCell hCell = getHeaderCell(oldIndex);
  3043. final Element cell = hCell.getElement();
  3044. visibleCells.remove(oldIndex);
  3045. DOM.removeChild(tr, cell);
  3046. DOM.insertChild(tr, cell, newIndex);
  3047. visibleCells.add(newIndex, hCell);
  3048. }
  3049. @Override
  3050. public Iterator<Widget> iterator() {
  3051. return visibleCells.iterator();
  3052. }
  3053. @Override
  3054. public boolean remove(Widget w) {
  3055. if (visibleCells.contains(w)) {
  3056. visibleCells.remove(w);
  3057. orphan(w);
  3058. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  3059. return true;
  3060. }
  3061. return false;
  3062. }
  3063. public void removeCell(String colKey) {
  3064. final HeaderCell c = getHeaderCell(colKey);
  3065. remove(c);
  3066. }
  3067. private void focusSlot(int index) {
  3068. removeSlotFocus();
  3069. if (index > 0) {
  3070. Element child = tr.getChild(index - 1).getFirstChild().cast();
  3071. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3072. + "-resizer");
  3073. child.addClassName(VScrollTable.this.getStylePrimaryName()
  3074. + "-focus-slot-right");
  3075. } else {
  3076. Element child = tr.getChild(index).getFirstChild().cast();
  3077. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3078. + "-resizer");
  3079. child.addClassName(VScrollTable.this.getStylePrimaryName()
  3080. + "-focus-slot-left");
  3081. }
  3082. focusedSlot = index;
  3083. }
  3084. private void removeSlotFocus() {
  3085. if (focusedSlot < 0) {
  3086. return;
  3087. }
  3088. if (focusedSlot == 0) {
  3089. Element child = tr.getChild(focusedSlot).getFirstChild().cast();
  3090. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3091. + "-resizer");
  3092. } else if (focusedSlot > 0) {
  3093. Element child = tr.getChild(focusedSlot - 1).getFirstChild()
  3094. .cast();
  3095. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3096. + "-resizer");
  3097. }
  3098. focusedSlot = -1;
  3099. }
  3100. @Override
  3101. public void onBrowserEvent(Event event) {
  3102. if (enabled) {
  3103. if (event.getEventTarget().cast() == columnSelector) {
  3104. final int left = DOM.getAbsoluteLeft(columnSelector);
  3105. final int top = DOM.getAbsoluteTop(columnSelector)
  3106. + DOM.getElementPropertyInt(columnSelector,
  3107. "offsetHeight");
  3108. client.getContextMenu().showAt(this, left, top);
  3109. }
  3110. }
  3111. }
  3112. @Override
  3113. protected void onDetach() {
  3114. super.onDetach();
  3115. if (client != null) {
  3116. client.getContextMenu().ensureHidden(this);
  3117. }
  3118. }
  3119. class VisibleColumnAction extends Action {
  3120. String colKey;
  3121. private boolean collapsed;
  3122. private boolean noncollapsible = false;
  3123. private VScrollTableRow currentlyFocusedRow;
  3124. public VisibleColumnAction(String colKey) {
  3125. super(VScrollTable.TableHead.this);
  3126. this.colKey = colKey;
  3127. caption = tHead.getHeaderCell(colKey).getCaption();
  3128. currentlyFocusedRow = focusedRow;
  3129. }
  3130. @Override
  3131. public void execute() {
  3132. if (noncollapsible) {
  3133. return;
  3134. }
  3135. client.getContextMenu().hide();
  3136. // toggle selected column
  3137. if (collapsedColumns.contains(colKey)) {
  3138. collapsedColumns.remove(colKey);
  3139. } else {
  3140. tHead.removeCell(colKey);
  3141. collapsedColumns.add(colKey);
  3142. triggerLazyColumnAdjustment(true);
  3143. }
  3144. // update variable to server
  3145. client.updateVariable(paintableId, "collapsedcolumns",
  3146. collapsedColumns.toArray(new String[collapsedColumns
  3147. .size()]), false);
  3148. // let rowRequestHandler determine proper rows
  3149. rowRequestHandler.refreshContent();
  3150. lazyRevertFocusToRow(currentlyFocusedRow);
  3151. }
  3152. public void setCollapsed(boolean b) {
  3153. collapsed = b;
  3154. }
  3155. public void setNoncollapsible(boolean b) {
  3156. noncollapsible = b;
  3157. }
  3158. /**
  3159. * Override default method to distinguish on/off columns
  3160. */
  3161. @Override
  3162. public String getHTML() {
  3163. final StringBuffer buf = new StringBuffer();
  3164. buf.append("<span class=\"");
  3165. if (collapsed) {
  3166. buf.append("v-off");
  3167. } else {
  3168. buf.append("v-on");
  3169. }
  3170. if (noncollapsible) {
  3171. buf.append(" v-disabled");
  3172. }
  3173. buf.append("\">");
  3174. buf.append(super.getHTML());
  3175. buf.append("</span>");
  3176. return buf.toString();
  3177. }
  3178. }
  3179. /*
  3180. * Returns columns as Action array for column select popup
  3181. */
  3182. @Override
  3183. public Action[] getActions() {
  3184. Object[] cols;
  3185. if (columnReordering && columnOrder != null) {
  3186. cols = columnOrder;
  3187. } else {
  3188. // if columnReordering is disabled, we need different way to get
  3189. // all available columns
  3190. cols = visibleColOrder;
  3191. cols = new Object[visibleColOrder.length
  3192. + collapsedColumns.size()];
  3193. int i;
  3194. for (i = 0; i < visibleColOrder.length; i++) {
  3195. cols[i] = visibleColOrder[i];
  3196. }
  3197. for (final Iterator<String> it = collapsedColumns.iterator(); it
  3198. .hasNext();) {
  3199. cols[i++] = it.next();
  3200. }
  3201. }
  3202. final Action[] actions = new Action[cols.length];
  3203. for (int i = 0; i < cols.length; i++) {
  3204. final String cid = (String) cols[i];
  3205. final HeaderCell c = getHeaderCell(cid);
  3206. final VisibleColumnAction a = new VisibleColumnAction(
  3207. c.getColKey());
  3208. a.setCaption(c.getCaption());
  3209. if (!c.isEnabled()) {
  3210. a.setCollapsed(true);
  3211. }
  3212. if (noncollapsibleColumns.contains(cid)) {
  3213. a.setNoncollapsible(true);
  3214. }
  3215. actions[i] = a;
  3216. }
  3217. return actions;
  3218. }
  3219. @Override
  3220. public ApplicationConnection getClient() {
  3221. return client;
  3222. }
  3223. @Override
  3224. public String getPaintableId() {
  3225. return paintableId;
  3226. }
  3227. /**
  3228. * Returns column alignments for visible columns
  3229. */
  3230. public char[] getColumnAlignments() {
  3231. final Iterator<Widget> it = visibleCells.iterator();
  3232. final char[] aligns = new char[visibleCells.size()];
  3233. int colIndex = 0;
  3234. while (it.hasNext()) {
  3235. aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
  3236. }
  3237. return aligns;
  3238. }
  3239. /**
  3240. * Disables the automatic calculation of all column widths by forcing
  3241. * the widths to be "defined" thus turning off expand ratios and such.
  3242. */
  3243. public void disableAutoColumnWidthCalculation(HeaderCell source) {
  3244. for (HeaderCell cell : availableCells.values()) {
  3245. cell.disableAutoWidthCalculation();
  3246. }
  3247. // fire column resize events for all columns but the source of the
  3248. // resize action, since an event will fire separately for this.
  3249. ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
  3250. availableCells.values());
  3251. columns.remove(source);
  3252. sendColumnWidthUpdates(columns);
  3253. forceRealignColumnHeaders();
  3254. }
  3255. }
  3256. /**
  3257. * A cell in the footer
  3258. */
  3259. public class FooterCell extends Widget {
  3260. private final Element td = DOM.createTD();
  3261. private final Element captionContainer = DOM.createDiv();
  3262. private char align = ALIGN_LEFT;
  3263. private int width = -1;
  3264. private float expandRatio = 0;
  3265. private final String cid;
  3266. boolean definedWidth = false;
  3267. private int naturalWidth = -1;
  3268. public FooterCell(String colId, String headerText) {
  3269. cid = colId;
  3270. setText(headerText);
  3271. // ensure no clipping initially (problem on column additions)
  3272. DOM.setStyleAttribute(captionContainer, "overflow", "visible");
  3273. DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
  3274. DOM.appendChild(td, captionContainer);
  3275. DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
  3276. | Event.ONCONTEXTMENU);
  3277. setElement(td);
  3278. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3279. }
  3280. protected void updateStyleNames(String primaryStyleName) {
  3281. captionContainer.setClassName(primaryStyleName
  3282. + "-footer-container");
  3283. }
  3284. /**
  3285. * Sets the text of the footer
  3286. *
  3287. * @param footerText
  3288. * The text in the footer
  3289. */
  3290. public void setText(String footerText) {
  3291. if (footerText == null || footerText.equals("")) {
  3292. footerText = "&nbsp;";
  3293. }
  3294. DOM.setInnerHTML(captionContainer, footerText);
  3295. }
  3296. /**
  3297. * Set alignment of the text in the cell
  3298. *
  3299. * @param c
  3300. * The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
  3301. * ALIGN_RIGHT
  3302. */
  3303. public void setAlign(char c) {
  3304. if (align != c) {
  3305. switch (c) {
  3306. case ALIGN_CENTER:
  3307. DOM.setStyleAttribute(captionContainer, "textAlign",
  3308. "center");
  3309. break;
  3310. case ALIGN_RIGHT:
  3311. DOM.setStyleAttribute(captionContainer, "textAlign",
  3312. "right");
  3313. break;
  3314. default:
  3315. DOM.setStyleAttribute(captionContainer, "textAlign", "");
  3316. break;
  3317. }
  3318. }
  3319. align = c;
  3320. }
  3321. /**
  3322. * Get the alignment of the text int the cell
  3323. *
  3324. * @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
  3325. */
  3326. public char getAlign() {
  3327. return align;
  3328. }
  3329. /**
  3330. * Sets the width of the cell. This width should not include any
  3331. * possible indent modifications that are present in
  3332. * {@link VScrollTableBody#getMaxIndent()}.
  3333. *
  3334. * @param w
  3335. * The width of the cell
  3336. * @param ensureDefinedWidth
  3337. * Ensures that the given width is not recalculated
  3338. */
  3339. public void setWidth(int w, boolean ensureDefinedWidth) {
  3340. if (ensureDefinedWidth) {
  3341. definedWidth = true;
  3342. // on column resize expand ratio becomes zero
  3343. expandRatio = 0;
  3344. }
  3345. if (width == w) {
  3346. return;
  3347. }
  3348. if (width == -1) {
  3349. // go to default mode, clip content if necessary
  3350. DOM.setStyleAttribute(captionContainer, "overflow", "");
  3351. }
  3352. width = w;
  3353. if (w == -1) {
  3354. DOM.setStyleAttribute(captionContainer, "width", "");
  3355. setWidth("");
  3356. } else {
  3357. /*
  3358. * Reduce width with one pixel for the right border since the
  3359. * footers does not have any spacers between them.
  3360. */
  3361. final int borderWidths = 1;
  3362. // Set the container width (check for negative value)
  3363. captionContainer.getStyle().setPropertyPx("width",
  3364. Math.max(w - borderWidths, 0));
  3365. /*
  3366. * if we already have tBody, set the header width properly, if
  3367. * not defer it. IE will fail with complex float in table header
  3368. * unless TD width is not explicitly set.
  3369. */
  3370. if (scrollBody != null) {
  3371. int maxIndent = scrollBody.getMaxIndent();
  3372. if (w < maxIndent
  3373. && tFoot.visibleCells.indexOf(this) == getHierarchyColumnIndex()) {
  3374. // ensure there's room for the indent
  3375. w = maxIndent;
  3376. }
  3377. int tdWidth = w + scrollBody.getCellExtraWidth()
  3378. - borderWidths;
  3379. setWidth(Math.max(tdWidth, 0) + "px");
  3380. } else {
  3381. Scheduler.get().scheduleDeferred(new Command() {
  3382. @Override
  3383. public void execute() {
  3384. int tdWidth = width;
  3385. int maxIndent = scrollBody.getMaxIndent();
  3386. if (tdWidth < maxIndent
  3387. && tFoot.visibleCells.indexOf(this) == getHierarchyColumnIndex()) {
  3388. // ensure there's room for the indent
  3389. tdWidth = maxIndent;
  3390. }
  3391. tdWidth += scrollBody.getCellExtraWidth()
  3392. - borderWidths;
  3393. setWidth(Math.max(tdWidth, 0) + "px");
  3394. }
  3395. });
  3396. }
  3397. }
  3398. }
  3399. /**
  3400. * Sets the width to undefined
  3401. */
  3402. public void setUndefinedWidth() {
  3403. definedWidth = false;
  3404. setWidth(-1, false);
  3405. }
  3406. /**
  3407. * Detects if width is fixed by developer on server side or resized to
  3408. * current width by user.
  3409. *
  3410. * @return true if defined, false if "natural" width
  3411. */
  3412. public boolean isDefinedWidth() {
  3413. return definedWidth && width >= 0;
  3414. }
  3415. /**
  3416. * Returns the pixels width of the footer cell.
  3417. *
  3418. * @return The width in pixels
  3419. */
  3420. public int getWidth() {
  3421. return width;
  3422. }
  3423. /**
  3424. * Sets the expand ratio of the cell
  3425. *
  3426. * @param floatAttribute
  3427. * The expand ratio
  3428. */
  3429. public void setExpandRatio(float floatAttribute) {
  3430. expandRatio = floatAttribute;
  3431. }
  3432. /**
  3433. * Returns the expand ration of the cell
  3434. *
  3435. * @return The expand ratio
  3436. */
  3437. public float getExpandRatio() {
  3438. return expandRatio;
  3439. }
  3440. /**
  3441. * Is the cell enabled?
  3442. *
  3443. * @return True if enabled else False
  3444. */
  3445. public boolean isEnabled() {
  3446. return getParent() != null;
  3447. }
  3448. /**
  3449. * Handle column clicking
  3450. */
  3451. @Override
  3452. public void onBrowserEvent(Event event) {
  3453. if (enabled && event != null) {
  3454. handleCaptionEvent(event);
  3455. if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
  3456. scrollBodyPanel.setFocus(true);
  3457. }
  3458. boolean stopPropagation = true;
  3459. if (event.getTypeInt() == Event.ONCONTEXTMENU
  3460. && !client.hasEventListeners(VScrollTable.this,
  3461. TableConstants.FOOTER_CLICK_EVENT_ID)) {
  3462. // Show browser context menu if a footer click listener is
  3463. // not present
  3464. stopPropagation = false;
  3465. }
  3466. if (stopPropagation) {
  3467. event.stopPropagation();
  3468. event.preventDefault();
  3469. }
  3470. }
  3471. }
  3472. /**
  3473. * Handles a event on the captions
  3474. *
  3475. * @param event
  3476. * The event to handle
  3477. */
  3478. protected void handleCaptionEvent(Event event) {
  3479. if (event.getTypeInt() == Event.ONMOUSEUP
  3480. || event.getTypeInt() == Event.ONDBLCLICK) {
  3481. fireFooterClickedEvent(event);
  3482. }
  3483. }
  3484. /**
  3485. * Fires a footer click event after the user has clicked a column footer
  3486. * cell
  3487. *
  3488. * @param event
  3489. * The click event
  3490. */
  3491. private void fireFooterClickedEvent(Event event) {
  3492. if (client.hasEventListeners(VScrollTable.this,
  3493. TableConstants.FOOTER_CLICK_EVENT_ID)) {
  3494. MouseEventDetails details = MouseEventDetailsBuilder
  3495. .buildMouseEventDetails(event);
  3496. client.updateVariable(paintableId, "footerClickEvent",
  3497. details.toString(), false);
  3498. client.updateVariable(paintableId, "footerClickCID", cid, true);
  3499. }
  3500. }
  3501. /**
  3502. * Returns the column key of the column
  3503. *
  3504. * @return The column key
  3505. */
  3506. public String getColKey() {
  3507. return cid;
  3508. }
  3509. /**
  3510. * Detects the natural minimum width for the column of this header cell.
  3511. * If column is resized by user or the width is defined by server the
  3512. * actual width is returned. Else the natural min width is returned.
  3513. *
  3514. * @param columnIndex
  3515. * column index hint, if -1 (unknown) it will be detected
  3516. *
  3517. * @return
  3518. */
  3519. public int getNaturalColumnWidth(int columnIndex) {
  3520. final int iw = columnIndex == getHierarchyColumnIndex() ? scrollBody
  3521. .getMaxIndent() : 0;
  3522. if (isDefinedWidth()) {
  3523. if (iw > width) {
  3524. return iw;
  3525. }
  3526. return width;
  3527. } else {
  3528. if (naturalWidth < 0) {
  3529. // This is recently revealed column. Try to detect a proper
  3530. // value (greater of header and data
  3531. // cols)
  3532. final int hw = ((Element) getElement().getLastChild())
  3533. .getOffsetWidth() + getHeaderPadding();
  3534. if (columnIndex < 0) {
  3535. columnIndex = 0;
  3536. for (Iterator<Widget> it = tHead.iterator(); it
  3537. .hasNext(); columnIndex++) {
  3538. if (it.next() == this) {
  3539. break;
  3540. }
  3541. }
  3542. }
  3543. final int cw = scrollBody.getColWidth(columnIndex);
  3544. naturalWidth = (hw > cw ? hw : cw);
  3545. }
  3546. if (iw > naturalWidth) {
  3547. return iw;
  3548. } else {
  3549. return naturalWidth;
  3550. }
  3551. }
  3552. }
  3553. public void setNaturalMinimumColumnWidth(int w) {
  3554. naturalWidth = w;
  3555. }
  3556. }
  3557. /**
  3558. * HeaderCell that is header cell for row headers.
  3559. *
  3560. * Reordering disabled and clicking on it resets sorting.
  3561. */
  3562. public class RowHeadersFooterCell extends FooterCell {
  3563. RowHeadersFooterCell() {
  3564. super(ROW_HEADER_COLUMN_KEY, "");
  3565. }
  3566. @Override
  3567. protected void handleCaptionEvent(Event event) {
  3568. // NOP: RowHeaders cannot be reordered
  3569. // TODO It'd be nice to reset sorting here
  3570. }
  3571. }
  3572. /**
  3573. * The footer of the table which can be seen in the bottom of the Table.
  3574. */
  3575. public class TableFooter extends Panel {
  3576. private static final int WRAPPER_WIDTH = 900000;
  3577. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  3578. HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
  3579. Element div = DOM.createDiv();
  3580. Element hTableWrapper = DOM.createDiv();
  3581. Element hTableContainer = DOM.createDiv();
  3582. Element table = DOM.createTable();
  3583. Element headerTableBody = DOM.createTBody();
  3584. Element tr = DOM.createTR();
  3585. public TableFooter() {
  3586. DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
  3587. DOM.appendChild(table, headerTableBody);
  3588. DOM.appendChild(headerTableBody, tr);
  3589. DOM.appendChild(hTableContainer, table);
  3590. DOM.appendChild(hTableWrapper, hTableContainer);
  3591. DOM.appendChild(div, hTableWrapper);
  3592. setElement(div);
  3593. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3594. new RowHeadersFooterCell());
  3595. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3596. }
  3597. protected void updateStyleNames(String primaryStyleName) {
  3598. hTableWrapper.setClassName(primaryStyleName + "-footer");
  3599. setStyleName(primaryStyleName + "-footer-wrap");
  3600. for (FooterCell c : availableCells.values()) {
  3601. c.updateStyleNames(primaryStyleName);
  3602. }
  3603. }
  3604. @Override
  3605. public void clear() {
  3606. for (String cid : availableCells.keySet()) {
  3607. removeCell(cid);
  3608. }
  3609. availableCells.clear();
  3610. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3611. new RowHeadersFooterCell());
  3612. }
  3613. /*
  3614. * (non-Javadoc)
  3615. *
  3616. * @see
  3617. * com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
  3618. * .ui.Widget)
  3619. */
  3620. @Override
  3621. public boolean remove(Widget w) {
  3622. if (visibleCells.contains(w)) {
  3623. visibleCells.remove(w);
  3624. orphan(w);
  3625. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  3626. return true;
  3627. }
  3628. return false;
  3629. }
  3630. /*
  3631. * (non-Javadoc)
  3632. *
  3633. * @see com.google.gwt.user.client.ui.HasWidgets#iterator()
  3634. */
  3635. @Override
  3636. public Iterator<Widget> iterator() {
  3637. return visibleCells.iterator();
  3638. }
  3639. /**
  3640. * Gets a footer cell which represents the given columnId
  3641. *
  3642. * @param cid
  3643. * The columnId
  3644. *
  3645. * @return The cell
  3646. */
  3647. public FooterCell getFooterCell(String cid) {
  3648. return availableCells.get(cid);
  3649. }
  3650. /**
  3651. * Gets a footer cell by using a column index
  3652. *
  3653. * @param index
  3654. * The index of the column
  3655. * @return The Cell
  3656. */
  3657. public FooterCell getFooterCell(int index) {
  3658. if (index < visibleCells.size()) {
  3659. return (FooterCell) visibleCells.get(index);
  3660. } else {
  3661. return null;
  3662. }
  3663. }
  3664. /**
  3665. * Updates the cells contents when updateUIDL request is received
  3666. *
  3667. * @param uidl
  3668. * The UIDL
  3669. */
  3670. public void updateCellsFromUIDL(UIDL uidl) {
  3671. Iterator<?> columnIterator = uidl.getChildIterator();
  3672. HashSet<String> updated = new HashSet<String>();
  3673. while (columnIterator.hasNext()) {
  3674. final UIDL col = (UIDL) columnIterator.next();
  3675. final String cid = col.getStringAttribute("cid");
  3676. updated.add(cid);
  3677. String caption = col.hasAttribute("fcaption") ? col
  3678. .getStringAttribute("fcaption") : "";
  3679. FooterCell c = getFooterCell(cid);
  3680. if (c == null) {
  3681. c = new FooterCell(cid, caption);
  3682. availableCells.put(cid, c);
  3683. if (initializedAndAttached) {
  3684. // we will need a column width recalculation
  3685. initializedAndAttached = false;
  3686. initialContentReceived = false;
  3687. isNewBody = true;
  3688. }
  3689. } else {
  3690. c.setText(caption);
  3691. }
  3692. if (col.hasAttribute("align")) {
  3693. c.setAlign(col.getStringAttribute("align").charAt(0));
  3694. } else {
  3695. c.setAlign(ALIGN_LEFT);
  3696. }
  3697. if (col.hasAttribute("width")) {
  3698. if (scrollBody == null) {
  3699. // Already updated by setColWidth called from
  3700. // TableHeads.updateCellsFromUIDL in case of a server
  3701. // side resize
  3702. final String width = col.getStringAttribute("width");
  3703. c.setWidth(Integer.parseInt(width), true);
  3704. }
  3705. } else if (recalcWidths) {
  3706. c.setUndefinedWidth();
  3707. }
  3708. if (col.hasAttribute("er")) {
  3709. c.setExpandRatio(col.getFloatAttribute("er"));
  3710. }
  3711. if (col.hasAttribute("collapsed")) {
  3712. // ensure header is properly removed from parent (case when
  3713. // collapsing happens via servers side api)
  3714. if (c.isAttached()) {
  3715. c.removeFromParent();
  3716. headerChangedDuringUpdate = true;
  3717. }
  3718. }
  3719. }
  3720. // check for orphaned header cells
  3721. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  3722. .hasNext();) {
  3723. String cid = cit.next();
  3724. if (!updated.contains(cid)) {
  3725. removeCell(cid);
  3726. cit.remove();
  3727. }
  3728. }
  3729. }
  3730. /**
  3731. * Set a footer cell for a specified column index
  3732. *
  3733. * @param index
  3734. * The index
  3735. * @param cell
  3736. * The footer cell
  3737. */
  3738. public void setFooterCell(int index, FooterCell cell) {
  3739. if (cell.isEnabled()) {
  3740. // we're moving the cell
  3741. DOM.removeChild(tr, cell.getElement());
  3742. orphan(cell);
  3743. visibleCells.remove(cell);
  3744. }
  3745. if (index < visibleCells.size()) {
  3746. // insert to right slot
  3747. DOM.insertChild(tr, cell.getElement(), index);
  3748. adopt(cell);
  3749. visibleCells.add(index, cell);
  3750. } else if (index == visibleCells.size()) {
  3751. // simply append
  3752. DOM.appendChild(tr, cell.getElement());
  3753. adopt(cell);
  3754. visibleCells.add(cell);
  3755. } else {
  3756. throw new RuntimeException(
  3757. "Header cells must be appended in order");
  3758. }
  3759. }
  3760. /**
  3761. * Remove a cell by using the columnId
  3762. *
  3763. * @param colKey
  3764. * The columnId to remove
  3765. */
  3766. public void removeCell(String colKey) {
  3767. final FooterCell c = getFooterCell(colKey);
  3768. remove(c);
  3769. }
  3770. /**
  3771. * Enable a column (Sets the footer cell)
  3772. *
  3773. * @param cid
  3774. * The columnId
  3775. * @param index
  3776. * The index of the column
  3777. */
  3778. public void enableColumn(String cid, int index) {
  3779. final FooterCell c = getFooterCell(cid);
  3780. if (!c.isEnabled() || getFooterCell(index) != c) {
  3781. setFooterCell(index, c);
  3782. if (initializedAndAttached) {
  3783. headerChangedDuringUpdate = true;
  3784. }
  3785. }
  3786. }
  3787. /**
  3788. * Disable browser measurement of the table width
  3789. */
  3790. public void disableBrowserIntelligence() {
  3791. DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
  3792. + "px");
  3793. }
  3794. /**
  3795. * Enable browser measurement of the table width
  3796. */
  3797. public void enableBrowserIntelligence() {
  3798. DOM.setStyleAttribute(hTableContainer, "width", "");
  3799. }
  3800. /**
  3801. * Set the horizontal position in the cell in the footer. This is done
  3802. * when a horizontal scrollbar is present.
  3803. *
  3804. * @param scrollLeft
  3805. * The value of the leftScroll
  3806. */
  3807. public void setHorizontalScrollPosition(int scrollLeft) {
  3808. hTableWrapper.setScrollLeft(scrollLeft);
  3809. }
  3810. /**
  3811. * Swap cells when the column are dragged
  3812. *
  3813. * @param oldIndex
  3814. * The old index of the cell
  3815. * @param newIndex
  3816. * The new index of the cell
  3817. */
  3818. public void moveCell(int oldIndex, int newIndex) {
  3819. final FooterCell hCell = getFooterCell(oldIndex);
  3820. final Element cell = hCell.getElement();
  3821. visibleCells.remove(oldIndex);
  3822. DOM.removeChild(tr, cell);
  3823. DOM.insertChild(tr, cell, newIndex);
  3824. visibleCells.add(newIndex, hCell);
  3825. }
  3826. }
  3827. /**
  3828. * This Panel can only contain VScrollTableRow type of widgets. This
  3829. * "simulates" very large table, keeping spacers which take room of
  3830. * unrendered rows.
  3831. *
  3832. */
  3833. public class VScrollTableBody extends Panel {
  3834. public static final int DEFAULT_ROW_HEIGHT = 24;
  3835. private double rowHeight = -1;
  3836. private final LinkedList<Widget> renderedRows = new LinkedList<Widget>();
  3837. /**
  3838. * Due some optimizations row height measuring is deferred and initial
  3839. * set of rows is rendered detached. Flag set on when table body has
  3840. * been attached in dom and rowheight has been measured.
  3841. */
  3842. private boolean tBodyMeasurementsDone = false;
  3843. Element preSpacer = DOM.createDiv();
  3844. Element postSpacer = DOM.createDiv();
  3845. Element container = DOM.createDiv();
  3846. TableSectionElement tBodyElement = Document.get().createTBodyElement();
  3847. Element table = DOM.createTable();
  3848. private int firstRendered;
  3849. private int lastRendered;
  3850. private char[] aligns;
  3851. protected VScrollTableBody() {
  3852. constructDOM();
  3853. setElement(container);
  3854. }
  3855. public void setLastRendered(int lastRendered) {
  3856. if (totalRows >= 0 && lastRendered > totalRows) {
  3857. VConsole.log("setLastRendered: " + this.lastRendered + " -> "
  3858. + lastRendered);
  3859. this.lastRendered = totalRows - 1;
  3860. } else {
  3861. this.lastRendered = lastRendered;
  3862. }
  3863. }
  3864. public int getLastRendered() {
  3865. return lastRendered;
  3866. }
  3867. public int getFirstRendered() {
  3868. return firstRendered;
  3869. }
  3870. public VScrollTableRow getRowByRowIndex(int indexInTable) {
  3871. int internalIndex = indexInTable - firstRendered;
  3872. if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
  3873. return (VScrollTableRow) renderedRows.get(internalIndex);
  3874. } else {
  3875. return null;
  3876. }
  3877. }
  3878. /**
  3879. * @return the height of scrollable body, subpixels ceiled.
  3880. */
  3881. public int getRequiredHeight() {
  3882. return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
  3883. + Util.getRequiredHeight(table);
  3884. }
  3885. private void constructDOM() {
  3886. if (BrowserInfo.get().isIE()) {
  3887. table.setPropertyInt("cellSpacing", 0);
  3888. }
  3889. table.appendChild(tBodyElement);
  3890. DOM.appendChild(container, preSpacer);
  3891. DOM.appendChild(container, table);
  3892. DOM.appendChild(container, postSpacer);
  3893. if (BrowserInfo.get().requiresTouchScrollDelegate()) {
  3894. NodeList<Node> childNodes = container.getChildNodes();
  3895. for (int i = 0; i < childNodes.getLength(); i++) {
  3896. Element item = (Element) childNodes.getItem(i);
  3897. item.getStyle().setProperty("webkitTransform",
  3898. "translate3d(0,0,0)");
  3899. }
  3900. }
  3901. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3902. }
  3903. protected void updateStyleNames(String primaryStyleName) {
  3904. table.setClassName(primaryStyleName + "-table");
  3905. preSpacer.setClassName(primaryStyleName + "-row-spacer");
  3906. postSpacer.setClassName(primaryStyleName + "-row-spacer");
  3907. for (Widget w : renderedRows) {
  3908. VScrollTableRow row = (VScrollTableRow) w;
  3909. row.updateStyleNames(primaryStyleName);
  3910. }
  3911. }
  3912. public int getAvailableWidth() {
  3913. int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
  3914. return availW;
  3915. }
  3916. public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
  3917. firstRendered = firstIndex;
  3918. setLastRendered(firstIndex + rows - 1);
  3919. final Iterator<?> it = rowData.getChildIterator();
  3920. aligns = tHead.getColumnAlignments();
  3921. while (it.hasNext()) {
  3922. final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
  3923. addRow(row);
  3924. }
  3925. if (isAttached()) {
  3926. fixSpacers();
  3927. }
  3928. }
  3929. public void renderRows(UIDL rowData, int firstIndex, int rows) {
  3930. // FIXME REVIEW
  3931. aligns = tHead.getColumnAlignments();
  3932. final Iterator<?> it = rowData.getChildIterator();
  3933. if (firstIndex == lastRendered + 1) {
  3934. while (it.hasNext()) {
  3935. final VScrollTableRow row = prepareRow((UIDL) it.next());
  3936. addRow(row);
  3937. setLastRendered(lastRendered + 1);
  3938. }
  3939. fixSpacers();
  3940. } else if (firstIndex + rows == firstRendered) {
  3941. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  3942. int i = rows;
  3943. while (it.hasNext()) {
  3944. i--;
  3945. rowArray[i] = prepareRow((UIDL) it.next());
  3946. }
  3947. for (i = 0; i < rows; i++) {
  3948. addRowBeforeFirstRendered(rowArray[i]);
  3949. firstRendered--;
  3950. }
  3951. } else {
  3952. // completely new set of rows
  3953. // there can't be sanity checks for last rendered within this
  3954. // while loop regardless of what has been set previously, so
  3955. // change it temporarily to true and then return the original
  3956. // value
  3957. boolean temp = postponeSanityCheckForLastRendered;
  3958. postponeSanityCheckForLastRendered = true;
  3959. while (lastRendered + 1 > firstRendered) {
  3960. unlinkRow(false);
  3961. }
  3962. postponeSanityCheckForLastRendered = temp;
  3963. VScrollTableRow row = prepareRow((UIDL) it.next());
  3964. firstRendered = firstIndex;
  3965. setLastRendered(firstIndex - 1);
  3966. addRow(row);
  3967. setLastRendered(lastRendered + 1);
  3968. setContainerHeight();
  3969. fixSpacers();
  3970. while (it.hasNext()) {
  3971. addRow(prepareRow((UIDL) it.next()));
  3972. setLastRendered(lastRendered + 1);
  3973. }
  3974. fixSpacers();
  3975. }
  3976. // this may be a new set of rows due content change,
  3977. // ensure we have proper cache rows
  3978. ensureCacheFilled();
  3979. }
  3980. /**
  3981. * Ensure we have the correct set of rows on client side, e.g. if the
  3982. * content on the server side has changed, or the client scroll position
  3983. * has changed since the last request.
  3984. */
  3985. protected void ensureCacheFilled() {
  3986. int reactFirstRow = (int) (firstRowInViewPort - pageLength
  3987. * cache_react_rate);
  3988. int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
  3989. * cache_react_rate);
  3990. if (reactFirstRow < 0) {
  3991. reactFirstRow = 0;
  3992. }
  3993. if (reactLastRow >= totalRows) {
  3994. reactLastRow = totalRows - 1;
  3995. }
  3996. if (lastRendered < reactFirstRow || firstRendered > reactLastRow) {
  3997. /*
  3998. * #8040 - scroll position is completely changed since the
  3999. * latest request, so request a new set of rows.
  4000. *
  4001. * TODO: We should probably check whether the fetched rows match
  4002. * the current scroll position right when they arrive, so as to
  4003. * not waste time rendering a set of rows that will never be
  4004. * visible...
  4005. */
  4006. rowRequestHandler.triggerRowFetch(reactFirstRow, reactLastRow
  4007. - reactFirstRow + 1, 1);
  4008. } else if (lastRendered < reactLastRow) {
  4009. // get some cache rows below visible area
  4010. rowRequestHandler.triggerRowFetch(lastRendered + 1,
  4011. reactLastRow - lastRendered, 1);
  4012. } else if (firstRendered > reactFirstRow) {
  4013. /*
  4014. * Branch for fetching cache above visible area.
  4015. *
  4016. * If cache needed for both before and after visible area, this
  4017. * will be rendered after-cache is received and rendered. So in
  4018. * some rare situations the table may make two cache visits to
  4019. * server.
  4020. */
  4021. rowRequestHandler.triggerRowFetch(reactFirstRow, firstRendered
  4022. - reactFirstRow, 1);
  4023. }
  4024. }
  4025. /**
  4026. * Inserts rows as provided in the rowData starting at firstIndex.
  4027. *
  4028. * @param rowData
  4029. * @param firstIndex
  4030. * @param rows
  4031. * the number of rows
  4032. * @return a list of the rows added.
  4033. */
  4034. protected List<VScrollTableRow> insertRows(UIDL rowData,
  4035. int firstIndex, int rows) {
  4036. aligns = tHead.getColumnAlignments();
  4037. final Iterator<?> it = rowData.getChildIterator();
  4038. List<VScrollTableRow> insertedRows = new ArrayList<VScrollTableRow>();
  4039. if (firstIndex == lastRendered + 1) {
  4040. while (it.hasNext()) {
  4041. final VScrollTableRow row = prepareRow((UIDL) it.next());
  4042. addRow(row);
  4043. insertedRows.add(row);
  4044. if (postponeSanityCheckForLastRendered) {
  4045. lastRendered++;
  4046. } else {
  4047. setLastRendered(lastRendered + 1);
  4048. }
  4049. }
  4050. fixSpacers();
  4051. } else if (firstIndex + rows == firstRendered) {
  4052. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  4053. int i = rows;
  4054. while (it.hasNext()) {
  4055. i--;
  4056. rowArray[i] = prepareRow((UIDL) it.next());
  4057. }
  4058. for (i = 0; i < rows; i++) {
  4059. addRowBeforeFirstRendered(rowArray[i]);
  4060. insertedRows.add(rowArray[i]);
  4061. firstRendered--;
  4062. }
  4063. } else {
  4064. // insert in the middle
  4065. int ix = firstIndex;
  4066. while (it.hasNext()) {
  4067. VScrollTableRow row = prepareRow((UIDL) it.next());
  4068. insertRowAt(row, ix);
  4069. insertedRows.add(row);
  4070. if (postponeSanityCheckForLastRendered) {
  4071. lastRendered++;
  4072. } else {
  4073. setLastRendered(lastRendered + 1);
  4074. }
  4075. ix++;
  4076. }
  4077. fixSpacers();
  4078. }
  4079. return insertedRows;
  4080. }
  4081. protected List<VScrollTableRow> insertAndReindexRows(UIDL rowData,
  4082. int firstIndex, int rows) {
  4083. List<VScrollTableRow> inserted = insertRows(rowData, firstIndex,
  4084. rows);
  4085. int actualIxOfFirstRowAfterInserted = firstIndex + rows
  4086. - firstRendered;
  4087. for (int ix = actualIxOfFirstRowAfterInserted; ix < renderedRows
  4088. .size(); ix++) {
  4089. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  4090. r.setIndex(r.getIndex() + rows);
  4091. }
  4092. setContainerHeight();
  4093. return inserted;
  4094. }
  4095. protected void insertRowsDeleteBelow(UIDL rowData, int firstIndex,
  4096. int rows) {
  4097. unlinkAllRowsStartingAt(firstIndex);
  4098. insertRows(rowData, firstIndex, rows);
  4099. setContainerHeight();
  4100. }
  4101. /**
  4102. * This method is used to instantiate new rows for this table. It
  4103. * automatically sets correct widths to rows cells and assigns correct
  4104. * client reference for child widgets.
  4105. *
  4106. * This method can be called only after table has been initialized
  4107. *
  4108. * @param uidl
  4109. */
  4110. private VScrollTableRow prepareRow(UIDL uidl) {
  4111. final VScrollTableRow row = createRow(uidl, aligns);
  4112. row.initCellWidths();
  4113. return row;
  4114. }
  4115. protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
  4116. if (uidl.hasAttribute("gen_html")) {
  4117. // This is a generated row.
  4118. return new VScrollTableGeneratedRow(uidl, aligns2);
  4119. }
  4120. return new VScrollTableRow(uidl, aligns2);
  4121. }
  4122. private void addRowBeforeFirstRendered(VScrollTableRow row) {
  4123. row.setIndex(firstRendered - 1);
  4124. if (row.isSelected()) {
  4125. row.addStyleName("v-selected");
  4126. }
  4127. tBodyElement.insertBefore(row.getElement(),
  4128. tBodyElement.getFirstChild());
  4129. adopt(row);
  4130. renderedRows.add(0, row);
  4131. }
  4132. private void addRow(VScrollTableRow row) {
  4133. row.setIndex(firstRendered + renderedRows.size());
  4134. if (row.isSelected()) {
  4135. row.addStyleName("v-selected");
  4136. }
  4137. tBodyElement.appendChild(row.getElement());
  4138. // Add to renderedRows before adopt so iterator() will return also
  4139. // this row if called in an attach handler (#9264)
  4140. renderedRows.add(row);
  4141. adopt(row);
  4142. }
  4143. private void insertRowAt(VScrollTableRow row, int index) {
  4144. row.setIndex(index);
  4145. if (row.isSelected()) {
  4146. row.addStyleName("v-selected");
  4147. }
  4148. if (index > 0) {
  4149. VScrollTableRow sibling = getRowByRowIndex(index - 1);
  4150. tBodyElement
  4151. .insertAfter(row.getElement(), sibling.getElement());
  4152. } else {
  4153. VScrollTableRow sibling = getRowByRowIndex(index);
  4154. tBodyElement.insertBefore(row.getElement(),
  4155. sibling.getElement());
  4156. }
  4157. adopt(row);
  4158. int actualIx = index - firstRendered;
  4159. renderedRows.add(actualIx, row);
  4160. }
  4161. @Override
  4162. public Iterator<Widget> iterator() {
  4163. return renderedRows.iterator();
  4164. }
  4165. /**
  4166. * @return false if couldn't remove row
  4167. */
  4168. protected boolean unlinkRow(boolean fromBeginning) {
  4169. if (lastRendered - firstRendered < 0) {
  4170. return false;
  4171. }
  4172. int actualIx;
  4173. if (fromBeginning) {
  4174. actualIx = 0;
  4175. firstRendered++;
  4176. } else {
  4177. actualIx = renderedRows.size() - 1;
  4178. if (postponeSanityCheckForLastRendered) {
  4179. --lastRendered;
  4180. } else {
  4181. setLastRendered(lastRendered - 1);
  4182. }
  4183. }
  4184. if (actualIx >= 0) {
  4185. unlinkRowAtActualIndex(actualIx);
  4186. fixSpacers();
  4187. return true;
  4188. }
  4189. return false;
  4190. }
  4191. protected void unlinkRows(int firstIndex, int count) {
  4192. if (count < 1) {
  4193. return;
  4194. }
  4195. if (firstRendered > firstIndex
  4196. && firstRendered < firstIndex + count) {
  4197. count = count - (firstRendered - firstIndex);
  4198. firstIndex = firstRendered;
  4199. }
  4200. int lastIndex = firstIndex + count - 1;
  4201. if (lastRendered < lastIndex) {
  4202. lastIndex = lastRendered;
  4203. }
  4204. for (int ix = lastIndex; ix >= firstIndex; ix--) {
  4205. unlinkRowAtActualIndex(actualIndex(ix));
  4206. if (postponeSanityCheckForLastRendered) {
  4207. // partialUpdate handles sanity check later
  4208. lastRendered--;
  4209. } else {
  4210. setLastRendered(lastRendered - 1);
  4211. }
  4212. }
  4213. fixSpacers();
  4214. }
  4215. protected void unlinkAndReindexRows(int firstIndex, int count) {
  4216. unlinkRows(firstIndex, count);
  4217. int actualFirstIx = firstIndex - firstRendered;
  4218. for (int ix = actualFirstIx; ix < renderedRows.size(); ix++) {
  4219. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  4220. r.setIndex(r.getIndex() - count);
  4221. }
  4222. setContainerHeight();
  4223. }
  4224. protected void unlinkAllRowsStartingAt(int index) {
  4225. if (firstRendered > index) {
  4226. index = firstRendered;
  4227. }
  4228. for (int ix = renderedRows.size() - 1; ix >= index; ix--) {
  4229. unlinkRowAtActualIndex(actualIndex(ix));
  4230. setLastRendered(lastRendered - 1);
  4231. }
  4232. fixSpacers();
  4233. }
  4234. private int actualIndex(int index) {
  4235. return index - firstRendered;
  4236. }
  4237. private void unlinkRowAtActualIndex(int index) {
  4238. final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
  4239. .get(index);
  4240. tBodyElement.removeChild(toBeRemoved.getElement());
  4241. orphan(toBeRemoved);
  4242. renderedRows.remove(index);
  4243. }
  4244. @Override
  4245. public boolean remove(Widget w) {
  4246. throw new UnsupportedOperationException();
  4247. }
  4248. /**
  4249. * Fix container blocks height according to totalRows to avoid
  4250. * "bouncing" when scrolling
  4251. */
  4252. private void setContainerHeight() {
  4253. fixSpacers();
  4254. DOM.setStyleAttribute(container, "height",
  4255. measureRowHeightOffset(totalRows) + "px");
  4256. }
  4257. private void fixSpacers() {
  4258. int prepx = measureRowHeightOffset(firstRendered);
  4259. if (prepx < 0) {
  4260. prepx = 0;
  4261. }
  4262. preSpacer.getStyle().setPropertyPx("height", prepx);
  4263. int postpx;
  4264. if (pageLength == 0 && totalRows == pageLength) {
  4265. /*
  4266. * TreeTable depends on having lastRendered out of sync in some
  4267. * situations, which makes this method miss the special
  4268. * situation in which one row worth of post spacer to be added
  4269. * if there are no rows in the table. #9203
  4270. */
  4271. postpx = measureRowHeightOffset(1);
  4272. } else {
  4273. postpx = measureRowHeightOffset(totalRows - 1)
  4274. - measureRowHeightOffset(lastRendered);
  4275. }
  4276. if (postpx < 0) {
  4277. postpx = 0;
  4278. }
  4279. postSpacer.getStyle().setPropertyPx("height", postpx);
  4280. }
  4281. public double getRowHeight() {
  4282. return getRowHeight(false);
  4283. }
  4284. public double getRowHeight(boolean forceUpdate) {
  4285. if (tBodyMeasurementsDone && !forceUpdate) {
  4286. return rowHeight;
  4287. } else {
  4288. if (tBodyElement.getRows().getLength() > 0) {
  4289. int tableHeight = getTableHeight();
  4290. int rowCount = tBodyElement.getRows().getLength();
  4291. rowHeight = tableHeight / (double) rowCount;
  4292. } else {
  4293. // Special cases if we can't just measure the current rows
  4294. if (!Double.isNaN(lastKnownRowHeight)) {
  4295. // Use previous value if available
  4296. if (BrowserInfo.get().isIE()) {
  4297. /*
  4298. * IE needs to reflow the table element at this
  4299. * point to work correctly (e.g.
  4300. * com.vaadin.tests.components.table.
  4301. * ContainerSizeChange) - the other code paths
  4302. * already trigger reflows, but here it must be done
  4303. * explicitly.
  4304. */
  4305. getTableHeight();
  4306. }
  4307. rowHeight = lastKnownRowHeight;
  4308. } else if (isAttached()) {
  4309. // measure row height by adding a dummy row
  4310. VScrollTableRow scrollTableRow = new VScrollTableRow();
  4311. tBodyElement.appendChild(scrollTableRow.getElement());
  4312. getRowHeight(forceUpdate);
  4313. tBodyElement.removeChild(scrollTableRow.getElement());
  4314. } else {
  4315. // TODO investigate if this can never happen anymore
  4316. return DEFAULT_ROW_HEIGHT;
  4317. }
  4318. }
  4319. lastKnownRowHeight = rowHeight;
  4320. tBodyMeasurementsDone = true;
  4321. return rowHeight;
  4322. }
  4323. }
  4324. public int getTableHeight() {
  4325. return table.getOffsetHeight();
  4326. }
  4327. /**
  4328. * Returns the width available for column content.
  4329. *
  4330. * @param columnIndex
  4331. * @return
  4332. */
  4333. public int getColWidth(int columnIndex) {
  4334. if (tBodyMeasurementsDone) {
  4335. if (renderedRows.isEmpty()) {
  4336. // no rows yet rendered
  4337. return 0;
  4338. }
  4339. for (Widget row : renderedRows) {
  4340. if (!(row instanceof VScrollTableGeneratedRow)) {
  4341. TableRowElement tr = row.getElement().cast();
  4342. Element wrapperdiv = tr.getCells().getItem(columnIndex)
  4343. .getFirstChildElement().cast();
  4344. return wrapperdiv.getOffsetWidth();
  4345. }
  4346. }
  4347. return 0;
  4348. } else {
  4349. return 0;
  4350. }
  4351. }
  4352. /**
  4353. * Sets the content width of a column.
  4354. *
  4355. * Due IE limitation, we must set the width to a wrapper elements inside
  4356. * table cells (with overflow hidden, which does not work on td
  4357. * elements).
  4358. *
  4359. * To get this work properly crossplatform, we will also set the width
  4360. * of td.
  4361. *
  4362. * @param colIndex
  4363. * @param w
  4364. */
  4365. public void setColWidth(int colIndex, int w) {
  4366. for (Widget row : renderedRows) {
  4367. ((VScrollTableRow) row).setCellWidth(colIndex, w);
  4368. }
  4369. }
  4370. private int cellExtraWidth = -1;
  4371. /**
  4372. * Method to return the space used for cell paddings + border.
  4373. */
  4374. private int getCellExtraWidth() {
  4375. if (cellExtraWidth < 0) {
  4376. detectExtrawidth();
  4377. }
  4378. return cellExtraWidth;
  4379. }
  4380. /**
  4381. * This method exists for the needs of {@link VTreeTable} only. May be
  4382. * removed or replaced in the future.</br> </br> Returns the maximum
  4383. * indent of the hierarcyColumn, if applicable.
  4384. *
  4385. * @see {@link VScrollTable#getHierarchyColumnIndex()}
  4386. *
  4387. * @return maximum indent in pixels
  4388. */
  4389. protected int getMaxIndent() {
  4390. return 0;
  4391. }
  4392. /**
  4393. * This method exists for the needs of {@link VTreeTable} only. May be
  4394. * removed or replaced in the future.</br> </br> Calculates the maximum
  4395. * indent of the hierarcyColumn, if applicable.
  4396. */
  4397. protected void calculateMaxIndent() {
  4398. // NOP
  4399. }
  4400. private void detectExtrawidth() {
  4401. NodeList<TableRowElement> rows = tBodyElement.getRows();
  4402. if (rows.getLength() == 0) {
  4403. /* need to temporary add empty row and detect */
  4404. VScrollTableRow scrollTableRow = new VScrollTableRow();
  4405. scrollTableRow.updateStyleNames(VScrollTable.this
  4406. .getStylePrimaryName());
  4407. tBodyElement.appendChild(scrollTableRow.getElement());
  4408. detectExtrawidth();
  4409. tBodyElement.removeChild(scrollTableRow.getElement());
  4410. } else {
  4411. boolean noCells = false;
  4412. TableRowElement item = rows.getItem(0);
  4413. TableCellElement firstTD = item.getCells().getItem(0);
  4414. if (firstTD == null) {
  4415. // content is currently empty, we need to add a fake cell
  4416. // for measuring
  4417. noCells = true;
  4418. VScrollTableRow next = (VScrollTableRow) iterator().next();
  4419. boolean sorted = tHead.getHeaderCell(0) != null ? tHead
  4420. .getHeaderCell(0).isSorted() : false;
  4421. next.addCell(null, "", ALIGN_LEFT, "", true, sorted);
  4422. firstTD = item.getCells().getItem(0);
  4423. }
  4424. com.google.gwt.dom.client.Element wrapper = firstTD
  4425. .getFirstChildElement();
  4426. cellExtraWidth = firstTD.getOffsetWidth()
  4427. - wrapper.getOffsetWidth();
  4428. if (noCells) {
  4429. firstTD.getParentElement().removeChild(firstTD);
  4430. }
  4431. }
  4432. }
  4433. public void moveCol(int oldIndex, int newIndex) {
  4434. // loop all rows and move given index to its new place
  4435. final Iterator<?> rows = iterator();
  4436. while (rows.hasNext()) {
  4437. final VScrollTableRow row = (VScrollTableRow) rows.next();
  4438. final Element td = DOM.getChild(row.getElement(), oldIndex);
  4439. if (td != null) {
  4440. DOM.removeChild(row.getElement(), td);
  4441. DOM.insertChild(row.getElement(), td, newIndex);
  4442. }
  4443. }
  4444. }
  4445. /**
  4446. * Restore row visibility which is set to "none" when the row is
  4447. * rendered (due a performance optimization).
  4448. */
  4449. private void restoreRowVisibility() {
  4450. for (Widget row : renderedRows) {
  4451. row.getElement().getStyle().setProperty("visibility", "");
  4452. }
  4453. }
  4454. public class VScrollTableRow extends Panel implements ActionOwner {
  4455. private static final int TOUCHSCROLL_TIMEOUT = 100;
  4456. private static final int DRAGMODE_MULTIROW = 2;
  4457. protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
  4458. private boolean selected = false;
  4459. protected final int rowKey;
  4460. private String[] actionKeys = null;
  4461. private final TableRowElement rowElement;
  4462. private int index;
  4463. private Event touchStart;
  4464. private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
  4465. private Timer contextTouchTimeout;
  4466. private Timer dragTouchTimeout;
  4467. private int touchStartY;
  4468. private int touchStartX;
  4469. private TooltipInfo tooltipInfo = null;
  4470. private Map<TableCellElement, TooltipInfo> cellToolTips = new HashMap<TableCellElement, TooltipInfo>();
  4471. private boolean isDragging = false;
  4472. private String rowStyle = null;
  4473. private VScrollTableRow(int rowKey) {
  4474. this.rowKey = rowKey;
  4475. rowElement = Document.get().createTRElement();
  4476. setElement(rowElement);
  4477. DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
  4478. | Event.TOUCHEVENTS | Event.ONDBLCLICK
  4479. | Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS);
  4480. }
  4481. public VScrollTableRow(UIDL uidl, char[] aligns) {
  4482. this(uidl.getIntAttribute("key"));
  4483. /*
  4484. * Rendering the rows as hidden improves Firefox and Safari
  4485. * performance drastically.
  4486. */
  4487. getElement().getStyle().setProperty("visibility", "hidden");
  4488. rowStyle = uidl.getStringAttribute("rowstyle");
  4489. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  4490. String rowDescription = uidl.getStringAttribute("rowdescr");
  4491. if (rowDescription != null && !rowDescription.equals("")) {
  4492. tooltipInfo = new TooltipInfo(rowDescription);
  4493. } else {
  4494. tooltipInfo = null;
  4495. }
  4496. tHead.getColumnAlignments();
  4497. int col = 0;
  4498. int visibleColumnIndex = -1;
  4499. // row header
  4500. if (showRowHeaders) {
  4501. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4502. addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
  4503. "rowheader", true, sorted);
  4504. visibleColumnIndex++;
  4505. }
  4506. if (uidl.hasAttribute("al")) {
  4507. actionKeys = uidl.getStringArrayAttribute("al");
  4508. }
  4509. addCellsFromUIDL(uidl, aligns, col, visibleColumnIndex);
  4510. if (uidl.hasAttribute("selected") && !isSelected()) {
  4511. toggleSelection();
  4512. }
  4513. }
  4514. protected void updateStyleNames(String primaryStyleName) {
  4515. if (getStylePrimaryName().contains("odd")) {
  4516. setStyleName(primaryStyleName + "-row-odd");
  4517. } else {
  4518. setStyleName(primaryStyleName + "-row");
  4519. }
  4520. if (rowStyle != null) {
  4521. addStyleName(primaryStyleName + "-row-" + rowStyle);
  4522. }
  4523. for (int i = 0; i < rowElement.getChildCount(); i++) {
  4524. TableCellElement cell = (TableCellElement) rowElement
  4525. .getChild(i);
  4526. updateCellStyleNames(cell, primaryStyleName);
  4527. }
  4528. }
  4529. public TooltipInfo getTooltipInfo() {
  4530. return tooltipInfo;
  4531. }
  4532. /**
  4533. * Add a dummy row, used for measurements if Table is empty.
  4534. */
  4535. public VScrollTableRow() {
  4536. this(0);
  4537. addCell(null, "_", 'b', "", true, false);
  4538. }
  4539. protected void initCellWidths() {
  4540. final int cells = tHead.getVisibleCellCount();
  4541. for (int i = 0; i < cells; i++) {
  4542. int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
  4543. if (w < 0) {
  4544. w = 0;
  4545. }
  4546. setCellWidth(i, w);
  4547. }
  4548. }
  4549. protected void setCellWidth(int cellIx, int width) {
  4550. final Element cell = DOM.getChild(getElement(), cellIx);
  4551. Style wrapperStyle = cell.getFirstChildElement().getStyle();
  4552. int wrapperWidth = width;
  4553. if (BrowserInfo.get().isWebkit()
  4554. || BrowserInfo.get().isOpera10()) {
  4555. /*
  4556. * Some versions of Webkit and Opera ignore the width
  4557. * definition of zero width table cells. Instead, use 1px
  4558. * and compensate with a negative margin.
  4559. */
  4560. if (width == 0) {
  4561. wrapperWidth = 1;
  4562. wrapperStyle.setMarginRight(-1, Unit.PX);
  4563. } else {
  4564. wrapperStyle.clearMarginRight();
  4565. }
  4566. }
  4567. wrapperStyle.setPropertyPx("width", wrapperWidth);
  4568. cell.getStyle().setPropertyPx("width", width);
  4569. }
  4570. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  4571. int visibleColumnIndex) {
  4572. final Iterator<?> cells = uidl.getChildIterator();
  4573. while (cells.hasNext()) {
  4574. final Object cell = cells.next();
  4575. visibleColumnIndex++;
  4576. String columnId = visibleColOrder[visibleColumnIndex];
  4577. String style = "";
  4578. if (uidl.hasAttribute("style-" + columnId)) {
  4579. style = uidl.getStringAttribute("style-" + columnId);
  4580. }
  4581. String description = null;
  4582. if (uidl.hasAttribute("descr-" + columnId)) {
  4583. description = uidl.getStringAttribute("descr-"
  4584. + columnId);
  4585. }
  4586. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4587. if (cell instanceof String) {
  4588. addCell(uidl, cell.toString(), aligns[col++], style,
  4589. isRenderHtmlInCells(), sorted, description);
  4590. } else {
  4591. final ComponentConnector cellContent = client
  4592. .getPaintable((UIDL) cell);
  4593. addCell(uidl, cellContent.getWidget(), aligns[col++],
  4594. style, sorted, description);
  4595. }
  4596. }
  4597. }
  4598. /**
  4599. * Overriding this and returning true causes all text cells to be
  4600. * rendered as HTML.
  4601. *
  4602. * @return always returns false in the default implementation
  4603. */
  4604. protected boolean isRenderHtmlInCells() {
  4605. return false;
  4606. }
  4607. /**
  4608. * Detects whether row is visible in tables viewport.
  4609. *
  4610. * @return
  4611. */
  4612. public boolean isInViewPort() {
  4613. int absoluteTop = getAbsoluteTop();
  4614. int scrollPosition = scrollBodyPanel.getAbsoluteTop()
  4615. + scrollBodyPanel.getScrollPosition();
  4616. if (absoluteTop < scrollPosition) {
  4617. return false;
  4618. }
  4619. int maxVisible = scrollPosition
  4620. + scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
  4621. if (absoluteTop > maxVisible) {
  4622. return false;
  4623. }
  4624. return true;
  4625. }
  4626. /**
  4627. * Makes a check based on indexes whether the row is before the
  4628. * compared row.
  4629. *
  4630. * @param row1
  4631. * @return true if this rows index is smaller than in the row1
  4632. */
  4633. public boolean isBefore(VScrollTableRow row1) {
  4634. return getIndex() < row1.getIndex();
  4635. }
  4636. /**
  4637. * Sets the index of the row in the whole table. Currently used just
  4638. * to set even/odd classname
  4639. *
  4640. * @param indexInWholeTable
  4641. */
  4642. private void setIndex(int indexInWholeTable) {
  4643. index = indexInWholeTable;
  4644. boolean isOdd = indexInWholeTable % 2 == 0;
  4645. // Inverted logic to be backwards compatible with earlier 6.4.
  4646. // It is very strange because rows 1,3,5 are considered "even"
  4647. // and 2,4,6 "odd".
  4648. //
  4649. // First remove any old styles so that both styles aren't
  4650. // applied when indexes are updated.
  4651. String primaryStyleName = getStylePrimaryName();
  4652. if (primaryStyleName != null && !primaryStyleName.equals("")) {
  4653. removeStyleName(getStylePrimaryName());
  4654. }
  4655. if (!isOdd) {
  4656. addStyleName(VScrollTable.this.getStylePrimaryName()
  4657. + "-row-odd");
  4658. } else {
  4659. addStyleName(VScrollTable.this.getStylePrimaryName()
  4660. + "-row");
  4661. }
  4662. }
  4663. public int getIndex() {
  4664. return index;
  4665. }
  4666. @Override
  4667. protected void onDetach() {
  4668. super.onDetach();
  4669. client.getContextMenu().ensureHidden(this);
  4670. }
  4671. public String getKey() {
  4672. return String.valueOf(rowKey);
  4673. }
  4674. public void addCell(UIDL rowUidl, String text, char align,
  4675. String style, boolean textIsHTML, boolean sorted) {
  4676. addCell(rowUidl, text, align, style, textIsHTML, sorted, null);
  4677. }
  4678. public void addCell(UIDL rowUidl, String text, char align,
  4679. String style, boolean textIsHTML, boolean sorted,
  4680. String description) {
  4681. // String only content is optimized by not using Label widget
  4682. final TableCellElement td = DOM.createTD().cast();
  4683. initCellWithText(text, align, style, textIsHTML, sorted,
  4684. description, td);
  4685. }
  4686. protected void initCellWithText(String text, char align,
  4687. String style, boolean textIsHTML, boolean sorted,
  4688. String description, final TableCellElement td) {
  4689. final Element container = DOM.createDiv();
  4690. container.setClassName(VScrollTable.this.getStylePrimaryName()
  4691. + "-cell-wrapper");
  4692. td.setClassName(VScrollTable.this.getStylePrimaryName()
  4693. + "-cell-content");
  4694. if (style != null && !style.equals("")) {
  4695. td.addClassName(VScrollTable.this.getStylePrimaryName()
  4696. + "-cell-content-" + style);
  4697. }
  4698. if (sorted) {
  4699. td.addClassName(VScrollTable.this.getStylePrimaryName()
  4700. + "-cell-content-sorted");
  4701. }
  4702. if (textIsHTML) {
  4703. container.setInnerHTML(text);
  4704. } else {
  4705. container.setInnerText(text);
  4706. }
  4707. if (align != ALIGN_LEFT) {
  4708. switch (align) {
  4709. case ALIGN_CENTER:
  4710. container.getStyle().setProperty("textAlign", "center");
  4711. break;
  4712. case ALIGN_RIGHT:
  4713. default:
  4714. container.getStyle().setProperty("textAlign", "right");
  4715. break;
  4716. }
  4717. }
  4718. setTooltip(td, description);
  4719. td.appendChild(container);
  4720. getElement().appendChild(td);
  4721. }
  4722. protected void updateCellStyleNames(TableCellElement td,
  4723. String primaryStyleName) {
  4724. Element container = td.getFirstChild().cast();
  4725. container.setClassName(primaryStyleName + "-cell-wrapper");
  4726. /*
  4727. * Replace old primary style name with new one
  4728. */
  4729. String className = td.getClassName();
  4730. String oldPrimaryName = className.split("-cell-content")[0];
  4731. td.setClassName(className.replaceAll(oldPrimaryName,
  4732. primaryStyleName));
  4733. }
  4734. public void addCell(UIDL rowUidl, Widget w, char align,
  4735. String style, boolean sorted, String description) {
  4736. final TableCellElement td = DOM.createTD().cast();
  4737. initCellWithWidget(w, align, style, sorted, td);
  4738. setTooltip(td, description);
  4739. }
  4740. private void setTooltip(TableCellElement td, String description) {
  4741. if (description != null && !description.equals("")) {
  4742. TooltipInfo info = new TooltipInfo(description);
  4743. cellToolTips.put(td, info);
  4744. } else {
  4745. cellToolTips.remove(td);
  4746. }
  4747. }
  4748. protected void initCellWithWidget(Widget w, char align,
  4749. String style, boolean sorted, final TableCellElement td) {
  4750. final Element container = DOM.createDiv();
  4751. String className = VScrollTable.this.getStylePrimaryName()
  4752. + "-cell-content";
  4753. if (style != null && !style.equals("")) {
  4754. className += " " + VScrollTable.this.getStylePrimaryName()
  4755. + "-cell-content-" + style;
  4756. }
  4757. if (sorted) {
  4758. className += " " + VScrollTable.this.getStylePrimaryName()
  4759. + "-cell-content-sorted";
  4760. }
  4761. td.setClassName(className);
  4762. container.setClassName(VScrollTable.this.getStylePrimaryName()
  4763. + "-cell-wrapper");
  4764. // TODO most components work with this, but not all (e.g.
  4765. // Select)
  4766. // Old comment: make widget cells respect align.
  4767. // text-align:center for IE, margin: auto for others
  4768. if (align != ALIGN_LEFT) {
  4769. switch (align) {
  4770. case ALIGN_CENTER:
  4771. container.getStyle().setProperty("textAlign", "center");
  4772. break;
  4773. case ALIGN_RIGHT:
  4774. default:
  4775. container.getStyle().setProperty("textAlign", "right");
  4776. break;
  4777. }
  4778. }
  4779. td.appendChild(container);
  4780. getElement().appendChild(td);
  4781. // ensure widget not attached to another element (possible tBody
  4782. // change)
  4783. w.removeFromParent();
  4784. container.appendChild(w.getElement());
  4785. adopt(w);
  4786. childWidgets.add(w);
  4787. }
  4788. @Override
  4789. public Iterator<Widget> iterator() {
  4790. return childWidgets.iterator();
  4791. }
  4792. @Override
  4793. public boolean remove(Widget w) {
  4794. if (childWidgets.contains(w)) {
  4795. orphan(w);
  4796. DOM.removeChild(DOM.getParent(w.getElement()),
  4797. w.getElement());
  4798. childWidgets.remove(w);
  4799. return true;
  4800. } else {
  4801. return false;
  4802. }
  4803. }
  4804. /**
  4805. * If there are registered click listeners, sends a click event and
  4806. * returns true. Otherwise, does nothing and returns false.
  4807. *
  4808. * @param event
  4809. * @param targetTdOrTr
  4810. * @param immediate
  4811. * Whether the event is sent immediately
  4812. * @return Whether a click event was sent
  4813. */
  4814. private boolean handleClickEvent(Event event, Element targetTdOrTr,
  4815. boolean immediate) {
  4816. if (!client.hasEventListeners(VScrollTable.this,
  4817. TableConstants.ITEM_CLICK_EVENT_ID)) {
  4818. // Don't send an event if nobody is listening
  4819. return false;
  4820. }
  4821. // This row was clicked
  4822. client.updateVariable(paintableId, "clickedKey", "" + rowKey,
  4823. false);
  4824. if (getElement() == targetTdOrTr.getParentElement()) {
  4825. // A specific column was clicked
  4826. int childIndex = DOM.getChildIndex(getElement(),
  4827. targetTdOrTr);
  4828. String colKey = null;
  4829. colKey = tHead.getHeaderCell(childIndex).getColKey();
  4830. client.updateVariable(paintableId, "clickedColKey", colKey,
  4831. false);
  4832. }
  4833. MouseEventDetails details = MouseEventDetailsBuilder
  4834. .buildMouseEventDetails(event);
  4835. client.updateVariable(paintableId, "clickEvent",
  4836. details.toString(), immediate);
  4837. return true;
  4838. }
  4839. public TooltipInfo getTooltip(
  4840. com.google.gwt.dom.client.Element target) {
  4841. TooltipInfo info = null;
  4842. final Element targetTdOrTr = getTdOrTr((Element) target.cast());
  4843. if (targetTdOrTr != null
  4844. && "td".equals(targetTdOrTr.getTagName().toLowerCase())) {
  4845. TableCellElement td = (TableCellElement) targetTdOrTr
  4846. .cast();
  4847. info = cellToolTips.get(td);
  4848. }
  4849. if (info == null) {
  4850. info = tooltipInfo;
  4851. }
  4852. return info;
  4853. }
  4854. private Element getTdOrTr(Element target) {
  4855. Element thisTrElement = getElement();
  4856. if (target == thisTrElement) {
  4857. // This was a on the TR element
  4858. return target;
  4859. }
  4860. // Iterate upwards until we find the TR element
  4861. Element element = target;
  4862. while (element != null
  4863. && element.getParentElement().cast() != thisTrElement) {
  4864. element = element.getParentElement().cast();
  4865. }
  4866. return element;
  4867. }
  4868. /**
  4869. * Special handler for touch devices that support native scrolling
  4870. *
  4871. * @return Whether the event was handled by this method.
  4872. */
  4873. private boolean handleTouchEvent(final Event event) {
  4874. boolean touchEventHandled = false;
  4875. if (enabled && hasNativeTouchScrolling) {
  4876. final Element targetTdOrTr = getEventTargetTdOrTr(event);
  4877. final int type = event.getTypeInt();
  4878. switch (type) {
  4879. case Event.ONTOUCHSTART:
  4880. touchEventHandled = true;
  4881. touchStart = event;
  4882. isDragging = false;
  4883. Touch touch = event.getChangedTouches().get(0);
  4884. // save position to fields, touches in events are same
  4885. // instance during the operation.
  4886. touchStartX = touch.getClientX();
  4887. touchStartY = touch.getClientY();
  4888. if (dragmode != 0) {
  4889. if (dragTouchTimeout == null) {
  4890. dragTouchTimeout = new Timer() {
  4891. @Override
  4892. public void run() {
  4893. if (touchStart != null) {
  4894. // Start a drag if a finger is held
  4895. // in place long enough, then moved
  4896. isDragging = true;
  4897. }
  4898. }
  4899. };
  4900. }
  4901. dragTouchTimeout.schedule(TOUCHSCROLL_TIMEOUT);
  4902. }
  4903. if (actionKeys != null) {
  4904. if (contextTouchTimeout == null) {
  4905. contextTouchTimeout = new Timer() {
  4906. @Override
  4907. public void run() {
  4908. if (touchStart != null) {
  4909. // Open the context menu if finger
  4910. // is held in place long enough.
  4911. showContextMenu(touchStart);
  4912. event.preventDefault();
  4913. touchStart = null;
  4914. }
  4915. }
  4916. };
  4917. }
  4918. contextTouchTimeout
  4919. .schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  4920. }
  4921. break;
  4922. case Event.ONTOUCHMOVE:
  4923. touchEventHandled = true;
  4924. if (isSignificantMove(event)) {
  4925. if (contextTouchTimeout != null) {
  4926. // Moved finger before the context menu timer
  4927. // expired, so let the browser handle this as a
  4928. // scroll.
  4929. contextTouchTimeout.cancel();
  4930. contextTouchTimeout = null;
  4931. }
  4932. if (!isDragging && dragTouchTimeout != null) {
  4933. // Moved finger before the drag timer expired,
  4934. // so let the browser handle this as a scroll.
  4935. dragTouchTimeout.cancel();
  4936. dragTouchTimeout = null;
  4937. }
  4938. if (dragmode != 0 && touchStart != null
  4939. && isDragging) {
  4940. event.preventDefault();
  4941. event.stopPropagation();
  4942. startRowDrag(touchStart, type, targetTdOrTr);
  4943. }
  4944. touchStart = null;
  4945. }
  4946. break;
  4947. case Event.ONTOUCHEND:
  4948. case Event.ONTOUCHCANCEL:
  4949. touchEventHandled = true;
  4950. if (contextTouchTimeout != null) {
  4951. contextTouchTimeout.cancel();
  4952. }
  4953. if (dragTouchTimeout != null) {
  4954. dragTouchTimeout.cancel();
  4955. }
  4956. if (touchStart != null) {
  4957. if (!BrowserInfo.get().isAndroid()) {
  4958. event.preventDefault();
  4959. event.stopPropagation();
  4960. Util.simulateClickFromTouchEvent(touchStart,
  4961. this);
  4962. }
  4963. touchStart = null;
  4964. }
  4965. isDragging = false;
  4966. break;
  4967. }
  4968. }
  4969. return touchEventHandled;
  4970. }
  4971. /*
  4972. * React on click that occur on content cells only
  4973. */
  4974. @Override
  4975. public void onBrowserEvent(final Event event) {
  4976. final boolean touchEventHandled = handleTouchEvent(event);
  4977. if (enabled && !touchEventHandled) {
  4978. final int type = event.getTypeInt();
  4979. final Element targetTdOrTr = getEventTargetTdOrTr(event);
  4980. if (type == Event.ONCONTEXTMENU) {
  4981. showContextMenu(event);
  4982. if (enabled
  4983. && (actionKeys != null || client
  4984. .hasEventListeners(
  4985. VScrollTable.this,
  4986. TableConstants.ITEM_CLICK_EVENT_ID))) {
  4987. /*
  4988. * Prevent browser context menu only if there are
  4989. * action handlers or item click listeners
  4990. * registered
  4991. */
  4992. event.stopPropagation();
  4993. event.preventDefault();
  4994. }
  4995. return;
  4996. }
  4997. boolean targetCellOrRowFound = targetTdOrTr != null;
  4998. switch (type) {
  4999. case Event.ONDBLCLICK:
  5000. if (targetCellOrRowFound) {
  5001. handleClickEvent(event, targetTdOrTr, true);
  5002. }
  5003. break;
  5004. case Event.ONMOUSEUP:
  5005. if (targetCellOrRowFound) {
  5006. /*
  5007. * Queue here, send at the same time as the
  5008. * corresponding value change event - see #7127
  5009. */
  5010. boolean clickEventSent = handleClickEvent(event,
  5011. targetTdOrTr, false);
  5012. if (event.getButton() == Event.BUTTON_LEFT
  5013. && isSelectable()) {
  5014. // Ctrl+Shift click
  5015. if ((event.getCtrlKey() || event.getMetaKey())
  5016. && event.getShiftKey()
  5017. && isMultiSelectModeDefault()) {
  5018. toggleShiftSelection(false);
  5019. setRowFocus(this);
  5020. // Ctrl click
  5021. } else if ((event.getCtrlKey() || event
  5022. .getMetaKey())
  5023. && isMultiSelectModeDefault()) {
  5024. boolean wasSelected = isSelected();
  5025. toggleSelection();
  5026. setRowFocus(this);
  5027. /*
  5028. * next possible range select must start on
  5029. * this row
  5030. */
  5031. selectionRangeStart = this;
  5032. if (wasSelected) {
  5033. removeRowFromUnsentSelectionRanges(this);
  5034. }
  5035. } else if ((event.getCtrlKey() || event
  5036. .getMetaKey()) && isSingleSelectMode()) {
  5037. // Ctrl (or meta) click (Single selection)
  5038. if (!isSelected()
  5039. || (isSelected() && nullSelectionAllowed)) {
  5040. if (!isSelected()) {
  5041. deselectAll();
  5042. }
  5043. toggleSelection();
  5044. setRowFocus(this);
  5045. }
  5046. } else if (event.getShiftKey()
  5047. && isMultiSelectModeDefault()) {
  5048. // Shift click
  5049. toggleShiftSelection(true);
  5050. } else {
  5051. // click
  5052. boolean currentlyJustThisRowSelected = selectedRowKeys
  5053. .size() == 1
  5054. && selectedRowKeys
  5055. .contains(getKey());
  5056. if (!currentlyJustThisRowSelected) {
  5057. if (isSingleSelectMode()
  5058. || isMultiSelectModeDefault()) {
  5059. /*
  5060. * For default multi select mode
  5061. * (ctrl/shift) and for single
  5062. * select mode we need to clear the
  5063. * previous selection before
  5064. * selecting a new one when the user
  5065. * clicks on a row. Only in
  5066. * multiselect/simple mode the old
  5067. * selection should remain after a
  5068. * normal click.
  5069. */
  5070. deselectAll();
  5071. }
  5072. toggleSelection();
  5073. } else if ((isSingleSelectMode() || isMultiSelectModeSimple())
  5074. && nullSelectionAllowed) {
  5075. toggleSelection();
  5076. }/*
  5077. * else NOP to avoid excessive server
  5078. * visits (selection is removed with
  5079. * CTRL/META click)
  5080. */
  5081. selectionRangeStart = this;
  5082. setRowFocus(this);
  5083. }
  5084. // Remove IE text selection hack
  5085. if (BrowserInfo.get().isIE()) {
  5086. ((Element) event.getEventTarget().cast())
  5087. .setPropertyJSO("onselectstart",
  5088. null);
  5089. }
  5090. // Queue value change
  5091. sendSelectedRows(false);
  5092. }
  5093. /*
  5094. * Send queued click and value change events if any
  5095. * If a click event is sent, send value change with
  5096. * it regardless of the immediate flag, see #7127
  5097. */
  5098. if (immediate || clickEventSent) {
  5099. client.sendPendingVariableChanges();
  5100. }
  5101. }
  5102. break;
  5103. case Event.ONTOUCHEND:
  5104. case Event.ONTOUCHCANCEL:
  5105. if (touchStart != null) {
  5106. /*
  5107. * Touch has not been handled as neither context or
  5108. * drag start, handle it as a click.
  5109. */
  5110. Util.simulateClickFromTouchEvent(touchStart, this);
  5111. touchStart = null;
  5112. }
  5113. if (contextTouchTimeout != null) {
  5114. contextTouchTimeout.cancel();
  5115. }
  5116. break;
  5117. case Event.ONTOUCHMOVE:
  5118. if (isSignificantMove(event)) {
  5119. /*
  5120. * TODO figure out scroll delegate don't eat events
  5121. * if row is selected. Null check for active
  5122. * delegate is as a workaround.
  5123. */
  5124. if (dragmode != 0
  5125. && touchStart != null
  5126. && (TouchScrollDelegate
  5127. .getActiveScrollDelegate() == null)) {
  5128. startRowDrag(touchStart, type, targetTdOrTr);
  5129. }
  5130. if (contextTouchTimeout != null) {
  5131. contextTouchTimeout.cancel();
  5132. }
  5133. /*
  5134. * Avoid clicks and drags by clearing touch start
  5135. * flag.
  5136. */
  5137. touchStart = null;
  5138. }
  5139. break;
  5140. case Event.ONTOUCHSTART:
  5141. touchStart = event;
  5142. Touch touch = event.getChangedTouches().get(0);
  5143. // save position to fields, touches in events are same
  5144. // isntance during the operation.
  5145. touchStartX = touch.getClientX();
  5146. touchStartY = touch.getClientY();
  5147. /*
  5148. * Prevent simulated mouse events.
  5149. */
  5150. touchStart.preventDefault();
  5151. if (dragmode != 0 || actionKeys != null) {
  5152. new Timer() {
  5153. @Override
  5154. public void run() {
  5155. TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
  5156. .getActiveScrollDelegate();
  5157. /*
  5158. * If there's a scroll delegate, check if
  5159. * we're actually scrolling and handle it.
  5160. * If no delegate, do nothing here and let
  5161. * the row handle potential drag'n'drop or
  5162. * context menu.
  5163. */
  5164. if (activeScrollDelegate != null) {
  5165. if (activeScrollDelegate.isMoved()) {
  5166. /*
  5167. * Prevent the row from handling
  5168. * touch move/end events (the
  5169. * delegate handles those) and from
  5170. * doing drag'n'drop or opening a
  5171. * context menu.
  5172. */
  5173. touchStart = null;
  5174. } else {
  5175. /*
  5176. * Scrolling hasn't started, so
  5177. * cancel delegate and let the row
  5178. * handle potential drag'n'drop or
  5179. * context menu.
  5180. */
  5181. activeScrollDelegate
  5182. .stopScrolling();
  5183. }
  5184. }
  5185. }
  5186. }.schedule(TOUCHSCROLL_TIMEOUT);
  5187. if (contextTouchTimeout == null
  5188. && actionKeys != null) {
  5189. contextTouchTimeout = new Timer() {
  5190. @Override
  5191. public void run() {
  5192. if (touchStart != null) {
  5193. showContextMenu(touchStart);
  5194. touchStart = null;
  5195. }
  5196. }
  5197. };
  5198. }
  5199. if (contextTouchTimeout != null) {
  5200. contextTouchTimeout.cancel();
  5201. contextTouchTimeout
  5202. .schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  5203. }
  5204. }
  5205. break;
  5206. case Event.ONMOUSEDOWN:
  5207. if (targetCellOrRowFound) {
  5208. setRowFocus(this);
  5209. ensureFocus();
  5210. if (dragmode != 0
  5211. && (event.getButton() == NativeEvent.BUTTON_LEFT)) {
  5212. startRowDrag(event, type, targetTdOrTr);
  5213. } else if (event.getCtrlKey()
  5214. || event.getShiftKey()
  5215. || event.getMetaKey()
  5216. && isMultiSelectModeDefault()) {
  5217. // Prevent default text selection in Firefox
  5218. event.preventDefault();
  5219. // Prevent default text selection in IE
  5220. if (BrowserInfo.get().isIE()) {
  5221. ((Element) event.getEventTarget().cast())
  5222. .setPropertyJSO(
  5223. "onselectstart",
  5224. getPreventTextSelectionIEHack());
  5225. }
  5226. event.stopPropagation();
  5227. }
  5228. }
  5229. break;
  5230. case Event.ONMOUSEOUT:
  5231. break;
  5232. default:
  5233. break;
  5234. }
  5235. }
  5236. super.onBrowserEvent(event);
  5237. }
  5238. private boolean isSignificantMove(Event event) {
  5239. if (touchStart == null) {
  5240. // no touch start
  5241. return false;
  5242. }
  5243. /*
  5244. * TODO calculate based on real distance instead of separate
  5245. * axis checks
  5246. */
  5247. Touch touch = event.getChangedTouches().get(0);
  5248. if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  5249. return true;
  5250. }
  5251. if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  5252. return true;
  5253. }
  5254. return false;
  5255. }
  5256. /**
  5257. * Checks if the row represented by the row key has been selected
  5258. *
  5259. * @param key
  5260. * The generated row key
  5261. */
  5262. private boolean rowKeyIsSelected(int rowKey) {
  5263. // Check single selections
  5264. if (selectedRowKeys.contains("" + rowKey)) {
  5265. return true;
  5266. }
  5267. // Check range selections
  5268. for (SelectionRange r : selectedRowRanges) {
  5269. if (r.inRange(getRenderedRowByKey("" + rowKey))) {
  5270. return true;
  5271. }
  5272. }
  5273. return false;
  5274. }
  5275. protected void startRowDrag(Event event, final int type,
  5276. Element targetTdOrTr) {
  5277. VTransferable transferable = new VTransferable();
  5278. transferable.setDragSource(ConnectorMap.get(client)
  5279. .getConnector(VScrollTable.this));
  5280. transferable.setData("itemId", "" + rowKey);
  5281. NodeList<TableCellElement> cells = rowElement.getCells();
  5282. for (int i = 0; i < cells.getLength(); i++) {
  5283. if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
  5284. HeaderCell headerCell = tHead.getHeaderCell(i);
  5285. transferable.setData("propertyId", headerCell.cid);
  5286. break;
  5287. }
  5288. }
  5289. VDragEvent ev = VDragAndDropManager.get().startDrag(
  5290. transferable, event, true);
  5291. if (dragmode == DRAGMODE_MULTIROW && isMultiSelectModeAny()
  5292. && rowKeyIsSelected(rowKey)) {
  5293. // Create a drag image of ALL rows
  5294. ev.createDragImage(
  5295. (Element) scrollBody.tBodyElement.cast(), true);
  5296. // Hide rows which are not selected
  5297. Element dragImage = ev.getDragImage();
  5298. int i = 0;
  5299. for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
  5300. .hasNext();) {
  5301. VScrollTableRow next = (VScrollTableRow) iterator
  5302. .next();
  5303. Element child = (Element) dragImage.getChild(i++);
  5304. if (!rowKeyIsSelected(next.rowKey)) {
  5305. child.getStyle().setVisibility(Visibility.HIDDEN);
  5306. }
  5307. }
  5308. } else {
  5309. ev.createDragImage(getElement(), true);
  5310. }
  5311. if (type == Event.ONMOUSEDOWN) {
  5312. event.preventDefault();
  5313. }
  5314. event.stopPropagation();
  5315. }
  5316. /**
  5317. * Finds the TD that the event interacts with. Returns null if the
  5318. * target of the event should not be handled. If the event target is
  5319. * the row directly this method returns the TR element instead of
  5320. * the TD.
  5321. *
  5322. * @param event
  5323. * @return TD or TR element that the event targets (the actual event
  5324. * target is this element or a child of it)
  5325. */
  5326. private Element getEventTargetTdOrTr(Event event) {
  5327. final Element eventTarget = event.getEventTarget().cast();
  5328. Widget widget = Util.findWidget(eventTarget, null);
  5329. final Element thisTrElement = getElement();
  5330. if (widget != this) {
  5331. /*
  5332. * This is a workaround to make Labels, read only TextFields
  5333. * and Embedded in a Table clickable (see #2688). It is
  5334. * really not a fix as it does not work with a custom read
  5335. * only components (not extending VLabel/VEmbedded).
  5336. */
  5337. while (widget != null && widget.getParent() != this) {
  5338. widget = widget.getParent();
  5339. }
  5340. if (!(widget instanceof VLabel)
  5341. && !(widget instanceof VEmbedded)
  5342. && !(widget instanceof VTextField && ((VTextField) widget)
  5343. .isReadOnly())) {
  5344. return null;
  5345. }
  5346. }
  5347. return getTdOrTr(eventTarget);
  5348. }
  5349. public void showContextMenu(Event event) {
  5350. if (enabled && actionKeys != null) {
  5351. // Show context menu if there are registered action handlers
  5352. int left = Util.getTouchOrMouseClientX(event)
  5353. + Window.getScrollLeft();
  5354. int top = Util.getTouchOrMouseClientY(event)
  5355. + Window.getScrollTop();
  5356. showContextMenu(left, top);
  5357. }
  5358. }
  5359. public void showContextMenu(int left, int top) {
  5360. VContextMenu menu = client.getContextMenu();
  5361. contextMenu = new ContextMenuDetails(menu, getKey(), left, top);
  5362. menu.showAt(this, left, top);
  5363. }
  5364. /**
  5365. * Has the row been selected?
  5366. *
  5367. * @return Returns true if selected, else false
  5368. */
  5369. public boolean isSelected() {
  5370. return selected;
  5371. }
  5372. /**
  5373. * Toggle the selection of the row
  5374. */
  5375. public void toggleSelection() {
  5376. selected = !selected;
  5377. selectionChanged = true;
  5378. if (selected) {
  5379. selectedRowKeys.add(String.valueOf(rowKey));
  5380. addStyleName("v-selected");
  5381. } else {
  5382. removeStyleName("v-selected");
  5383. selectedRowKeys.remove(String.valueOf(rowKey));
  5384. }
  5385. }
  5386. /**
  5387. * Is called when a user clicks an item when holding SHIFT key down.
  5388. * This will select a new range from the last focused row
  5389. *
  5390. * @param deselectPrevious
  5391. * Should the previous selected range be deselected
  5392. */
  5393. private void toggleShiftSelection(boolean deselectPrevious) {
  5394. /*
  5395. * Ensures that we are in multiselect mode and that we have a
  5396. * previous selection which was not a deselection
  5397. */
  5398. if (isSingleSelectMode()) {
  5399. // No previous selection found
  5400. deselectAll();
  5401. toggleSelection();
  5402. return;
  5403. }
  5404. // Set the selectable range
  5405. VScrollTableRow endRow = this;
  5406. VScrollTableRow startRow = selectionRangeStart;
  5407. if (startRow == null) {
  5408. startRow = focusedRow;
  5409. // If start row is null then we have a multipage selection
  5410. // from
  5411. // above
  5412. if (startRow == null) {
  5413. startRow = (VScrollTableRow) scrollBody.iterator()
  5414. .next();
  5415. setRowFocus(endRow);
  5416. }
  5417. }
  5418. // Deselect previous items if so desired
  5419. if (deselectPrevious) {
  5420. deselectAll();
  5421. }
  5422. // we'll ensure GUI state from top down even though selection
  5423. // was the opposite way
  5424. if (!startRow.isBefore(endRow)) {
  5425. VScrollTableRow tmp = startRow;
  5426. startRow = endRow;
  5427. endRow = tmp;
  5428. }
  5429. SelectionRange range = new SelectionRange(startRow, endRow);
  5430. for (Widget w : scrollBody) {
  5431. VScrollTableRow row = (VScrollTableRow) w;
  5432. if (range.inRange(row)) {
  5433. if (!row.isSelected()) {
  5434. row.toggleSelection();
  5435. }
  5436. selectedRowKeys.add(row.getKey());
  5437. }
  5438. }
  5439. // Add range
  5440. if (startRow != endRow) {
  5441. selectedRowRanges.add(range);
  5442. }
  5443. }
  5444. /*
  5445. * (non-Javadoc)
  5446. *
  5447. * @see com.vaadin.client.ui.IActionOwner#getActions ()
  5448. */
  5449. @Override
  5450. public Action[] getActions() {
  5451. if (actionKeys == null) {
  5452. return new Action[] {};
  5453. }
  5454. final Action[] actions = new Action[actionKeys.length];
  5455. for (int i = 0; i < actions.length; i++) {
  5456. final String actionKey = actionKeys[i];
  5457. final TreeAction a = new TreeAction(this,
  5458. String.valueOf(rowKey), actionKey) {
  5459. @Override
  5460. public void execute() {
  5461. super.execute();
  5462. lazyRevertFocusToRow(VScrollTableRow.this);
  5463. }
  5464. };
  5465. a.setCaption(getActionCaption(actionKey));
  5466. a.setIconUrl(getActionIcon(actionKey));
  5467. actions[i] = a;
  5468. }
  5469. return actions;
  5470. }
  5471. @Override
  5472. public ApplicationConnection getClient() {
  5473. return client;
  5474. }
  5475. @Override
  5476. public String getPaintableId() {
  5477. return paintableId;
  5478. }
  5479. private int getColIndexOf(Widget child) {
  5480. com.google.gwt.dom.client.Element widgetCell = child
  5481. .getElement().getParentElement().getParentElement();
  5482. NodeList<TableCellElement> cells = rowElement.getCells();
  5483. for (int i = 0; i < cells.getLength(); i++) {
  5484. if (cells.getItem(i) == widgetCell) {
  5485. return i;
  5486. }
  5487. }
  5488. return -1;
  5489. }
  5490. public Widget getWidgetForPaintable() {
  5491. return this;
  5492. }
  5493. }
  5494. protected class VScrollTableGeneratedRow extends VScrollTableRow {
  5495. private boolean spanColumns;
  5496. private boolean htmlContentAllowed;
  5497. public VScrollTableGeneratedRow(UIDL uidl, char[] aligns) {
  5498. super(uidl, aligns);
  5499. addStyleName("v-table-generated-row");
  5500. }
  5501. public boolean isSpanColumns() {
  5502. return spanColumns;
  5503. }
  5504. @Override
  5505. protected void initCellWidths() {
  5506. if (spanColumns) {
  5507. setSpannedColumnWidthAfterDOMFullyInited();
  5508. } else {
  5509. super.initCellWidths();
  5510. }
  5511. }
  5512. private void setSpannedColumnWidthAfterDOMFullyInited() {
  5513. // Defer setting width on spanned columns to make sure that
  5514. // they are added to the DOM before trying to calculate
  5515. // widths.
  5516. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  5517. @Override
  5518. public void execute() {
  5519. if (showRowHeaders) {
  5520. setCellWidth(0, tHead.getHeaderCell(0)
  5521. .getWidthWithIndent());
  5522. calcAndSetSpanWidthOnCell(1);
  5523. } else {
  5524. calcAndSetSpanWidthOnCell(0);
  5525. }
  5526. }
  5527. });
  5528. }
  5529. @Override
  5530. protected boolean isRenderHtmlInCells() {
  5531. return htmlContentAllowed;
  5532. }
  5533. @Override
  5534. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  5535. int visibleColumnIndex) {
  5536. htmlContentAllowed = uidl.getBooleanAttribute("gen_html");
  5537. spanColumns = uidl.getBooleanAttribute("gen_span");
  5538. final Iterator<?> cells = uidl.getChildIterator();
  5539. if (spanColumns) {
  5540. int colCount = uidl.getChildCount();
  5541. if (cells.hasNext()) {
  5542. final Object cell = cells.next();
  5543. if (cell instanceof String) {
  5544. addSpannedCell(uidl, cell.toString(), aligns[0],
  5545. "", htmlContentAllowed, false, null,
  5546. colCount);
  5547. } else {
  5548. addSpannedCell(uidl, (Widget) cell, aligns[0], "",
  5549. false, colCount);
  5550. }
  5551. }
  5552. } else {
  5553. super.addCellsFromUIDL(uidl, aligns, col,
  5554. visibleColumnIndex);
  5555. }
  5556. }
  5557. private void addSpannedCell(UIDL rowUidl, Widget w, char align,
  5558. String style, boolean sorted, int colCount) {
  5559. TableCellElement td = DOM.createTD().cast();
  5560. td.setColSpan(colCount);
  5561. initCellWithWidget(w, align, style, sorted, td);
  5562. }
  5563. private void addSpannedCell(UIDL rowUidl, String text, char align,
  5564. String style, boolean textIsHTML, boolean sorted,
  5565. String description, int colCount) {
  5566. // String only content is optimized by not using Label widget
  5567. final TableCellElement td = DOM.createTD().cast();
  5568. td.setColSpan(colCount);
  5569. initCellWithText(text, align, style, textIsHTML, sorted,
  5570. description, td);
  5571. }
  5572. @Override
  5573. protected void setCellWidth(int cellIx, int width) {
  5574. if (isSpanColumns()) {
  5575. if (showRowHeaders) {
  5576. if (cellIx == 0) {
  5577. super.setCellWidth(0, width);
  5578. } else {
  5579. // We need to recalculate the spanning TDs width for
  5580. // every cellIx in order to support column resizing.
  5581. calcAndSetSpanWidthOnCell(1);
  5582. }
  5583. } else {
  5584. // Same as above.
  5585. calcAndSetSpanWidthOnCell(0);
  5586. }
  5587. } else {
  5588. super.setCellWidth(cellIx, width);
  5589. }
  5590. }
  5591. private void calcAndSetSpanWidthOnCell(final int cellIx) {
  5592. int spanWidth = 0;
  5593. for (int ix = (showRowHeaders ? 1 : 0); ix < tHead
  5594. .getVisibleCellCount(); ix++) {
  5595. spanWidth += tHead.getHeaderCell(ix).getOffsetWidth();
  5596. }
  5597. Util.setWidthExcludingPaddingAndBorder((Element) getElement()
  5598. .getChild(cellIx), spanWidth, 13, false);
  5599. }
  5600. }
  5601. /**
  5602. * Ensure the component has a focus.
  5603. *
  5604. * TODO the current implementation simply always calls focus for the
  5605. * component. In case the Table at some point implements focus/blur
  5606. * listeners, this method needs to be evolved to conditionally call
  5607. * focus only if not currently focused.
  5608. */
  5609. protected void ensureFocus() {
  5610. if (!hasFocus) {
  5611. scrollBodyPanel.setFocus(true);
  5612. }
  5613. }
  5614. }
  5615. /**
  5616. * Deselects all items
  5617. */
  5618. public void deselectAll() {
  5619. for (Widget w : scrollBody) {
  5620. VScrollTableRow row = (VScrollTableRow) w;
  5621. if (row.isSelected()) {
  5622. row.toggleSelection();
  5623. }
  5624. }
  5625. // still ensure all selects are removed from (not necessary rendered)
  5626. selectedRowKeys.clear();
  5627. selectedRowRanges.clear();
  5628. // also notify server that it clears all previous selections (the client
  5629. // side does not know about the invisible ones)
  5630. instructServerToForgetPreviousSelections();
  5631. }
  5632. /**
  5633. * Used in multiselect mode when the client side knows that all selections
  5634. * are in the next request.
  5635. */
  5636. private void instructServerToForgetPreviousSelections() {
  5637. client.updateVariable(paintableId, "clearSelections", true, false);
  5638. }
  5639. /**
  5640. * Determines the pagelength when the table height is fixed.
  5641. */
  5642. public void updatePageLength() {
  5643. // Only update if visible and enabled
  5644. if (!isVisible() || !enabled) {
  5645. return;
  5646. }
  5647. if (scrollBody == null) {
  5648. return;
  5649. }
  5650. if (isDynamicHeight()) {
  5651. return;
  5652. }
  5653. int rowHeight = (int) Math.round(scrollBody.getRowHeight());
  5654. int bodyH = scrollBodyPanel.getOffsetHeight();
  5655. int rowsAtOnce = bodyH / rowHeight;
  5656. boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
  5657. if (anotherPartlyVisible) {
  5658. rowsAtOnce++;
  5659. }
  5660. if (pageLength != rowsAtOnce) {
  5661. pageLength = rowsAtOnce;
  5662. client.updateVariable(paintableId, "pagelength", pageLength, false);
  5663. if (!rendering) {
  5664. int currentlyVisible = scrollBody.getLastRendered()
  5665. - scrollBody.getFirstRendered();
  5666. if (currentlyVisible < pageLength
  5667. && currentlyVisible < totalRows) {
  5668. // shake scrollpanel to fill empty space
  5669. scrollBodyPanel.setScrollPosition(scrollTop + 1);
  5670. scrollBodyPanel.setScrollPosition(scrollTop - 1);
  5671. }
  5672. sizeNeedsInit = true;
  5673. }
  5674. }
  5675. }
  5676. /** For internal use only. May be removed or replaced in the future. */
  5677. public void updateWidth() {
  5678. if (!isVisible()) {
  5679. /*
  5680. * Do not update size when the table is hidden as all column widths
  5681. * will be set to zero and they won't be recalculated when the table
  5682. * is set visible again (until the size changes again)
  5683. */
  5684. return;
  5685. }
  5686. if (!isDynamicWidth()) {
  5687. int innerPixels = getOffsetWidth() - getBorderWidth();
  5688. if (innerPixels < 0) {
  5689. innerPixels = 0;
  5690. }
  5691. setContentWidth(innerPixels);
  5692. // readjust undefined width columns
  5693. triggerLazyColumnAdjustment(false);
  5694. } else {
  5695. sizeNeedsInit = true;
  5696. // readjust undefined width columns
  5697. triggerLazyColumnAdjustment(false);
  5698. }
  5699. /*
  5700. * setting width may affect wheter the component has scrollbars -> needs
  5701. * scrolling or not
  5702. */
  5703. setProperTabIndex();
  5704. }
  5705. private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
  5706. private final Timer lazyAdjustColumnWidths = new Timer() {
  5707. /**
  5708. * Check for column widths, and available width, to see if we can fix
  5709. * column widths "optimally". Doing this lazily to avoid expensive
  5710. * calculation when resizing is not yet finished.
  5711. */
  5712. @Override
  5713. public void run() {
  5714. if (scrollBody == null) {
  5715. // Try again later if we get here before scrollBody has been
  5716. // initalized
  5717. triggerLazyColumnAdjustment(false);
  5718. return;
  5719. }
  5720. Iterator<Widget> headCells = tHead.iterator();
  5721. int usedMinimumWidth = 0;
  5722. int totalExplicitColumnsWidths = 0;
  5723. float expandRatioDivider = 0;
  5724. int colIndex = 0;
  5725. int hierarchyColumnIndent = scrollBody.getMaxIndent();
  5726. int hierarchyColumnIndex = getHierarchyColumnIndex();
  5727. HeaderCell hierarchyHeaderInNeedOfFurtherHandling = null;
  5728. while (headCells.hasNext()) {
  5729. final HeaderCell hCell = (HeaderCell) headCells.next();
  5730. boolean hasIndent = hierarchyColumnIndent > 0
  5731. && hCell.isHierarchyColumn();
  5732. if (hCell.isDefinedWidth()) {
  5733. // get width without indent to find out whether adjustments
  5734. // are needed (requires special handling further ahead)
  5735. int w = hCell.getWidth();
  5736. if (hasIndent && w < hierarchyColumnIndent) {
  5737. // enforce indent if necessary
  5738. w = hierarchyColumnIndent;
  5739. hierarchyHeaderInNeedOfFurtherHandling = hCell;
  5740. }
  5741. totalExplicitColumnsWidths += w;
  5742. usedMinimumWidth += w;
  5743. } else {
  5744. // natural width already includes indent if any
  5745. int naturalColumnWidth = hCell
  5746. .getNaturalColumnWidth(colIndex);
  5747. usedMinimumWidth += naturalColumnWidth;
  5748. expandRatioDivider += hCell.getExpandRatio();
  5749. if (hasIndent) {
  5750. hierarchyHeaderInNeedOfFurtherHandling = hCell;
  5751. }
  5752. }
  5753. colIndex++;
  5754. }
  5755. int availW = scrollBody.getAvailableWidth();
  5756. // Hey IE, are you really sure about this?
  5757. availW = scrollBody.getAvailableWidth();
  5758. int visibleCellCount = tHead.getVisibleCellCount();
  5759. int totalExtraWidth = scrollBody.getCellExtraWidth()
  5760. * visibleCellCount;
  5761. if (willHaveScrollbars()) {
  5762. totalExtraWidth += Util.getNativeScrollbarSize();
  5763. }
  5764. availW -= totalExtraWidth;
  5765. int forceScrollBodyWidth = -1;
  5766. int extraSpace = availW - usedMinimumWidth;
  5767. if (extraSpace < 0) {
  5768. if (getTotalRows() == 0) {
  5769. /*
  5770. * Too wide header combined with no rows in the table.
  5771. *
  5772. * No horizontal scrollbars would be displayed because
  5773. * there's no rows that grows too wide causing the
  5774. * scrollBody container div to overflow. Must explicitely
  5775. * force a width to a scrollbar. (see #9187)
  5776. */
  5777. forceScrollBodyWidth = usedMinimumWidth + totalExtraWidth;
  5778. }
  5779. extraSpace = 0;
  5780. }
  5781. if (forceScrollBodyWidth > 0) {
  5782. scrollBody.container.getStyle().setWidth(forceScrollBodyWidth,
  5783. Unit.PX);
  5784. } else {
  5785. // Clear width that might have been set to force horizontal
  5786. // scrolling if there are no rows
  5787. scrollBody.container.getStyle().clearWidth();
  5788. }
  5789. int totalUndefinedNaturalWidths = usedMinimumWidth
  5790. - totalExplicitColumnsWidths;
  5791. if (hierarchyHeaderInNeedOfFurtherHandling != null
  5792. && !hierarchyHeaderInNeedOfFurtherHandling.isDefinedWidth()) {
  5793. // ensure the cell gets enough space for the indent
  5794. int w = hierarchyHeaderInNeedOfFurtherHandling
  5795. .getNaturalColumnWidth(hierarchyColumnIndex);
  5796. int newSpace = Math.round(w + (float) extraSpace * (float) w
  5797. / totalUndefinedNaturalWidths);
  5798. if (newSpace >= hierarchyColumnIndent) {
  5799. // no special handling required
  5800. hierarchyHeaderInNeedOfFurtherHandling = null;
  5801. } else {
  5802. // treat as a defined width column of indent's width
  5803. totalExplicitColumnsWidths += hierarchyColumnIndent;
  5804. usedMinimumWidth -= w - hierarchyColumnIndent;
  5805. totalUndefinedNaturalWidths = usedMinimumWidth
  5806. - totalExplicitColumnsWidths;
  5807. expandRatioDivider += hierarchyHeaderInNeedOfFurtherHandling
  5808. .getExpandRatio();
  5809. extraSpace = Math.max(availW - usedMinimumWidth, 0);
  5810. }
  5811. }
  5812. // we have some space that can be divided optimally
  5813. HeaderCell hCell;
  5814. colIndex = 0;
  5815. headCells = tHead.iterator();
  5816. int checksum = 0;
  5817. while (headCells.hasNext()) {
  5818. hCell = (HeaderCell) headCells.next();
  5819. if (!hCell.isDefinedWidth()) {
  5820. int w = hCell.getNaturalColumnWidth(colIndex);
  5821. int newSpace;
  5822. if (expandRatioDivider > 0) {
  5823. // divide excess space by expand ratios
  5824. newSpace = Math.round((w + extraSpace
  5825. * hCell.getExpandRatio() / expandRatioDivider));
  5826. } else {
  5827. if (hierarchyHeaderInNeedOfFurtherHandling == hCell) {
  5828. // still exists, so needs exactly the indent's width
  5829. newSpace = hierarchyColumnIndent;
  5830. } else if (totalUndefinedNaturalWidths != 0) {
  5831. // divide relatively to natural column widths
  5832. newSpace = Math.round(w + (float) extraSpace
  5833. * (float) w / totalUndefinedNaturalWidths);
  5834. } else {
  5835. newSpace = w;
  5836. }
  5837. }
  5838. checksum += newSpace;
  5839. setColWidth(colIndex, newSpace, false);
  5840. } else {
  5841. if (hierarchyHeaderInNeedOfFurtherHandling == hCell) {
  5842. // defined with enforced into indent width
  5843. checksum += hierarchyColumnIndent;
  5844. setColWidth(colIndex, hierarchyColumnIndent, false);
  5845. } else {
  5846. int cellWidth = hCell.getWidthWithIndent();
  5847. checksum += cellWidth;
  5848. if (hCell.isHierarchyColumn()) {
  5849. // update in case the indent has changed
  5850. // (not detectable earlier)
  5851. setColWidth(colIndex, cellWidth, true);
  5852. }
  5853. }
  5854. }
  5855. colIndex++;
  5856. }
  5857. if (extraSpace > 0 && checksum != availW) {
  5858. /*
  5859. * There might be in some cases a rounding error of 1px when
  5860. * extra space is divided so if there is one then we give the
  5861. * first undefined column 1 more pixel
  5862. */
  5863. headCells = tHead.iterator();
  5864. colIndex = 0;
  5865. while (headCells.hasNext()) {
  5866. HeaderCell hc = (HeaderCell) headCells.next();
  5867. if (!hc.isDefinedWidth()) {
  5868. setColWidth(colIndex, hc.getWidthWithIndent() + availW
  5869. - checksum, false);
  5870. break;
  5871. }
  5872. colIndex++;
  5873. }
  5874. }
  5875. if (isDynamicHeight() && totalRows == pageLength) {
  5876. // fix body height (may vary if lazy loading is offhorizontal
  5877. // scrollbar appears/disappears)
  5878. int bodyHeight = scrollBody.getRequiredHeight();
  5879. boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
  5880. if (needsSpaceForHorizontalScrollbar) {
  5881. bodyHeight += Util.getNativeScrollbarSize();
  5882. }
  5883. int heightBefore = getOffsetHeight();
  5884. scrollBodyPanel.setHeight(bodyHeight + "px");
  5885. if (heightBefore != getOffsetHeight()) {
  5886. Util.notifyParentOfSizeChange(VScrollTable.this, false);
  5887. }
  5888. }
  5889. Scheduler.get().scheduleDeferred(new Command() {
  5890. @Override
  5891. public void execute() {
  5892. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  5893. }
  5894. });
  5895. forceRealignColumnHeaders();
  5896. }
  5897. };
  5898. private void forceRealignColumnHeaders() {
  5899. if (BrowserInfo.get().isIE()) {
  5900. /*
  5901. * IE does not fire onscroll event if scroll position is reverted to
  5902. * 0 due to the content element size growth. Ensure headers are in
  5903. * sync with content manually. Safe to use null event as we don't
  5904. * actually use the event object in listener.
  5905. */
  5906. onScroll(null);
  5907. }
  5908. }
  5909. /**
  5910. * helper to set pixel size of head and body part
  5911. *
  5912. * @param pixels
  5913. */
  5914. private void setContentWidth(int pixels) {
  5915. tHead.setWidth(pixels + "px");
  5916. scrollBodyPanel.setWidth(pixels + "px");
  5917. tFoot.setWidth(pixels + "px");
  5918. }
  5919. private int borderWidth = -1;
  5920. /**
  5921. * @return border left + border right
  5922. */
  5923. private int getBorderWidth() {
  5924. if (borderWidth < 0) {
  5925. borderWidth = Util.measureHorizontalPaddingAndBorder(
  5926. scrollBodyPanel.getElement(), 2);
  5927. if (borderWidth < 0) {
  5928. borderWidth = 0;
  5929. }
  5930. }
  5931. return borderWidth;
  5932. }
  5933. /**
  5934. * Ensures scrollable area is properly sized. This method is used when fixed
  5935. * size is used.
  5936. */
  5937. private int containerHeight;
  5938. private void setContainerHeight() {
  5939. if (!isDynamicHeight()) {
  5940. /*
  5941. * Android 2.3 cannot measure the height of the inline-block
  5942. * properly, and will return the wrong offset height. So for android
  5943. * 2.3 we set the element to a block element while measuring and
  5944. * then restore it which yields the correct result. #11331
  5945. */
  5946. if (BrowserInfo.get().isAndroid23()) {
  5947. getElement().getStyle().setDisplay(Display.BLOCK);
  5948. }
  5949. containerHeight = getOffsetHeight();
  5950. containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
  5951. containerHeight -= tFoot.getOffsetHeight();
  5952. containerHeight -= getContentAreaBorderHeight();
  5953. if (containerHeight < 0) {
  5954. containerHeight = 0;
  5955. }
  5956. scrollBodyPanel.setHeight(containerHeight + "px");
  5957. if (BrowserInfo.get().isAndroid23()) {
  5958. getElement().getStyle().clearDisplay();
  5959. }
  5960. }
  5961. }
  5962. private int contentAreaBorderHeight = -1;
  5963. private int scrollLeft;
  5964. private int scrollTop;
  5965. /** For internal use only. May be removed or replaced in the future. */
  5966. public VScrollTableDropHandler dropHandler;
  5967. private boolean navKeyDown;
  5968. /** For internal use only. May be removed or replaced in the future. */
  5969. public boolean multiselectPending;
  5970. /**
  5971. * @return border top + border bottom of the scrollable area of table
  5972. */
  5973. private int getContentAreaBorderHeight() {
  5974. if (contentAreaBorderHeight < 0) {
  5975. DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
  5976. "hidden");
  5977. int oh = scrollBodyPanel.getOffsetHeight();
  5978. int ch = scrollBodyPanel.getElement()
  5979. .getPropertyInt("clientHeight");
  5980. contentAreaBorderHeight = oh - ch;
  5981. DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
  5982. "auto");
  5983. }
  5984. return contentAreaBorderHeight;
  5985. }
  5986. @Override
  5987. public void setHeight(String height) {
  5988. if (height.length() == 0
  5989. && getElement().getStyle().getHeight().length() != 0) {
  5990. /*
  5991. * Changing from defined to undefined size -> should do a size init
  5992. * to take page length into account again
  5993. */
  5994. sizeNeedsInit = true;
  5995. }
  5996. super.setHeight(height);
  5997. }
  5998. /** For internal use only. May be removed or replaced in the future. */
  5999. public void updateHeight() {
  6000. setContainerHeight();
  6001. if (initializedAndAttached) {
  6002. updatePageLength();
  6003. }
  6004. if (!rendering) {
  6005. // Webkit may sometimes get an odd rendering bug (white space
  6006. // between header and body), see bug #3875. Running
  6007. // overflow hack here to shake body element a bit.
  6008. // We must run the fix as a deferred command to prevent it from
  6009. // overwriting the scroll position with an outdated value, see
  6010. // #7607.
  6011. Scheduler.get().scheduleDeferred(new Command() {
  6012. @Override
  6013. public void execute() {
  6014. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  6015. }
  6016. });
  6017. }
  6018. triggerLazyColumnAdjustment(false);
  6019. /*
  6020. * setting height may affect wheter the component has scrollbars ->
  6021. * needs scrolling or not
  6022. */
  6023. setProperTabIndex();
  6024. }
  6025. /*
  6026. * Overridden due Table might not survive of visibility change (scroll pos
  6027. * lost). Example ITabPanel just set contained components invisible and back
  6028. * when changing tabs.
  6029. */
  6030. @Override
  6031. public void setVisible(boolean visible) {
  6032. if (isVisible() != visible) {
  6033. super.setVisible(visible);
  6034. if (initializedAndAttached) {
  6035. if (visible) {
  6036. Scheduler.get().scheduleDeferred(new Command() {
  6037. @Override
  6038. public void execute() {
  6039. scrollBodyPanel
  6040. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  6041. }
  6042. });
  6043. }
  6044. }
  6045. }
  6046. }
  6047. /**
  6048. * Helper function to build html snippet for column or row headers
  6049. *
  6050. * @param uidl
  6051. * possibly with values caption and icon
  6052. * @return html snippet containing possibly an icon + caption text
  6053. */
  6054. protected String buildCaptionHtmlSnippet(UIDL uidl) {
  6055. String s = uidl.hasAttribute("caption") ? uidl
  6056. .getStringAttribute("caption") : "";
  6057. if (uidl.hasAttribute("icon")) {
  6058. s = "<img src=\""
  6059. + Util.escapeAttribute(client.translateVaadinUri(uidl
  6060. .getStringAttribute("icon")))
  6061. + "\" alt=\"icon\" class=\"v-icon\">" + s;
  6062. }
  6063. return s;
  6064. }
  6065. /**
  6066. * This method has logic which rows needs to be requested from server when
  6067. * user scrolls
  6068. */
  6069. @Override
  6070. public void onScroll(ScrollEvent event) {
  6071. scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
  6072. scrollTop = scrollBodyPanel.getScrollPosition();
  6073. /*
  6074. * #6970 - IE sometimes fires scroll events for a detached table.
  6075. *
  6076. * FIXME initializedAndAttached should probably be renamed - its name
  6077. * doesn't seem to reflect its semantics. onDetach() doesn't set it to
  6078. * false, and changing that might break something else, so we need to
  6079. * check isAttached() separately.
  6080. */
  6081. if (!initializedAndAttached || !isAttached()) {
  6082. return;
  6083. }
  6084. if (!enabled) {
  6085. scrollBodyPanel
  6086. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  6087. return;
  6088. }
  6089. rowRequestHandler.cancel();
  6090. if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
  6091. // due to the webkitoverflowworkaround, top may sometimes report 0
  6092. // for webkit, although it really is not. Expecting to have the
  6093. // correct
  6094. // value available soon.
  6095. Scheduler.get().scheduleDeferred(new Command() {
  6096. @Override
  6097. public void execute() {
  6098. onScroll(null);
  6099. }
  6100. });
  6101. return;
  6102. }
  6103. // fix headers horizontal scrolling
  6104. tHead.setHorizontalScrollPosition(scrollLeft);
  6105. // fix footers horizontal scrolling
  6106. tFoot.setHorizontalScrollPosition(scrollLeft);
  6107. firstRowInViewPort = calcFirstRowInViewPort();
  6108. if (firstRowInViewPort > totalRows - pageLength) {
  6109. firstRowInViewPort = totalRows - pageLength;
  6110. }
  6111. int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
  6112. * cache_react_rate);
  6113. if (postLimit > totalRows - 1) {
  6114. postLimit = totalRows - 1;
  6115. }
  6116. int preLimit = (int) (firstRowInViewPort - pageLength
  6117. * cache_react_rate);
  6118. if (preLimit < 0) {
  6119. preLimit = 0;
  6120. }
  6121. final int lastRendered = scrollBody.getLastRendered();
  6122. final int firstRendered = scrollBody.getFirstRendered();
  6123. if (postLimit <= lastRendered && preLimit >= firstRendered) {
  6124. // we're within no-react area, no need to request more rows
  6125. // remember which firstvisible we requested, in case the server has
  6126. // a differing opinion
  6127. lastRequestedFirstvisible = firstRowInViewPort;
  6128. client.updateVariable(paintableId, "firstvisible",
  6129. firstRowInViewPort, false);
  6130. return;
  6131. }
  6132. if (firstRowInViewPort - pageLength * cache_rate > lastRendered
  6133. || firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
  6134. // need a totally new set of rows
  6135. rowRequestHandler
  6136. .setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
  6137. int last = firstRowInViewPort + (int) (cache_rate * pageLength)
  6138. + pageLength - 1;
  6139. if (last >= totalRows) {
  6140. last = totalRows - 1;
  6141. }
  6142. rowRequestHandler.setReqRows(last
  6143. - rowRequestHandler.getReqFirstRow() + 1);
  6144. rowRequestHandler.deferRowFetch();
  6145. return;
  6146. }
  6147. if (preLimit < firstRendered) {
  6148. // need some rows to the beginning of the rendered area
  6149. rowRequestHandler
  6150. .setReqFirstRow((int) (firstRowInViewPort - pageLength
  6151. * cache_rate));
  6152. rowRequestHandler.setReqRows(firstRendered
  6153. - rowRequestHandler.getReqFirstRow());
  6154. rowRequestHandler.deferRowFetch();
  6155. return;
  6156. }
  6157. if (postLimit > lastRendered) {
  6158. // need some rows to the end of the rendered area
  6159. int reqRows = (int) ((firstRowInViewPort + pageLength + pageLength
  6160. * cache_rate) - lastRendered);
  6161. rowRequestHandler.triggerRowFetch(lastRendered + 1, reqRows);
  6162. }
  6163. }
  6164. protected int calcFirstRowInViewPort() {
  6165. return (int) Math.ceil(scrollTop / scrollBody.getRowHeight());
  6166. }
  6167. @Override
  6168. public VScrollTableDropHandler getDropHandler() {
  6169. return dropHandler;
  6170. }
  6171. private static class TableDDDetails {
  6172. int overkey = -1;
  6173. VerticalDropLocation dropLocation;
  6174. String colkey;
  6175. @Override
  6176. public boolean equals(Object obj) {
  6177. if (obj instanceof TableDDDetails) {
  6178. TableDDDetails other = (TableDDDetails) obj;
  6179. return dropLocation == other.dropLocation
  6180. && overkey == other.overkey
  6181. && ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
  6182. }
  6183. return false;
  6184. }
  6185. //
  6186. // public int hashCode() {
  6187. // return overkey;
  6188. // }
  6189. }
  6190. public class VScrollTableDropHandler extends VAbstractDropHandler {
  6191. private static final String ROWSTYLEBASE = "v-table-row-drag-";
  6192. private TableDDDetails dropDetails;
  6193. private TableDDDetails lastEmphasized;
  6194. @Override
  6195. public void dragEnter(VDragEvent drag) {
  6196. updateDropDetails(drag);
  6197. super.dragEnter(drag);
  6198. }
  6199. private void updateDropDetails(VDragEvent drag) {
  6200. dropDetails = new TableDDDetails();
  6201. Element elementOver = drag.getElementOver();
  6202. VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
  6203. if (row != null) {
  6204. dropDetails.overkey = row.rowKey;
  6205. Element tr = row.getElement();
  6206. Element element = elementOver;
  6207. while (element != null && element.getParentElement() != tr) {
  6208. element = (Element) element.getParentElement();
  6209. }
  6210. int childIndex = DOM.getChildIndex(tr, element);
  6211. dropDetails.colkey = tHead.getHeaderCell(childIndex)
  6212. .getColKey();
  6213. dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
  6214. row.getElement(), drag.getCurrentGwtEvent(), 0.2);
  6215. }
  6216. drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
  6217. drag.getDropDetails().put(
  6218. "detail",
  6219. dropDetails.dropLocation != null ? dropDetails.dropLocation
  6220. .toString() : null);
  6221. }
  6222. private Class<? extends Widget> getRowClass() {
  6223. // get the row type this way to make dd work in derived
  6224. // implementations
  6225. return scrollBody.iterator().next().getClass();
  6226. }
  6227. @Override
  6228. public void dragOver(VDragEvent drag) {
  6229. TableDDDetails oldDetails = dropDetails;
  6230. updateDropDetails(drag);
  6231. if (!oldDetails.equals(dropDetails)) {
  6232. deEmphasis();
  6233. final TableDDDetails newDetails = dropDetails;
  6234. VAcceptCallback cb = new VAcceptCallback() {
  6235. @Override
  6236. public void accepted(VDragEvent event) {
  6237. if (newDetails.equals(dropDetails)) {
  6238. dragAccepted(event);
  6239. }
  6240. /*
  6241. * Else new target slot already defined, ignore
  6242. */
  6243. }
  6244. };
  6245. validate(cb, drag);
  6246. }
  6247. }
  6248. @Override
  6249. public void dragLeave(VDragEvent drag) {
  6250. deEmphasis();
  6251. super.dragLeave(drag);
  6252. }
  6253. @Override
  6254. public boolean drop(VDragEvent drag) {
  6255. deEmphasis();
  6256. return super.drop(drag);
  6257. }
  6258. private void deEmphasis() {
  6259. UIObject.setStyleName(getElement(),
  6260. VScrollTable.this.getStylePrimaryName() + "-drag", false);
  6261. if (lastEmphasized == null) {
  6262. return;
  6263. }
  6264. for (Widget w : scrollBody.renderedRows) {
  6265. VScrollTableRow row = (VScrollTableRow) w;
  6266. if (lastEmphasized != null
  6267. && row.rowKey == lastEmphasized.overkey) {
  6268. String stylename = ROWSTYLEBASE
  6269. + lastEmphasized.dropLocation.toString()
  6270. .toLowerCase();
  6271. VScrollTableRow.setStyleName(row.getElement(), stylename,
  6272. false);
  6273. lastEmphasized = null;
  6274. return;
  6275. }
  6276. }
  6277. }
  6278. /**
  6279. * TODO needs different drop modes ?? (on cells, on rows), now only
  6280. * supports rows
  6281. */
  6282. private void emphasis(TableDDDetails details) {
  6283. deEmphasis();
  6284. UIObject.setStyleName(getElement(),
  6285. VScrollTable.this.getStylePrimaryName() + "-drag", true);
  6286. // iterate old and new emphasized row
  6287. for (Widget w : scrollBody.renderedRows) {
  6288. VScrollTableRow row = (VScrollTableRow) w;
  6289. if (details != null && details.overkey == row.rowKey) {
  6290. String stylename = ROWSTYLEBASE
  6291. + details.dropLocation.toString().toLowerCase();
  6292. VScrollTableRow.setStyleName(row.getElement(), stylename,
  6293. true);
  6294. lastEmphasized = details;
  6295. return;
  6296. }
  6297. }
  6298. }
  6299. @Override
  6300. protected void dragAccepted(VDragEvent drag) {
  6301. emphasis(dropDetails);
  6302. }
  6303. @Override
  6304. public ComponentConnector getConnector() {
  6305. return ConnectorMap.get(client).getConnector(VScrollTable.this);
  6306. }
  6307. @Override
  6308. public ApplicationConnection getApplicationConnection() {
  6309. return client;
  6310. }
  6311. }
  6312. protected VScrollTableRow getFocusedRow() {
  6313. return focusedRow;
  6314. }
  6315. /**
  6316. * Moves the selection head to a specific row
  6317. *
  6318. * @param row
  6319. * The row to where the selection head should move
  6320. * @return Returns true if focus was moved successfully, else false
  6321. */
  6322. public boolean setRowFocus(VScrollTableRow row) {
  6323. if (!isSelectable()) {
  6324. return false;
  6325. }
  6326. // Remove previous selection
  6327. if (focusedRow != null && focusedRow != row) {
  6328. focusedRow.removeStyleName(getStylePrimaryName() + "-focus");
  6329. }
  6330. if (row != null) {
  6331. // Apply focus style to new selection
  6332. row.addStyleName(getStylePrimaryName() + "-focus");
  6333. /*
  6334. * Trying to set focus on already focused row
  6335. */
  6336. if (row == focusedRow) {
  6337. return false;
  6338. }
  6339. // Set new focused row
  6340. focusedRow = row;
  6341. ensureRowIsVisible(row);
  6342. return true;
  6343. }
  6344. return false;
  6345. }
  6346. /**
  6347. * Ensures that the row is visible
  6348. *
  6349. * @param row
  6350. * The row to ensure is visible
  6351. */
  6352. private void ensureRowIsVisible(VScrollTableRow row) {
  6353. if (BrowserInfo.get().isTouchDevice()) {
  6354. // Skip due to android devices that have broken scrolltop will may
  6355. // get odd scrolling here.
  6356. return;
  6357. }
  6358. Util.scrollIntoViewVertically(row.getElement());
  6359. }
  6360. /**
  6361. * Handles the keyboard events handled by the table
  6362. *
  6363. * @param event
  6364. * The keyboard event received
  6365. * @return true iff the navigation event was handled
  6366. */
  6367. protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  6368. if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
  6369. // Do not handle tab key
  6370. return false;
  6371. }
  6372. // Down navigation
  6373. if (!isSelectable() && keycode == getNavigationDownKey()) {
  6374. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  6375. .getScrollPosition() + scrollingVelocity);
  6376. return true;
  6377. } else if (keycode == getNavigationDownKey()) {
  6378. if (isMultiSelectModeAny() && moveFocusDown()) {
  6379. selectFocusedRow(ctrl, shift);
  6380. } else if (isSingleSelectMode() && !shift && moveFocusDown()) {
  6381. selectFocusedRow(ctrl, shift);
  6382. }
  6383. return true;
  6384. }
  6385. // Up navigation
  6386. if (!isSelectable() && keycode == getNavigationUpKey()) {
  6387. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  6388. .getScrollPosition() - scrollingVelocity);
  6389. return true;
  6390. } else if (keycode == getNavigationUpKey()) {
  6391. if (isMultiSelectModeAny() && moveFocusUp()) {
  6392. selectFocusedRow(ctrl, shift);
  6393. } else if (isSingleSelectMode() && !shift && moveFocusUp()) {
  6394. selectFocusedRow(ctrl, shift);
  6395. }
  6396. return true;
  6397. }
  6398. if (keycode == getNavigationLeftKey()) {
  6399. // Left navigation
  6400. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  6401. .getHorizontalScrollPosition() - scrollingVelocity);
  6402. return true;
  6403. } else if (keycode == getNavigationRightKey()) {
  6404. // Right navigation
  6405. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  6406. .getHorizontalScrollPosition() + scrollingVelocity);
  6407. return true;
  6408. }
  6409. // Select navigation
  6410. if (isSelectable() && keycode == getNavigationSelectKey()) {
  6411. if (isSingleSelectMode()) {
  6412. boolean wasSelected = focusedRow.isSelected();
  6413. deselectAll();
  6414. if (!wasSelected || !nullSelectionAllowed) {
  6415. focusedRow.toggleSelection();
  6416. }
  6417. } else {
  6418. focusedRow.toggleSelection();
  6419. removeRowFromUnsentSelectionRanges(focusedRow);
  6420. }
  6421. sendSelectedRows();
  6422. return true;
  6423. }
  6424. // Page Down navigation
  6425. if (keycode == getNavigationPageDownKey()) {
  6426. if (isSelectable()) {
  6427. /*
  6428. * If selectable we plagiate MSW behaviour: first scroll to the
  6429. * end of current view. If at the end, scroll down one page
  6430. * length and keep the selected row in the bottom part of
  6431. * visible area.
  6432. */
  6433. if (!isFocusAtTheEndOfTable()) {
  6434. VScrollTableRow lastVisibleRowInViewPort = scrollBody
  6435. .getRowByRowIndex(firstRowInViewPort
  6436. + getFullyVisibleRowCount() - 1);
  6437. if (lastVisibleRowInViewPort != null
  6438. && lastVisibleRowInViewPort != focusedRow) {
  6439. // focused row is not at the end of the table, move
  6440. // focus and select the last visible row
  6441. setRowFocus(lastVisibleRowInViewPort);
  6442. selectFocusedRow(ctrl, shift);
  6443. sendSelectedRows();
  6444. } else {
  6445. int indexOfToBeFocused = focusedRow.getIndex()
  6446. + getFullyVisibleRowCount();
  6447. if (indexOfToBeFocused >= totalRows) {
  6448. indexOfToBeFocused = totalRows - 1;
  6449. }
  6450. VScrollTableRow toBeFocusedRow = scrollBody
  6451. .getRowByRowIndex(indexOfToBeFocused);
  6452. if (toBeFocusedRow != null) {
  6453. /*
  6454. * if the next focused row is rendered
  6455. */
  6456. setRowFocus(toBeFocusedRow);
  6457. selectFocusedRow(ctrl, shift);
  6458. // TODO needs scrollintoview ?
  6459. sendSelectedRows();
  6460. } else {
  6461. // scroll down by pixels and return, to wait for
  6462. // new rows, then select the last item in the
  6463. // viewport
  6464. selectLastItemInNextRender = true;
  6465. multiselectPending = shift;
  6466. scrollByPagelenght(1);
  6467. }
  6468. }
  6469. }
  6470. } else {
  6471. /* No selections, go page down by scrolling */
  6472. scrollByPagelenght(1);
  6473. }
  6474. return true;
  6475. }
  6476. // Page Up navigation
  6477. if (keycode == getNavigationPageUpKey()) {
  6478. if (isSelectable()) {
  6479. /*
  6480. * If selectable we plagiate MSW behaviour: first scroll to the
  6481. * end of current view. If at the end, scroll down one page
  6482. * length and keep the selected row in the bottom part of
  6483. * visible area.
  6484. */
  6485. if (!isFocusAtTheBeginningOfTable()) {
  6486. VScrollTableRow firstVisibleRowInViewPort = scrollBody
  6487. .getRowByRowIndex(firstRowInViewPort);
  6488. if (firstVisibleRowInViewPort != null
  6489. && firstVisibleRowInViewPort != focusedRow) {
  6490. // focus is not at the beginning of the table, move
  6491. // focus and select the first visible row
  6492. setRowFocus(firstVisibleRowInViewPort);
  6493. selectFocusedRow(ctrl, shift);
  6494. sendSelectedRows();
  6495. } else {
  6496. int indexOfToBeFocused = focusedRow.getIndex()
  6497. - getFullyVisibleRowCount();
  6498. if (indexOfToBeFocused < 0) {
  6499. indexOfToBeFocused = 0;
  6500. }
  6501. VScrollTableRow toBeFocusedRow = scrollBody
  6502. .getRowByRowIndex(indexOfToBeFocused);
  6503. if (toBeFocusedRow != null) { // if the next focused row
  6504. // is rendered
  6505. setRowFocus(toBeFocusedRow);
  6506. selectFocusedRow(ctrl, shift);
  6507. // TODO needs scrollintoview ?
  6508. sendSelectedRows();
  6509. } else {
  6510. // unless waiting for the next rowset already
  6511. // scroll down by pixels and return, to wait for
  6512. // new rows, then select the last item in the
  6513. // viewport
  6514. selectFirstItemInNextRender = true;
  6515. multiselectPending = shift;
  6516. scrollByPagelenght(-1);
  6517. }
  6518. }
  6519. }
  6520. } else {
  6521. /* No selections, go page up by scrolling */
  6522. scrollByPagelenght(-1);
  6523. }
  6524. return true;
  6525. }
  6526. // Goto start navigation
  6527. if (keycode == getNavigationStartKey()) {
  6528. scrollBodyPanel.setScrollPosition(0);
  6529. if (isSelectable()) {
  6530. if (focusedRow != null && focusedRow.getIndex() == 0) {
  6531. return false;
  6532. } else {
  6533. VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
  6534. .iterator().next();
  6535. if (rowByRowIndex.getIndex() == 0) {
  6536. setRowFocus(rowByRowIndex);
  6537. selectFocusedRow(ctrl, shift);
  6538. sendSelectedRows();
  6539. } else {
  6540. // first row of table will come in next row fetch
  6541. if (ctrl) {
  6542. focusFirstItemInNextRender = true;
  6543. } else {
  6544. selectFirstItemInNextRender = true;
  6545. multiselectPending = shift;
  6546. }
  6547. }
  6548. }
  6549. }
  6550. return true;
  6551. }
  6552. // Goto end navigation
  6553. if (keycode == getNavigationEndKey()) {
  6554. scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
  6555. if (isSelectable()) {
  6556. final int lastRendered = scrollBody.getLastRendered();
  6557. if (lastRendered + 1 == totalRows) {
  6558. VScrollTableRow rowByRowIndex = scrollBody
  6559. .getRowByRowIndex(lastRendered);
  6560. if (focusedRow != rowByRowIndex) {
  6561. setRowFocus(rowByRowIndex);
  6562. selectFocusedRow(ctrl, shift);
  6563. sendSelectedRows();
  6564. }
  6565. } else {
  6566. if (ctrl) {
  6567. focusLastItemInNextRender = true;
  6568. } else {
  6569. selectLastItemInNextRender = true;
  6570. multiselectPending = shift;
  6571. }
  6572. }
  6573. }
  6574. return true;
  6575. }
  6576. return false;
  6577. }
  6578. private boolean isFocusAtTheBeginningOfTable() {
  6579. return focusedRow.getIndex() == 0;
  6580. }
  6581. private boolean isFocusAtTheEndOfTable() {
  6582. return focusedRow.getIndex() + 1 >= totalRows;
  6583. }
  6584. private int getFullyVisibleRowCount() {
  6585. return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
  6586. .getRowHeight());
  6587. }
  6588. private void scrollByPagelenght(int i) {
  6589. int pixels = i * scrollBodyPanel.getOffsetHeight();
  6590. int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
  6591. if (newPixels < 0) {
  6592. newPixels = 0;
  6593. } // else if too high, NOP (all know browsers accept illegally big
  6594. // values here)
  6595. scrollBodyPanel.setScrollPosition(newPixels);
  6596. }
  6597. /*
  6598. * (non-Javadoc)
  6599. *
  6600. * @see
  6601. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  6602. * .dom.client.FocusEvent)
  6603. */
  6604. @Override
  6605. public void onFocus(FocusEvent event) {
  6606. if (isFocusable()) {
  6607. hasFocus = true;
  6608. // Focus a row if no row is in focus
  6609. if (focusedRow == null) {
  6610. focusRowFromBody();
  6611. } else {
  6612. setRowFocus(focusedRow);
  6613. }
  6614. }
  6615. }
  6616. /*
  6617. * (non-Javadoc)
  6618. *
  6619. * @see
  6620. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  6621. * .dom.client.BlurEvent)
  6622. */
  6623. @Override
  6624. public void onBlur(BlurEvent event) {
  6625. hasFocus = false;
  6626. navKeyDown = false;
  6627. if (BrowserInfo.get().isIE()) {
  6628. /*
  6629. * IE sometimes moves focus to a clicked table cell... (#7965)
  6630. * ...and sometimes it sends blur events even though the focus
  6631. * handler is still active. (#10464)
  6632. */
  6633. Element focusedElement = Util.getIEFocusedElement();
  6634. if (Util.getConnectorForElement(client, getParent(), focusedElement) == this
  6635. && focusedElement != null
  6636. && focusedElement != scrollBodyPanel.getFocusElement()) {
  6637. /*
  6638. * Steal focus back to the focus handler if it was moved to some
  6639. * other part of the table. Avoid stealing focus in other cases.
  6640. */
  6641. focus();
  6642. return;
  6643. }
  6644. }
  6645. if (isFocusable()) {
  6646. // Unfocus any row
  6647. setRowFocus(null);
  6648. }
  6649. }
  6650. /**
  6651. * Removes a key from a range if the key is found in a selected range
  6652. *
  6653. * @param key
  6654. * The key to remove
  6655. */
  6656. private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
  6657. Collection<SelectionRange> newRanges = null;
  6658. for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
  6659. .hasNext();) {
  6660. SelectionRange range = iterator.next();
  6661. if (range.inRange(row)) {
  6662. // Split the range if given row is in range
  6663. Collection<SelectionRange> splitranges = range.split(row);
  6664. if (newRanges == null) {
  6665. newRanges = new ArrayList<SelectionRange>();
  6666. }
  6667. newRanges.addAll(splitranges);
  6668. iterator.remove();
  6669. }
  6670. }
  6671. if (newRanges != null) {
  6672. selectedRowRanges.addAll(newRanges);
  6673. }
  6674. }
  6675. /**
  6676. * Can the Table be focused?
  6677. *
  6678. * @return True if the table can be focused, else false
  6679. */
  6680. public boolean isFocusable() {
  6681. if (scrollBody != null && enabled) {
  6682. return !(!hasHorizontalScrollbar() && !hasVerticalScrollbar() && !isSelectable());
  6683. }
  6684. return false;
  6685. }
  6686. private boolean hasHorizontalScrollbar() {
  6687. return scrollBody.getOffsetWidth() > scrollBodyPanel.getOffsetWidth();
  6688. }
  6689. private boolean hasVerticalScrollbar() {
  6690. return scrollBody.getOffsetHeight() > scrollBodyPanel.getOffsetHeight();
  6691. }
  6692. /*
  6693. * (non-Javadoc)
  6694. *
  6695. * @see com.vaadin.client.Focusable#focus()
  6696. */
  6697. @Override
  6698. public void focus() {
  6699. if (isFocusable()) {
  6700. scrollBodyPanel.focus();
  6701. }
  6702. }
  6703. /**
  6704. * Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
  6705. * component).
  6706. * <p>
  6707. * If the component has no explicit tabIndex a zero is given (default
  6708. * tabbing order based on dom hierarchy) or -1 if the component does not
  6709. * need to gain focus. The component needs no focus if it has no scrollabars
  6710. * (not scrollable) and not selectable. Note that in the future shortcut
  6711. * actions may need focus.
  6712. * <p>
  6713. * For internal use only. May be removed or replaced in the future.
  6714. */
  6715. public void setProperTabIndex() {
  6716. int storedScrollTop = 0;
  6717. int storedScrollLeft = 0;
  6718. if (BrowserInfo.get().getOperaVersion() >= 11) {
  6719. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  6720. storedScrollTop = scrollBodyPanel.getScrollPosition();
  6721. storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
  6722. }
  6723. if (tabIndex == 0 && !isFocusable()) {
  6724. scrollBodyPanel.setTabIndex(-1);
  6725. } else {
  6726. scrollBodyPanel.setTabIndex(tabIndex);
  6727. }
  6728. if (BrowserInfo.get().getOperaVersion() >= 11) {
  6729. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  6730. scrollBodyPanel.setScrollPosition(storedScrollTop);
  6731. scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
  6732. }
  6733. }
  6734. public void startScrollingVelocityTimer() {
  6735. if (scrollingVelocityTimer == null) {
  6736. scrollingVelocityTimer = new Timer() {
  6737. @Override
  6738. public void run() {
  6739. scrollingVelocity++;
  6740. }
  6741. };
  6742. scrollingVelocityTimer.scheduleRepeating(100);
  6743. }
  6744. }
  6745. public void cancelScrollingVelocityTimer() {
  6746. if (scrollingVelocityTimer != null) {
  6747. // Remove velocityTimer if it exists and the Table is disabled
  6748. scrollingVelocityTimer.cancel();
  6749. scrollingVelocityTimer = null;
  6750. scrollingVelocity = 10;
  6751. }
  6752. }
  6753. /**
  6754. *
  6755. * @param keyCode
  6756. * @return true if the given keyCode is used by the table for navigation
  6757. */
  6758. private boolean isNavigationKey(int keyCode) {
  6759. return keyCode == getNavigationUpKey()
  6760. || keyCode == getNavigationLeftKey()
  6761. || keyCode == getNavigationRightKey()
  6762. || keyCode == getNavigationDownKey()
  6763. || keyCode == getNavigationPageUpKey()
  6764. || keyCode == getNavigationPageDownKey()
  6765. || keyCode == getNavigationEndKey()
  6766. || keyCode == getNavigationStartKey();
  6767. }
  6768. public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
  6769. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  6770. @Override
  6771. public void execute() {
  6772. if (currentlyFocusedRow != null) {
  6773. setRowFocus(currentlyFocusedRow);
  6774. } else {
  6775. VConsole.log("no row?");
  6776. focusRowFromBody();
  6777. }
  6778. scrollBody.ensureFocus();
  6779. }
  6780. });
  6781. }
  6782. @Override
  6783. public Action[] getActions() {
  6784. if (bodyActionKeys == null) {
  6785. return new Action[] {};
  6786. }
  6787. final Action[] actions = new Action[bodyActionKeys.length];
  6788. for (int i = 0; i < actions.length; i++) {
  6789. final String actionKey = bodyActionKeys[i];
  6790. Action bodyAction = new TreeAction(this, null, actionKey);
  6791. bodyAction.setCaption(getActionCaption(actionKey));
  6792. bodyAction.setIconUrl(getActionIcon(actionKey));
  6793. actions[i] = bodyAction;
  6794. }
  6795. return actions;
  6796. }
  6797. @Override
  6798. public ApplicationConnection getClient() {
  6799. return client;
  6800. }
  6801. @Override
  6802. public String getPaintableId() {
  6803. return paintableId;
  6804. }
  6805. /**
  6806. * Add this to the element mouse down event by using element.setPropertyJSO
  6807. * ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
  6808. * when the mouse is depressed in the mouse up event.
  6809. *
  6810. * @return Returns the JSO preventing text selection
  6811. */
  6812. private static native JavaScriptObject getPreventTextSelectionIEHack()
  6813. /*-{
  6814. return function(){ return false; };
  6815. }-*/;
  6816. public void triggerLazyColumnAdjustment(boolean now) {
  6817. lazyAdjustColumnWidths.cancel();
  6818. if (now) {
  6819. lazyAdjustColumnWidths.run();
  6820. } else {
  6821. lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
  6822. }
  6823. }
  6824. private boolean isDynamicWidth() {
  6825. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  6826. this);
  6827. return paintable.isUndefinedWidth();
  6828. }
  6829. private boolean isDynamicHeight() {
  6830. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  6831. this);
  6832. if (paintable == null) {
  6833. // This should be refactored. As isDynamicHeight can be called from
  6834. // a timer it is possible that the connector has been unregistered
  6835. // when this method is called, causing getConnector to return null.
  6836. return false;
  6837. }
  6838. return paintable.isUndefinedHeight();
  6839. }
  6840. private void debug(String msg) {
  6841. if (enableDebug) {
  6842. VConsole.error(msg);
  6843. }
  6844. }
  6845. public Widget getWidgetForPaintable() {
  6846. return this;
  6847. }
  6848. }