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

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