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

VScrollTable.java 311KB

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