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

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