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

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