You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VScrollTable.java 311KB

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