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

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