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

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