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

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