Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

VScrollTable.java 311KB

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