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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.ui;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.HashMap;
  8. import java.util.HashSet;
  9. import java.util.Iterator;
  10. import java.util.LinkedList;
  11. import java.util.List;
  12. import java.util.Set;
  13. import com.google.gwt.core.client.JavaScriptObject;
  14. import com.google.gwt.core.client.Scheduler;
  15. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  16. import com.google.gwt.dom.client.Document;
  17. import com.google.gwt.dom.client.NativeEvent;
  18. import com.google.gwt.dom.client.NodeList;
  19. import com.google.gwt.dom.client.Style;
  20. import com.google.gwt.dom.client.Style.Display;
  21. import com.google.gwt.dom.client.Style.Position;
  22. import com.google.gwt.dom.client.Style.Unit;
  23. import com.google.gwt.dom.client.Style.Visibility;
  24. import com.google.gwt.dom.client.TableCellElement;
  25. import com.google.gwt.dom.client.TableRowElement;
  26. import com.google.gwt.dom.client.TableSectionElement;
  27. import com.google.gwt.dom.client.Touch;
  28. import com.google.gwt.event.dom.client.BlurEvent;
  29. import com.google.gwt.event.dom.client.BlurHandler;
  30. import com.google.gwt.event.dom.client.ContextMenuEvent;
  31. import com.google.gwt.event.dom.client.ContextMenuHandler;
  32. import com.google.gwt.event.dom.client.FocusEvent;
  33. import com.google.gwt.event.dom.client.FocusHandler;
  34. import com.google.gwt.event.dom.client.KeyCodes;
  35. import com.google.gwt.event.dom.client.KeyDownEvent;
  36. import com.google.gwt.event.dom.client.KeyDownHandler;
  37. import com.google.gwt.event.dom.client.KeyPressEvent;
  38. import com.google.gwt.event.dom.client.KeyPressHandler;
  39. import com.google.gwt.event.dom.client.KeyUpEvent;
  40. import com.google.gwt.event.dom.client.KeyUpHandler;
  41. import com.google.gwt.event.dom.client.ScrollEvent;
  42. import com.google.gwt.event.dom.client.ScrollHandler;
  43. import com.google.gwt.event.dom.client.TouchStartEvent;
  44. import com.google.gwt.event.dom.client.TouchStartHandler;
  45. import com.google.gwt.user.client.Command;
  46. import com.google.gwt.user.client.DOM;
  47. import com.google.gwt.user.client.Element;
  48. import com.google.gwt.user.client.Event;
  49. import com.google.gwt.user.client.Timer;
  50. import com.google.gwt.user.client.Window;
  51. import com.google.gwt.user.client.ui.FlowPanel;
  52. import com.google.gwt.user.client.ui.Panel;
  53. import com.google.gwt.user.client.ui.RootPanel;
  54. import com.google.gwt.user.client.ui.UIObject;
  55. import com.google.gwt.user.client.ui.Widget;
  56. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  57. import com.vaadin.terminal.gwt.client.BrowserInfo;
  58. import com.vaadin.terminal.gwt.client.Container;
  59. import com.vaadin.terminal.gwt.client.Focusable;
  60. import com.vaadin.terminal.gwt.client.MouseEventDetails;
  61. import com.vaadin.terminal.gwt.client.RenderSpace;
  62. import com.vaadin.terminal.gwt.client.TooltipInfo;
  63. import com.vaadin.terminal.gwt.client.UIDL;
  64. import com.vaadin.terminal.gwt.client.Util;
  65. import com.vaadin.terminal.gwt.client.VConsole;
  66. import com.vaadin.terminal.gwt.client.VPaintableMap;
  67. import com.vaadin.terminal.gwt.client.VPaintableWidget;
  68. import com.vaadin.terminal.gwt.client.VTooltip;
  69. import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
  70. import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
  71. import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
  72. import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
  73. import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
  74. import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
  75. import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
  76. import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
  77. import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
  78. /**
  79. * VScrollTable
  80. *
  81. * VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
  82. * ScrollPanel
  83. *
  84. * TableHead contains table's header and widgets + logic for resizing,
  85. * reordering and hiding columns.
  86. *
  87. * ScrollPanel contains VScrollTableBody object which handles content. To save
  88. * some bandwidth and to improve clients responsiveness with loads of data, in
  89. * VScrollTableBody all rows are not necessary rendered. There are "spacers" in
  90. * VScrollTableBody to use the exact same space as non-rendered rows would use.
  91. * This way we can use seamlessly traditional scrollbars and scrolling to fetch
  92. * more rows instead of "paging".
  93. *
  94. * In VScrollTable we listen to scroll events. On horizontal scrolling we also
  95. * update TableHeads scroll position which has its scrollbars hidden. On
  96. * vertical scroll events we will check if we are reaching the end of area where
  97. * we have rows rendered and
  98. *
  99. * TODO implement unregistering for child components in Cells
  100. */
  101. public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
  102. VHasDropHandler, FocusHandler, BlurHandler, Focusable, ActionOwner {
  103. public static final String ATTRIBUTE_PAGEBUFFER_FIRST = "pb-ft";
  104. public static final String ATTRIBUTE_PAGEBUFFER_LAST = "pb-l";
  105. private static final String ROW_HEADER_COLUMN_KEY = "0";
  106. public static final String CLASSNAME = "v-table";
  107. public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
  108. public static final String ITEM_CLICK_EVENT_ID = "itemClick";
  109. public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
  110. public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
  111. public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
  112. public static final String COLUMN_REORDER_EVENT_ID = "columnReorder";
  113. private static final double CACHE_RATE_DEFAULT = 2;
  114. /**
  115. * The default multi select mode where simple left clicks only selects one
  116. * item, CTRL+left click selects multiple items and SHIFT-left click selects
  117. * a range of items.
  118. */
  119. private static final int MULTISELECT_MODE_DEFAULT = 0;
  120. /**
  121. * The simple multiselect mode is what the table used to have before
  122. * ctrl/shift selections were added. That is that when this is set clicking
  123. * on an item selects/deselects the item and no ctrl/shift selections are
  124. * available.
  125. */
  126. private static final int MULTISELECT_MODE_SIMPLE = 1;
  127. /**
  128. * multiple of pagelength which component will cache when requesting more
  129. * rows
  130. */
  131. private double cache_rate = CACHE_RATE_DEFAULT;
  132. /**
  133. * fraction of pageLenght which can be scrolled without making new request
  134. */
  135. private double cache_react_rate = 0.75 * cache_rate;
  136. public static final char ALIGN_CENTER = 'c';
  137. public static final char ALIGN_LEFT = 'b';
  138. public static final char ALIGN_RIGHT = 'e';
  139. private static final int CHARCODE_SPACE = 32;
  140. private int firstRowInViewPort = 0;
  141. private int pageLength = 15;
  142. private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
  143. protected boolean showRowHeaders = false;
  144. private String[] columnOrder;
  145. protected ApplicationConnection client;
  146. protected String paintableId;
  147. private boolean immediate;
  148. private boolean nullSelectionAllowed = true;
  149. private int selectMode = Table.SELECT_MODE_NONE;
  150. private final HashSet<String> selectedRowKeys = new HashSet<String>();
  151. /*
  152. * When scrolling and selecting at the same time, the selections are not in
  153. * sync with the server while retrieving new rows (until key is released).
  154. */
  155. private HashSet<Object> unSyncedselectionsBeforeRowFetch;
  156. /*
  157. * These are used when jumping between pages when pressing Home and End
  158. */
  159. private boolean selectLastItemInNextRender = false;
  160. private boolean selectFirstItemInNextRender = false;
  161. private boolean focusFirstItemInNextRender = false;
  162. private boolean focusLastItemInNextRender = false;
  163. /*
  164. * The currently focused row
  165. */
  166. private VScrollTableRow focusedRow;
  167. /*
  168. * Helper to store selection range start in when using the keyboard
  169. */
  170. private VScrollTableRow selectionRangeStart;
  171. /*
  172. * Flag for notifying when the selection has changed and should be sent to
  173. * the server
  174. */
  175. private boolean selectionChanged = false;
  176. /*
  177. * The speed (in pixels) which the scrolling scrolls vertically/horizontally
  178. */
  179. private int scrollingVelocity = 10;
  180. private Timer scrollingVelocityTimer = null;
  181. private String[] bodyActionKeys;
  182. private boolean enableDebug = false;
  183. /**
  184. * Represents a select range of rows
  185. */
  186. private class SelectionRange {
  187. private VScrollTableRow startRow;
  188. private final int length;
  189. /**
  190. * Constuctor.
  191. */
  192. public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
  193. VScrollTableRow endRow;
  194. if (row2.isBefore(row1)) {
  195. startRow = row2;
  196. endRow = row1;
  197. } else {
  198. startRow = row1;
  199. endRow = row2;
  200. }
  201. length = endRow.getIndex() - startRow.getIndex() + 1;
  202. }
  203. public SelectionRange(VScrollTableRow row, int length) {
  204. startRow = row;
  205. this.length = length;
  206. }
  207. /*
  208. * (non-Javadoc)
  209. *
  210. * @see java.lang.Object#toString()
  211. */
  212. @Override
  213. public String toString() {
  214. return startRow.getKey() + "-" + length;
  215. }
  216. private boolean inRange(VScrollTableRow row) {
  217. return row.getIndex() >= startRow.getIndex()
  218. && row.getIndex() < startRow.getIndex() + length;
  219. }
  220. public Collection<SelectionRange> split(VScrollTableRow row) {
  221. assert row.isAttached();
  222. ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
  223. int endOfFirstRange = row.getIndex() - 1;
  224. if (!(endOfFirstRange - startRow.getIndex() < 0)) {
  225. // create range of first part unless its length is < 1
  226. VScrollTableRow endOfRange = scrollBody
  227. .getRowByRowIndex(endOfFirstRange);
  228. ranges.add(new SelectionRange(startRow, endOfRange));
  229. }
  230. int startOfSecondRange = row.getIndex() + 1;
  231. if (!(getEndIndex() - startOfSecondRange < 0)) {
  232. // create range of second part unless its length is < 1
  233. VScrollTableRow startOfRange = scrollBody
  234. .getRowByRowIndex(startOfSecondRange);
  235. ranges.add(new SelectionRange(startOfRange, getEndIndex()
  236. - startOfSecondRange + 1));
  237. }
  238. return ranges;
  239. }
  240. private int getEndIndex() {
  241. return startRow.getIndex() + length - 1;
  242. }
  243. };
  244. private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
  245. private boolean initializedAndAttached = false;
  246. /**
  247. * Flag to indicate if a column width recalculation is needed due update.
  248. */
  249. private boolean headerChangedDuringUpdate = false;
  250. protected final TableHead tHead = new TableHead();
  251. private final TableFooter tFoot = new TableFooter();
  252. private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
  253. true);
  254. private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
  255. public void onKeyPress(KeyPressEvent keyPressEvent) {
  256. // This is used for Firefox only, since Firefox auto-repeat
  257. // works correctly only if we use a key press handler, other
  258. // browsers handle it correctly when using a key down handler
  259. if (!BrowserInfo.get().isGecko()) {
  260. return;
  261. }
  262. NativeEvent event = keyPressEvent.getNativeEvent();
  263. if (!enabled) {
  264. // Cancel default keyboard events on a disabled Table
  265. // (prevents scrolling)
  266. event.preventDefault();
  267. } else if (hasFocus) {
  268. // Key code in Firefox/onKeyPress is present only for
  269. // special keys, otherwise 0 is returned
  270. int keyCode = event.getKeyCode();
  271. if (keyCode == 0 && event.getCharCode() == ' ') {
  272. // Provide a keyCode for space to be compatible with
  273. // FireFox keypress event
  274. keyCode = CHARCODE_SPACE;
  275. }
  276. if (handleNavigation(keyCode,
  277. event.getCtrlKey() || event.getMetaKey(),
  278. event.getShiftKey())) {
  279. event.preventDefault();
  280. }
  281. startScrollingVelocityTimer();
  282. }
  283. }
  284. };
  285. private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
  286. public void onKeyUp(KeyUpEvent keyUpEvent) {
  287. NativeEvent event = keyUpEvent.getNativeEvent();
  288. int keyCode = event.getKeyCode();
  289. if (!isFocusable()) {
  290. cancelScrollingVelocityTimer();
  291. } else if (isNavigationKey(keyCode)) {
  292. if (keyCode == getNavigationDownKey()
  293. || keyCode == getNavigationUpKey()) {
  294. /*
  295. * in multiselect mode the server may still have value from
  296. * previous page. Clear it unless doing multiselection or
  297. * just moving focus.
  298. */
  299. if (!event.getShiftKey() && !event.getCtrlKey()) {
  300. instructServerToForgetPreviousSelections();
  301. }
  302. sendSelectedRows();
  303. }
  304. cancelScrollingVelocityTimer();
  305. navKeyDown = false;
  306. }
  307. }
  308. };
  309. private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
  310. public void onKeyDown(KeyDownEvent keyDownEvent) {
  311. NativeEvent event = keyDownEvent.getNativeEvent();
  312. // This is not used for Firefox
  313. if (BrowserInfo.get().isGecko()) {
  314. return;
  315. }
  316. if (!enabled) {
  317. // Cancel default keyboard events on a disabled Table
  318. // (prevents scrolling)
  319. event.preventDefault();
  320. } else if (hasFocus) {
  321. if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
  322. || event.getMetaKey(), event.getShiftKey())) {
  323. navKeyDown = true;
  324. event.preventDefault();
  325. }
  326. startScrollingVelocityTimer();
  327. }
  328. }
  329. };
  330. private int totalRows;
  331. private Set<String> collapsedColumns;
  332. private final RowRequestHandler rowRequestHandler;
  333. private VScrollTableBody scrollBody;
  334. private int firstvisible = 0;
  335. private boolean sortAscending;
  336. private String sortColumn;
  337. private String oldSortColumn;
  338. private boolean columnReordering;
  339. /**
  340. * This map contains captions and icon urls for actions like: * "33_c" ->
  341. * "Edit" * "33_i" -> "http://dom.com/edit.png"
  342. */
  343. private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
  344. private String[] visibleColOrder;
  345. private boolean initialContentReceived = false;
  346. private Element scrollPositionElement;
  347. private boolean enabled;
  348. private boolean showColHeaders;
  349. private boolean showColFooters;
  350. /** flag to indicate that table body has changed */
  351. private boolean isNewBody = true;
  352. /*
  353. * Read from the "recalcWidths" -attribute. When it is true, the table will
  354. * recalculate the widths for columns - desirable in some cases. For #1983,
  355. * marked experimental.
  356. */
  357. boolean recalcWidths = false;
  358. private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
  359. private String height;
  360. private String width = "";
  361. private boolean rendering = false;
  362. private boolean hasFocus = false;
  363. private int dragmode;
  364. private int multiselectmode;
  365. private int tabIndex;
  366. private TouchScrollDelegate touchScrollDelegate;
  367. private int lastRenderedHeight;
  368. /**
  369. * Values (serverCacheFirst+serverCacheLast) sent by server that tells which
  370. * rows (indexes) are in the server side cache (page buffer). -1 means
  371. * unknown. The server side cache row MUST MATCH the client side cache rows.
  372. *
  373. * If the client side cache contains additional rows with e.g. buttons, it
  374. * will cause out of sync when such a button is pressed.
  375. *
  376. * If the server side cache contains additional rows with e.g. buttons,
  377. * scrolling in the client will cause empty buttons to be rendered
  378. * (cached=true request for non-existing components)
  379. */
  380. private int serverCacheFirst = -1;
  381. private int serverCacheLast = -1;
  382. public VScrollTable() {
  383. setMultiSelectMode(MULTISELECT_MODE_DEFAULT);
  384. scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
  385. scrollBodyPanel.addFocusHandler(this);
  386. scrollBodyPanel.addBlurHandler(this);
  387. scrollBodyPanel.addScrollHandler(this);
  388. scrollBodyPanel.setStyleName(CLASSNAME + "-body");
  389. /*
  390. * Firefox auto-repeat works correctly only if we use a key press
  391. * handler, other browsers handle it correctly when using a key down
  392. * handler
  393. */
  394. if (BrowserInfo.get().isGecko()) {
  395. scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
  396. } else {
  397. scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
  398. }
  399. scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
  400. scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
  401. scrollBodyPanel.addDomHandler(new TouchStartHandler() {
  402. public void onTouchStart(TouchStartEvent event) {
  403. getTouchScrollDelegate().onTouchStart(event);
  404. }
  405. }, TouchStartEvent.getType());
  406. scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
  407. scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
  408. public void onContextMenu(ContextMenuEvent event) {
  409. handleBodyContextMenu(event);
  410. }
  411. }, ContextMenuEvent.getType());
  412. setStyleName(CLASSNAME);
  413. add(tHead);
  414. add(scrollBodyPanel);
  415. add(tFoot);
  416. rowRequestHandler = new RowRequestHandler();
  417. }
  418. protected TouchScrollDelegate getTouchScrollDelegate() {
  419. if (touchScrollDelegate == null) {
  420. touchScrollDelegate = new TouchScrollDelegate(
  421. scrollBodyPanel.getElement());
  422. }
  423. return touchScrollDelegate;
  424. }
  425. private void handleBodyContextMenu(ContextMenuEvent event) {
  426. if (enabled && bodyActionKeys != null) {
  427. int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
  428. int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
  429. top += Window.getScrollTop();
  430. left += Window.getScrollLeft();
  431. client.getContextMenu().showAt(this, left, top);
  432. // Only prevent browser context menu if there are action handlers
  433. // registered
  434. event.stopPropagation();
  435. event.preventDefault();
  436. }
  437. }
  438. /**
  439. * Fires a column resize event which sends the resize information to the
  440. * server.
  441. *
  442. * @param columnId
  443. * The columnId of the column which was resized
  444. * @param originalWidth
  445. * The width in pixels of the column before the resize event
  446. * @param newWidth
  447. * The width in pixels of the column after the resize event
  448. */
  449. private void fireColumnResizeEvent(String columnId, int originalWidth,
  450. int newWidth) {
  451. client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
  452. false);
  453. client.updateVariable(paintableId, "columnResizeEventPrev",
  454. originalWidth, false);
  455. client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
  456. immediate);
  457. }
  458. /**
  459. * Non-immediate variable update of column widths for a collection of
  460. * columns.
  461. *
  462. * @param columns
  463. * the columns to trigger the events for.
  464. */
  465. private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
  466. String[] newSizes = new String[columns.size()];
  467. int ix = 0;
  468. for (HeaderCell cell : columns) {
  469. newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
  470. }
  471. client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
  472. false);
  473. }
  474. /**
  475. * Moves the focus one step down
  476. *
  477. * @return Returns true if succeeded
  478. */
  479. private boolean moveFocusDown() {
  480. return moveFocusDown(0);
  481. }
  482. /**
  483. * Moves the focus down by 1+offset rows
  484. *
  485. * @return Returns true if succeeded, else false if the selection could not
  486. * be move downwards
  487. */
  488. private boolean moveFocusDown(int offset) {
  489. if (isSelectable()) {
  490. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  491. // FIXME should focus first visible from top, not first rendered
  492. // ??
  493. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  494. .next());
  495. } else {
  496. VScrollTableRow next = getNextRow(focusedRow, offset);
  497. if (next != null) {
  498. return setRowFocus(next);
  499. }
  500. }
  501. }
  502. return false;
  503. }
  504. /**
  505. * Moves the selection one step up
  506. *
  507. * @return Returns true if succeeded
  508. */
  509. private boolean moveFocusUp() {
  510. return moveFocusUp(0);
  511. }
  512. /**
  513. * Moves the focus row upwards
  514. *
  515. * @return Returns true if succeeded, else false if the selection could not
  516. * be move upwards
  517. *
  518. */
  519. private boolean moveFocusUp(int offset) {
  520. if (isSelectable()) {
  521. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  522. // FIXME logic is exactly the same as in moveFocusDown, should
  523. // be the opposite??
  524. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  525. .next());
  526. } else {
  527. VScrollTableRow prev = getPreviousRow(focusedRow, offset);
  528. if (prev != null) {
  529. return setRowFocus(prev);
  530. } else {
  531. VConsole.log("no previous available");
  532. }
  533. }
  534. }
  535. return false;
  536. }
  537. /**
  538. * Selects a row where the current selection head is
  539. *
  540. * @param ctrlSelect
  541. * Is the selection a ctrl+selection
  542. * @param shiftSelect
  543. * Is the selection a shift+selection
  544. * @return Returns truw
  545. */
  546. private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
  547. if (focusedRow != null) {
  548. // Arrows moves the selection and clears previous selections
  549. if (isSelectable() && !ctrlSelect && !shiftSelect) {
  550. deselectAll();
  551. focusedRow.toggleSelection();
  552. selectionRangeStart = focusedRow;
  553. } else if (isSelectable() && ctrlSelect && !shiftSelect) {
  554. // Ctrl+arrows moves selection head
  555. selectionRangeStart = focusedRow;
  556. // No selection, only selection head is moved
  557. } else if (isMultiSelectModeAny() && !ctrlSelect && shiftSelect) {
  558. // Shift+arrows selection selects a range
  559. focusedRow.toggleShiftSelection(shiftSelect);
  560. }
  561. }
  562. }
  563. /**
  564. * Sends the selection to the server if changed since the last update/visit.
  565. */
  566. protected void sendSelectedRows() {
  567. sendSelectedRows(immediate);
  568. }
  569. /**
  570. * Sends the selection to the server if it has been changed since the last
  571. * update/visit.
  572. *
  573. * @param immediately
  574. * set to true to immediately send the rows
  575. */
  576. protected void sendSelectedRows(boolean immediately) {
  577. // Don't send anything if selection has not changed
  578. if (!selectionChanged) {
  579. return;
  580. }
  581. // Reset selection changed flag
  582. selectionChanged = false;
  583. // Note: changing the immediateness of this might require changes to
  584. // "clickEvent" immediateness also.
  585. if (isMultiSelectModeDefault()) {
  586. // Convert ranges to a set of strings
  587. Set<String> ranges = new HashSet<String>();
  588. for (SelectionRange range : selectedRowRanges) {
  589. ranges.add(range.toString());
  590. }
  591. // Send the selected row ranges
  592. client.updateVariable(paintableId, "selectedRanges",
  593. ranges.toArray(new String[selectedRowRanges.size()]), false);
  594. // clean selectedRowKeys so that they don't contain excess values
  595. for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
  596. .hasNext();) {
  597. String key = iterator.next();
  598. VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
  599. if (renderedRowByKey != null) {
  600. for (SelectionRange range : selectedRowRanges) {
  601. if (range.inRange(renderedRowByKey)) {
  602. iterator.remove();
  603. }
  604. }
  605. } else {
  606. // orphaned selected key, must be in a range, ignore
  607. iterator.remove();
  608. }
  609. }
  610. }
  611. // Send the selected rows
  612. client.updateVariable(paintableId, "selected",
  613. selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
  614. immediately);
  615. }
  616. /**
  617. * Get the key that moves the selection head upwards. By default it is the
  618. * up arrow key but by overriding this you can change the key to whatever
  619. * you want.
  620. *
  621. * @return The keycode of the key
  622. */
  623. protected int getNavigationUpKey() {
  624. return KeyCodes.KEY_UP;
  625. }
  626. /**
  627. * Get the key that moves the selection head downwards. By default it is the
  628. * down arrow key but by overriding this you can change the key to whatever
  629. * you want.
  630. *
  631. * @return The keycode of the key
  632. */
  633. protected int getNavigationDownKey() {
  634. return KeyCodes.KEY_DOWN;
  635. }
  636. /**
  637. * Get the key that scrolls to the left in the table. By default it is the
  638. * left arrow key but by overriding this you can change the key to whatever
  639. * you want.
  640. *
  641. * @return The keycode of the key
  642. */
  643. protected int getNavigationLeftKey() {
  644. return KeyCodes.KEY_LEFT;
  645. }
  646. /**
  647. * Get the key that scroll to the right on the table. By default it is the
  648. * right arrow key but by overriding this you can change the key to whatever
  649. * you want.
  650. *
  651. * @return The keycode of the key
  652. */
  653. protected int getNavigationRightKey() {
  654. return KeyCodes.KEY_RIGHT;
  655. }
  656. /**
  657. * Get the key that selects an item in the table. By default it is the space
  658. * bar key but by overriding this you can change the key to whatever you
  659. * want.
  660. *
  661. * @return
  662. */
  663. protected int getNavigationSelectKey() {
  664. return CHARCODE_SPACE;
  665. }
  666. /**
  667. * Get the key the moves the selection one page up in the table. By default
  668. * this is the Page Up key but by overriding this you can change the key to
  669. * whatever you want.
  670. *
  671. * @return
  672. */
  673. protected int getNavigationPageUpKey() {
  674. return KeyCodes.KEY_PAGEUP;
  675. }
  676. /**
  677. * Get the key the moves the selection one page down in the table. By
  678. * default this is the Page Down key but by overriding this you can change
  679. * the key to whatever you want.
  680. *
  681. * @return
  682. */
  683. protected int getNavigationPageDownKey() {
  684. return KeyCodes.KEY_PAGEDOWN;
  685. }
  686. /**
  687. * Get the key the moves the selection to the beginning of the table. By
  688. * default this is the Home key but by overriding this you can change the
  689. * key to whatever you want.
  690. *
  691. * @return
  692. */
  693. protected int getNavigationStartKey() {
  694. return KeyCodes.KEY_HOME;
  695. }
  696. /**
  697. * Get the key the moves the selection to the end of the table. By default
  698. * this is the End key but by overriding this you can change the key to
  699. * whatever you want.
  700. *
  701. * @return
  702. */
  703. protected int getNavigationEndKey() {
  704. return KeyCodes.KEY_END;
  705. }
  706. /*
  707. * (non-Javadoc)
  708. *
  709. * @see
  710. * com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
  711. * .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
  712. */
  713. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  714. rendering = true;
  715. if (uidl.hasAttribute(ATTRIBUTE_PAGEBUFFER_FIRST)) {
  716. serverCacheFirst = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_FIRST);
  717. serverCacheLast = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_LAST);
  718. } else {
  719. serverCacheFirst = -1;
  720. serverCacheLast = -1;
  721. }
  722. /*
  723. * We need to do this before updateComponent since updateComponent calls
  724. * this.setHeight() which will calculate a new body height depending on
  725. * the space available.
  726. */
  727. if (uidl.hasAttribute("colfooters")) {
  728. showColFooters = uidl.getBooleanAttribute("colfooters");
  729. }
  730. tFoot.setVisible(showColFooters);
  731. if (client.updateComponent(this, uidl, true)) {
  732. rendering = false;
  733. return;
  734. }
  735. enabled = !uidl.hasAttribute("disabled");
  736. if (BrowserInfo.get().isIE8() && !enabled) {
  737. /*
  738. * The disabled shim will not cover the table body if it is relative
  739. * in IE8. See #7324
  740. */
  741. scrollBodyPanel.getElement().getStyle()
  742. .setPosition(Position.STATIC);
  743. } else if (BrowserInfo.get().isIE8()) {
  744. scrollBodyPanel.getElement().getStyle()
  745. .setPosition(Position.RELATIVE);
  746. }
  747. this.client = client;
  748. paintableId = uidl.getStringAttribute("id");
  749. immediate = uidl.getBooleanAttribute("immediate");
  750. int previousTotalRows = totalRows;
  751. updateTotalRows(uidl);
  752. boolean totalRowsChanged = (totalRows != previousTotalRows);
  753. updateDragMode(uidl);
  754. updateSelectionProperties(uidl);
  755. if (uidl.hasAttribute("alb")) {
  756. bodyActionKeys = uidl.getStringArrayAttribute("alb");
  757. } else {
  758. // Need to clear the actions if the action handlers have been
  759. // removed
  760. bodyActionKeys = null;
  761. }
  762. setCacheRateFromUIDL(uidl);
  763. recalcWidths = uidl.hasAttribute("recalcWidths");
  764. if (recalcWidths) {
  765. tHead.clear();
  766. tFoot.clear();
  767. }
  768. updatePageLength(uidl);
  769. updateFirstVisibleAndScrollIfNeeded(uidl);
  770. showRowHeaders = uidl.getBooleanAttribute("rowheaders");
  771. showColHeaders = uidl.getBooleanAttribute("colheaders");
  772. updateSortingProperties(uidl);
  773. boolean keyboardSelectionOverRowFetchInProgress = selectSelectedRows(uidl);
  774. updateActionMap(uidl);
  775. updateColumnProperties(uidl);
  776. UIDL ac = uidl.getChildByTagName("-ac");
  777. if (ac == null) {
  778. if (dropHandler != null) {
  779. // remove dropHandler if not present anymore
  780. dropHandler = null;
  781. }
  782. } else {
  783. if (dropHandler == null) {
  784. dropHandler = new VScrollTableDropHandler();
  785. }
  786. dropHandler.updateAcceptRules(ac);
  787. }
  788. UIDL partialRowAdditions = uidl.getChildByTagName("prows");
  789. UIDL partialRowUpdates = uidl.getChildByTagName("urows");
  790. if (partialRowUpdates != null || partialRowAdditions != null) {
  791. // we may have pending cache row fetch, cancel it. See #2136
  792. rowRequestHandler.cancel();
  793. updateRowsInBody(partialRowUpdates);
  794. addAndRemoveRows(partialRowAdditions);
  795. } else {
  796. UIDL rowData = uidl.getChildByTagName("rows");
  797. if (rowData != null) {
  798. // we may have pending cache row fetch, cancel it. See #2136
  799. rowRequestHandler.cancel();
  800. if (!recalcWidths && initializedAndAttached) {
  801. updateBody(rowData, uidl.getIntAttribute("firstrow"),
  802. uidl.getIntAttribute("rows"));
  803. if (headerChangedDuringUpdate) {
  804. triggerLazyColumnAdjustment(true);
  805. } else if (!isScrollPositionVisible()
  806. || totalRowsChanged
  807. || lastRenderedHeight != scrollBody
  808. .getOffsetHeight()) {
  809. // webkits may still bug with their disturbing scrollbar
  810. // bug, see #3457
  811. // Run overflow fix for the scrollable area
  812. // #6698 - If there's a scroll going on, don't abort it
  813. // by changing overflows as the length of the contents
  814. // *shouldn't* have changed (unless the number of rows
  815. // or the height of the widget has also changed)
  816. Scheduler.get().scheduleDeferred(new Command() {
  817. public void execute() {
  818. Util.runWebkitOverflowAutoFix(scrollBodyPanel
  819. .getElement());
  820. }
  821. });
  822. }
  823. } else {
  824. initializeRows(uidl, rowData);
  825. }
  826. }
  827. }
  828. if (!isSelectable()) {
  829. scrollBody.addStyleName(CLASSNAME + "-body-noselection");
  830. } else {
  831. scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
  832. }
  833. hideScrollPositionAnnotation();
  834. purgeUnregistryBag();
  835. // selection is no in sync with server, avoid excessive server visits by
  836. // clearing to flag used during the normal operation
  837. if (!keyboardSelectionOverRowFetchInProgress) {
  838. selectionChanged = false;
  839. }
  840. /*
  841. * This is called when the Home or page up button has been pressed in
  842. * selectable mode and the next selected row was not yet rendered in the
  843. * client
  844. */
  845. if (selectFirstItemInNextRender || focusFirstItemInNextRender) {
  846. selectFirstRenderedRowInViewPort(focusFirstItemInNextRender);
  847. selectFirstItemInNextRender = focusFirstItemInNextRender = false;
  848. }
  849. /*
  850. * This is called when the page down or end button has been pressed in
  851. * selectable mode and the next selected row was not yet rendered in the
  852. * client
  853. */
  854. if (selectLastItemInNextRender || focusLastItemInNextRender) {
  855. selectLastRenderedRowInViewPort(focusLastItemInNextRender);
  856. selectLastItemInNextRender = focusLastItemInNextRender = false;
  857. }
  858. multiselectPending = false;
  859. if (focusedRow != null) {
  860. if (!focusedRow.isAttached() && !rowRequestHandler.isRunning()) {
  861. // focused row has been orphaned, can't focus
  862. focusRowFromBody();
  863. }
  864. }
  865. tabIndex = uidl.hasAttribute("tabindex") ? uidl
  866. .getIntAttribute("tabindex") : 0;
  867. setProperTabIndex();
  868. resizeSortedColumnForSortIndicator();
  869. // Remember this to detect situations where overflow hack might be
  870. // needed during scrolling
  871. lastRenderedHeight = scrollBody.getOffsetHeight();
  872. rendering = false;
  873. headerChangedDuringUpdate = false;
  874. }
  875. private void initializeRows(UIDL uidl, UIDL rowData) {
  876. if (scrollBody != null) {
  877. scrollBody.removeFromParent();
  878. lazyUnregistryBag.add(scrollBody);
  879. }
  880. scrollBody = createScrollBody();
  881. scrollBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"),
  882. uidl.getIntAttribute("rows"));
  883. scrollBodyPanel.add(scrollBody);
  884. // New body starts scrolled to the left, make sure the header and footer
  885. // are also scrolled to the left
  886. tHead.setHorizontalScrollPosition(0);
  887. tFoot.setHorizontalScrollPosition(0);
  888. initialContentReceived = true;
  889. if (isAttached()) {
  890. sizeInit();
  891. }
  892. scrollBody.restoreRowVisibility();
  893. }
  894. private void updateColumnProperties(UIDL uidl) {
  895. updateColumnOrder(uidl);
  896. updateCollapsedColumns(uidl);
  897. UIDL vc = uidl.getChildByTagName("visiblecolumns");
  898. if (vc != null) {
  899. tHead.updateCellsFromUIDL(vc);
  900. tFoot.updateCellsFromUIDL(vc);
  901. }
  902. updateHeader(uidl.getStringArrayAttribute("vcolorder"));
  903. updateFooter(uidl.getStringArrayAttribute("vcolorder"));
  904. }
  905. private void updateCollapsedColumns(UIDL uidl) {
  906. if (uidl.hasVariable("collapsedcolumns")) {
  907. tHead.setColumnCollapsingAllowed(true);
  908. collapsedColumns = uidl
  909. .getStringArrayVariableAsSet("collapsedcolumns");
  910. } else {
  911. tHead.setColumnCollapsingAllowed(false);
  912. }
  913. }
  914. private void updateColumnOrder(UIDL uidl) {
  915. if (uidl.hasVariable("columnorder")) {
  916. columnReordering = true;
  917. columnOrder = uidl.getStringArrayVariable("columnorder");
  918. } else {
  919. columnReordering = false;
  920. columnOrder = null;
  921. }
  922. }
  923. private boolean selectSelectedRows(UIDL uidl) {
  924. boolean keyboardSelectionOverRowFetchInProgress = false;
  925. if (uidl.hasVariable("selected")) {
  926. final Set<String> selectedKeys = uidl
  927. .getStringArrayVariableAsSet("selected");
  928. if (scrollBody != null) {
  929. Iterator<Widget> iterator = scrollBody.iterator();
  930. while (iterator.hasNext()) {
  931. /*
  932. * Make the focus reflect to the server side state unless we
  933. * are currently selecting multiple rows with keyboard.
  934. */
  935. VScrollTableRow row = (VScrollTableRow) iterator.next();
  936. boolean selected = selectedKeys.contains(row.getKey());
  937. if (!selected
  938. && unSyncedselectionsBeforeRowFetch != null
  939. && unSyncedselectionsBeforeRowFetch.contains(row
  940. .getKey())) {
  941. selected = true;
  942. keyboardSelectionOverRowFetchInProgress = true;
  943. }
  944. if (selected != row.isSelected()) {
  945. row.toggleSelection();
  946. if (!isSingleSelectMode() && !selected) {
  947. // Update selection range in case a row is
  948. // unselected from the middle of a range - #8076
  949. removeRowFromUnsentSelectionRanges(row);
  950. }
  951. }
  952. }
  953. }
  954. }
  955. unSyncedselectionsBeforeRowFetch = null;
  956. return keyboardSelectionOverRowFetchInProgress;
  957. }
  958. private void updateSortingProperties(UIDL uidl) {
  959. oldSortColumn = sortColumn;
  960. if (uidl.hasVariable("sortascending")) {
  961. sortAscending = uidl.getBooleanVariable("sortascending");
  962. sortColumn = uidl.getStringVariable("sortcolumn");
  963. }
  964. }
  965. private void resizeSortedColumnForSortIndicator() {
  966. // Force recalculation of the captionContainer element inside the header
  967. // cell to accomodate for the size of the sort arrow.
  968. HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
  969. if (sortedHeader != null) {
  970. tHead.resizeCaptionContainer(sortedHeader);
  971. }
  972. // Also recalculate the width of the captionContainer element in the
  973. // previously sorted header, since this now has more room.
  974. HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
  975. if (oldSortedHeader != null) {
  976. tHead.resizeCaptionContainer(oldSortedHeader);
  977. }
  978. }
  979. private void updateFirstVisibleAndScrollIfNeeded(UIDL uidl) {
  980. firstvisible = uidl.hasVariable("firstvisible") ? uidl
  981. .getIntVariable("firstvisible") : 0;
  982. if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
  983. // received 'surprising' firstvisible from server: scroll there
  984. firstRowInViewPort = firstvisible;
  985. scrollBodyPanel
  986. .setScrollPosition(measureRowHeightOffset(firstvisible));
  987. }
  988. }
  989. protected int measureRowHeightOffset(int rowIx) {
  990. return (int) (rowIx * scrollBody.getRowHeight());
  991. }
  992. private void updatePageLength(UIDL uidl) {
  993. int oldPageLength = pageLength;
  994. if (uidl.hasAttribute("pagelength")) {
  995. pageLength = uidl.getIntAttribute("pagelength");
  996. } else {
  997. // pagelenght is "0" meaning scrolling is turned off
  998. pageLength = totalRows;
  999. }
  1000. if (oldPageLength != pageLength && initializedAndAttached) {
  1001. // page length changed, need to update size
  1002. sizeInit();
  1003. }
  1004. }
  1005. private void updateSelectionProperties(UIDL uidl) {
  1006. setMultiSelectMode(uidl.hasAttribute("multiselectmode") ? uidl
  1007. .getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT);
  1008. nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
  1009. .getBooleanAttribute("nsa") : true;
  1010. if (uidl.hasAttribute("selectmode")) {
  1011. if (uidl.getBooleanAttribute("readonly")) {
  1012. selectMode = Table.SELECT_MODE_NONE;
  1013. } else if (uidl.getStringAttribute("selectmode").equals("multi")) {
  1014. selectMode = Table.SELECT_MODE_MULTI;
  1015. } else if (uidl.getStringAttribute("selectmode").equals("single")) {
  1016. selectMode = Table.SELECT_MODE_SINGLE;
  1017. } else {
  1018. selectMode = Table.SELECT_MODE_NONE;
  1019. }
  1020. }
  1021. }
  1022. private void updateDragMode(UIDL uidl) {
  1023. dragmode = uidl.hasAttribute("dragmode") ? uidl
  1024. .getIntAttribute("dragmode") : 0;
  1025. if (BrowserInfo.get().isIE()) {
  1026. if (dragmode > 0) {
  1027. getElement().setPropertyJSO("onselectstart",
  1028. getPreventTextSelectionIEHack());
  1029. } else {
  1030. getElement().setPropertyJSO("onselectstart", null);
  1031. }
  1032. }
  1033. }
  1034. protected void updateTotalRows(UIDL uidl) {
  1035. int newTotalRows = uidl.getIntAttribute("totalrows");
  1036. if (newTotalRows != getTotalRows()) {
  1037. if (scrollBody != null) {
  1038. if (getTotalRows() == 0) {
  1039. tHead.clear();
  1040. tFoot.clear();
  1041. }
  1042. initializedAndAttached = false;
  1043. initialContentReceived = false;
  1044. isNewBody = true;
  1045. }
  1046. setTotalRows(newTotalRows);
  1047. }
  1048. }
  1049. protected void setTotalRows(int newTotalRows) {
  1050. totalRows = newTotalRows;
  1051. }
  1052. protected int getTotalRows() {
  1053. return totalRows;
  1054. }
  1055. private void focusRowFromBody() {
  1056. if (selectedRowKeys.size() == 1) {
  1057. // try to focus a row currently selected and in viewport
  1058. String selectedRowKey = selectedRowKeys.iterator().next();
  1059. if (selectedRowKey != null) {
  1060. VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
  1061. if (renderedRow == null || !renderedRow.isInViewPort()) {
  1062. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1063. } else {
  1064. setRowFocus(renderedRow);
  1065. }
  1066. }
  1067. } else {
  1068. // multiselect mode
  1069. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1070. }
  1071. }
  1072. protected VScrollTableBody createScrollBody() {
  1073. return new VScrollTableBody();
  1074. }
  1075. /**
  1076. * Selects the last row visible in the table
  1077. *
  1078. * @param focusOnly
  1079. * Should the focus only be moved to the last row
  1080. */
  1081. private void selectLastRenderedRowInViewPort(boolean focusOnly) {
  1082. int index = firstRowInViewPort + getFullyVisibleRowCount();
  1083. VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
  1084. if (lastRowInViewport == null) {
  1085. // this should not happen in normal situations (white space at the
  1086. // end of viewport). Select the last rendered as a fallback.
  1087. lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
  1088. .getLastRendered());
  1089. if (lastRowInViewport == null) {
  1090. return; // empty table
  1091. }
  1092. }
  1093. setRowFocus(lastRowInViewport);
  1094. if (!focusOnly) {
  1095. selectFocusedRow(false, multiselectPending);
  1096. sendSelectedRows();
  1097. }
  1098. }
  1099. /**
  1100. * Selects the first row visible in the table
  1101. *
  1102. * @param focusOnly
  1103. * Should the focus only be moved to the first row
  1104. */
  1105. private void selectFirstRenderedRowInViewPort(boolean focusOnly) {
  1106. int index = firstRowInViewPort;
  1107. VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
  1108. if (firstInViewport == null) {
  1109. // this should not happen in normal situations
  1110. return;
  1111. }
  1112. setRowFocus(firstInViewport);
  1113. if (!focusOnly) {
  1114. selectFocusedRow(false, multiselectPending);
  1115. sendSelectedRows();
  1116. }
  1117. }
  1118. private void setCacheRateFromUIDL(UIDL uidl) {
  1119. setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
  1120. : CACHE_RATE_DEFAULT);
  1121. }
  1122. private void setCacheRate(double d) {
  1123. if (cache_rate != d) {
  1124. cache_rate = d;
  1125. cache_react_rate = 0.75 * d;
  1126. }
  1127. }
  1128. /**
  1129. * Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
  1130. * IScrollTableRows). This is done lazily as Table must survive from
  1131. * "subtreecaching" logic.
  1132. */
  1133. private void purgeUnregistryBag() {
  1134. for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
  1135. .hasNext();) {
  1136. VPaintableMap.get(client)
  1137. .unregisterChildPaintables(iterator.next());
  1138. }
  1139. lazyUnregistryBag.clear();
  1140. }
  1141. private void updateActionMap(UIDL mainUidl) {
  1142. UIDL actionsUidl = mainUidl.getChildByTagName("actions");
  1143. if (actionsUidl == null) {
  1144. return;
  1145. }
  1146. final Iterator<?> it = actionsUidl.getChildIterator();
  1147. while (it.hasNext()) {
  1148. final UIDL action = (UIDL) it.next();
  1149. final String key = action.getStringAttribute("key");
  1150. final String caption = action.getStringAttribute("caption");
  1151. actionMap.put(key + "_c", caption);
  1152. if (action.hasAttribute("icon")) {
  1153. // TODO need some uri handling ??
  1154. actionMap.put(key + "_i", client.translateVaadinUri(action
  1155. .getStringAttribute("icon")));
  1156. } else {
  1157. actionMap.remove(key + "_i");
  1158. }
  1159. }
  1160. }
  1161. public String getActionCaption(String actionKey) {
  1162. return actionMap.get(actionKey + "_c");
  1163. }
  1164. public String getActionIcon(String actionKey) {
  1165. return actionMap.get(actionKey + "_i");
  1166. }
  1167. private void updateHeader(String[] strings) {
  1168. if (strings == null) {
  1169. return;
  1170. }
  1171. int visibleCols = strings.length;
  1172. int colIndex = 0;
  1173. if (showRowHeaders) {
  1174. tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1175. visibleCols++;
  1176. visibleColOrder = new String[visibleCols];
  1177. visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
  1178. colIndex++;
  1179. } else {
  1180. visibleColOrder = new String[visibleCols];
  1181. tHead.removeCell(ROW_HEADER_COLUMN_KEY);
  1182. }
  1183. int i;
  1184. for (i = 0; i < strings.length; i++) {
  1185. final String cid = strings[i];
  1186. visibleColOrder[colIndex] = cid;
  1187. tHead.enableColumn(cid, colIndex);
  1188. colIndex++;
  1189. }
  1190. tHead.setVisible(showColHeaders);
  1191. setContainerHeight();
  1192. }
  1193. /**
  1194. * Updates footers.
  1195. * <p>
  1196. * Update headers whould be called before this method is called!
  1197. * </p>
  1198. *
  1199. * @param strings
  1200. */
  1201. private void updateFooter(String[] strings) {
  1202. if (strings == null) {
  1203. return;
  1204. }
  1205. // Add dummy column if row headers are present
  1206. int colIndex = 0;
  1207. if (showRowHeaders) {
  1208. tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1209. colIndex++;
  1210. } else {
  1211. tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
  1212. }
  1213. int i;
  1214. for (i = 0; i < strings.length; i++) {
  1215. final String cid = strings[i];
  1216. tFoot.enableColumn(cid, colIndex);
  1217. colIndex++;
  1218. }
  1219. tFoot.setVisible(showColFooters);
  1220. }
  1221. /**
  1222. * @param uidl
  1223. * which contains row data
  1224. * @param firstRow
  1225. * first row in data set
  1226. * @param reqRows
  1227. * amount of rows in data set
  1228. */
  1229. private void updateBody(UIDL uidl, int firstRow, int reqRows) {
  1230. if (uidl == null || reqRows < 1) {
  1231. // container is empty, remove possibly existing rows
  1232. if (firstRow <= 0) {
  1233. while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
  1234. scrollBody.unlinkRow(false);
  1235. }
  1236. scrollBody.unlinkRow(false);
  1237. }
  1238. return;
  1239. }
  1240. scrollBody.renderRows(uidl, firstRow, reqRows);
  1241. discardRowsOutsideCacheWindow();
  1242. }
  1243. private void updateRowsInBody(UIDL partialRowUpdates) {
  1244. if (partialRowUpdates == null) {
  1245. return;
  1246. }
  1247. int firstRowIx = partialRowUpdates.getIntAttribute("firsturowix");
  1248. int count = partialRowUpdates.getIntAttribute("numurows");
  1249. scrollBody.unlinkRows(firstRowIx, count);
  1250. scrollBody.insertRows(partialRowUpdates, firstRowIx, count);
  1251. }
  1252. /**
  1253. * Updates the internal cache by unlinking rows that fall outside of the
  1254. * caching window.
  1255. */
  1256. protected void discardRowsOutsideCacheWindow() {
  1257. int firstRowToKeep = (int) (firstRowInViewPort - pageLength
  1258. * cache_rate);
  1259. int lastRowToKeep = (int) (firstRowInViewPort + pageLength + pageLength
  1260. * cache_rate);
  1261. debug("Client side calculated cache rows to keep: " + firstRowToKeep
  1262. + "-" + lastRowToKeep);
  1263. if (serverCacheFirst != -1) {
  1264. firstRowToKeep = serverCacheFirst;
  1265. lastRowToKeep = serverCacheLast;
  1266. debug("Server cache rows that override: " + serverCacheFirst + "-"
  1267. + serverCacheLast);
  1268. if (firstRowToKeep < scrollBody.getFirstRendered()
  1269. || lastRowToKeep > scrollBody.getLastRendered()) {
  1270. debug("*** Server wants us to keep " + serverCacheFirst + "-"
  1271. + serverCacheLast + " but we only have rows "
  1272. + scrollBody.getFirstRendered() + "-"
  1273. + scrollBody.getLastRendered() + " rendered!");
  1274. }
  1275. }
  1276. discardRowsOutsideOf(firstRowToKeep, lastRowToKeep);
  1277. scrollBody.fixSpacers();
  1278. scrollBody.restoreRowVisibility();
  1279. }
  1280. private void discardRowsOutsideOf(int optimalFirstRow, int optimalLastRow) {
  1281. /*
  1282. * firstDiscarded and lastDiscarded are only calculated for debug
  1283. * purposes
  1284. */
  1285. int firstDiscarded = -1, lastDiscarded = -1;
  1286. boolean cont = true;
  1287. while (cont && scrollBody.getLastRendered() > optimalFirstRow
  1288. && scrollBody.getFirstRendered() < optimalFirstRow) {
  1289. if (firstDiscarded == -1) {
  1290. firstDiscarded = scrollBody.getFirstRendered();
  1291. }
  1292. // removing row from start
  1293. cont = scrollBody.unlinkRow(true);
  1294. }
  1295. if (firstDiscarded != -1) {
  1296. lastDiscarded = scrollBody.getFirstRendered() - 1;
  1297. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1298. }
  1299. firstDiscarded = lastDiscarded = -1;
  1300. cont = true;
  1301. while (cont && scrollBody.getLastRendered() > optimalLastRow) {
  1302. if (lastDiscarded == -1) {
  1303. lastDiscarded = scrollBody.getLastRendered();
  1304. }
  1305. // removing row from the end
  1306. cont = scrollBody.unlinkRow(false);
  1307. }
  1308. if (lastDiscarded != -1) {
  1309. firstDiscarded = scrollBody.getLastRendered() + 1;
  1310. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1311. }
  1312. debug("Now in cache: " + scrollBody.getFirstRendered() + "-"
  1313. + scrollBody.getLastRendered());
  1314. }
  1315. /**
  1316. * Inserts rows in the table body or removes them from the table body based
  1317. * on the commands in the UIDL.
  1318. *
  1319. * @param partialRowAdditions
  1320. * the UIDL containing row updates.
  1321. */
  1322. protected void addAndRemoveRows(UIDL partialRowAdditions) {
  1323. if (partialRowAdditions == null) {
  1324. return;
  1325. }
  1326. if (partialRowAdditions.hasAttribute("hide")) {
  1327. scrollBody.unlinkAndReindexRows(
  1328. partialRowAdditions.getIntAttribute("firstprowix"),
  1329. partialRowAdditions.getIntAttribute("numprows"));
  1330. scrollBody.ensureCacheFilled();
  1331. } else {
  1332. if (partialRowAdditions.hasAttribute("delbelow")) {
  1333. scrollBody.insertRowsDeleteBelow(partialRowAdditions,
  1334. partialRowAdditions.getIntAttribute("firstprowix"),
  1335. partialRowAdditions.getIntAttribute("numprows"));
  1336. } else {
  1337. scrollBody.insertAndReindexRows(partialRowAdditions,
  1338. partialRowAdditions.getIntAttribute("firstprowix"),
  1339. partialRowAdditions.getIntAttribute("numprows"));
  1340. }
  1341. }
  1342. discardRowsOutsideCacheWindow();
  1343. }
  1344. /**
  1345. * Gives correct column index for given column key ("cid" in UIDL).
  1346. *
  1347. * @param colKey
  1348. * @return column index of visible columns, -1 if column not visible
  1349. */
  1350. private int getColIndexByKey(String colKey) {
  1351. // return 0 if asked for rowHeaders
  1352. if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
  1353. return 0;
  1354. }
  1355. for (int i = 0; i < visibleColOrder.length; i++) {
  1356. if (visibleColOrder[i].equals(colKey)) {
  1357. return i;
  1358. }
  1359. }
  1360. return -1;
  1361. }
  1362. private boolean isMultiSelectModeSimple() {
  1363. return selectMode == Table.SELECT_MODE_MULTI
  1364. && multiselectmode == MULTISELECT_MODE_SIMPLE;
  1365. }
  1366. private boolean isSingleSelectMode() {
  1367. return selectMode == Table.SELECT_MODE_SINGLE;
  1368. }
  1369. private boolean isMultiSelectModeAny() {
  1370. return selectMode == Table.SELECT_MODE_MULTI;
  1371. }
  1372. private boolean isMultiSelectModeDefault() {
  1373. return selectMode == Table.SELECT_MODE_MULTI
  1374. && multiselectmode == MULTISELECT_MODE_DEFAULT;
  1375. }
  1376. private void setMultiSelectMode(int multiselectmode) {
  1377. if (BrowserInfo.get().isTouchDevice()) {
  1378. // Always use the simple mode for touch devices that do not have
  1379. // shift/ctrl keys
  1380. this.multiselectmode = MULTISELECT_MODE_SIMPLE;
  1381. } else {
  1382. this.multiselectmode = multiselectmode;
  1383. }
  1384. }
  1385. protected boolean isSelectable() {
  1386. return selectMode > Table.SELECT_MODE_NONE;
  1387. }
  1388. private boolean isCollapsedColumn(String colKey) {
  1389. if (collapsedColumns == null) {
  1390. return false;
  1391. }
  1392. if (collapsedColumns.contains(colKey)) {
  1393. return true;
  1394. }
  1395. return false;
  1396. }
  1397. private String getColKeyByIndex(int index) {
  1398. return tHead.getHeaderCell(index).getColKey();
  1399. }
  1400. private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
  1401. final HeaderCell hcell = tHead.getHeaderCell(colIndex);
  1402. // Make sure that the column grows to accommodate the sort indicator if
  1403. // necessary.
  1404. if (w < hcell.getMinWidth()) {
  1405. w = hcell.getMinWidth();
  1406. }
  1407. // Set header column width
  1408. hcell.setWidth(w, isDefinedWidth);
  1409. // Ensure indicators have been taken into account
  1410. tHead.resizeCaptionContainer(hcell);
  1411. // Set body column width
  1412. scrollBody.setColWidth(colIndex, w);
  1413. // Set footer column width
  1414. FooterCell fcell = tFoot.getFooterCell(colIndex);
  1415. fcell.setWidth(w, isDefinedWidth);
  1416. }
  1417. private int getColWidth(String colKey) {
  1418. return tHead.getHeaderCell(colKey).getWidth();
  1419. }
  1420. /**
  1421. * Get a rendered row by its key
  1422. *
  1423. * @param key
  1424. * The key to search with
  1425. * @return
  1426. */
  1427. protected VScrollTableRow getRenderedRowByKey(String key) {
  1428. if (scrollBody != null) {
  1429. final Iterator<Widget> it = scrollBody.iterator();
  1430. VScrollTableRow r = null;
  1431. while (it.hasNext()) {
  1432. r = (VScrollTableRow) it.next();
  1433. if (r.getKey().equals(key)) {
  1434. return r;
  1435. }
  1436. }
  1437. }
  1438. return null;
  1439. }
  1440. /**
  1441. * Returns the next row to the given row
  1442. *
  1443. * @param row
  1444. * The row to calculate from
  1445. *
  1446. * @return The next row or null if no row exists
  1447. */
  1448. private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
  1449. final Iterator<Widget> it = scrollBody.iterator();
  1450. VScrollTableRow r = null;
  1451. while (it.hasNext()) {
  1452. r = (VScrollTableRow) it.next();
  1453. if (r == row) {
  1454. r = null;
  1455. while (offset >= 0 && it.hasNext()) {
  1456. r = (VScrollTableRow) it.next();
  1457. offset--;
  1458. }
  1459. return r;
  1460. }
  1461. }
  1462. return null;
  1463. }
  1464. /**
  1465. * Returns the previous row from the given row
  1466. *
  1467. * @param row
  1468. * The row to calculate from
  1469. * @return The previous row or null if no row exists
  1470. */
  1471. private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
  1472. final Iterator<Widget> it = scrollBody.iterator();
  1473. final Iterator<Widget> offsetIt = scrollBody.iterator();
  1474. VScrollTableRow r = null;
  1475. VScrollTableRow prev = null;
  1476. while (it.hasNext()) {
  1477. r = (VScrollTableRow) it.next();
  1478. if (offset < 0) {
  1479. prev = (VScrollTableRow) offsetIt.next();
  1480. }
  1481. if (r == row) {
  1482. return prev;
  1483. }
  1484. offset--;
  1485. }
  1486. return null;
  1487. }
  1488. protected void reOrderColumn(String columnKey, int newIndex) {
  1489. final int oldIndex = getColIndexByKey(columnKey);
  1490. // Change header order
  1491. tHead.moveCell(oldIndex, newIndex);
  1492. // Change body order
  1493. scrollBody.moveCol(oldIndex, newIndex);
  1494. // Change footer order
  1495. tFoot.moveCell(oldIndex, newIndex);
  1496. /*
  1497. * Build new columnOrder and update it to server Note that columnOrder
  1498. * also contains collapsed columns so we cannot directly build it from
  1499. * cells vector Loop the old columnOrder and append in order to new
  1500. * array unless on moved columnKey. On new index also put the moved key
  1501. * i == index on columnOrder, j == index on newOrder
  1502. */
  1503. final String oldKeyOnNewIndex = visibleColOrder[newIndex];
  1504. if (showRowHeaders) {
  1505. newIndex--; // columnOrder don't have rowHeader
  1506. }
  1507. // add back hidden rows,
  1508. for (int i = 0; i < columnOrder.length; i++) {
  1509. if (columnOrder[i].equals(oldKeyOnNewIndex)) {
  1510. break; // break loop at target
  1511. }
  1512. if (isCollapsedColumn(columnOrder[i])) {
  1513. newIndex++;
  1514. }
  1515. }
  1516. // finally we can build the new columnOrder for server
  1517. final String[] newOrder = new String[columnOrder.length];
  1518. for (int i = 0, j = 0; j < newOrder.length; i++) {
  1519. if (j == newIndex) {
  1520. newOrder[j] = columnKey;
  1521. j++;
  1522. }
  1523. if (i == columnOrder.length) {
  1524. break;
  1525. }
  1526. if (columnOrder[i].equals(columnKey)) {
  1527. continue;
  1528. }
  1529. newOrder[j] = columnOrder[i];
  1530. j++;
  1531. }
  1532. columnOrder = newOrder;
  1533. // also update visibleColumnOrder
  1534. int i = showRowHeaders ? 1 : 0;
  1535. for (int j = 0; j < newOrder.length; j++) {
  1536. final String cid = newOrder[j];
  1537. if (!isCollapsedColumn(cid)) {
  1538. visibleColOrder[i++] = cid;
  1539. }
  1540. }
  1541. client.updateVariable(paintableId, "columnorder", columnOrder, false);
  1542. if (client.hasEventListeners(this, COLUMN_REORDER_EVENT_ID)) {
  1543. client.sendPendingVariableChanges();
  1544. }
  1545. }
  1546. @Override
  1547. protected void onAttach() {
  1548. super.onAttach();
  1549. if (initialContentReceived) {
  1550. sizeInit();
  1551. }
  1552. }
  1553. @Override
  1554. protected void onDetach() {
  1555. rowRequestHandler.cancel();
  1556. super.onDetach();
  1557. // ensure that scrollPosElement will be detached
  1558. if (scrollPositionElement != null) {
  1559. final Element parent = DOM.getParent(scrollPositionElement);
  1560. if (parent != null) {
  1561. DOM.removeChild(parent, scrollPositionElement);
  1562. }
  1563. }
  1564. }
  1565. /**
  1566. * Run only once when component is attached and received its initial
  1567. * content. This function:
  1568. *
  1569. * * Syncs headers and bodys "natural widths and saves the values.
  1570. *
  1571. * * Sets proper width and height
  1572. *
  1573. * * Makes deferred request to get some cache rows
  1574. */
  1575. private void sizeInit() {
  1576. /*
  1577. * We will use browsers table rendering algorithm to find proper column
  1578. * widths. If content and header take less space than available, we will
  1579. * divide extra space relatively to each column which has not width set.
  1580. *
  1581. * Overflow pixels are added to last column.
  1582. */
  1583. Iterator<Widget> headCells = tHead.iterator();
  1584. Iterator<Widget> footCells = tFoot.iterator();
  1585. int i = 0;
  1586. int totalExplicitColumnsWidths = 0;
  1587. int total = 0;
  1588. float expandRatioDivider = 0;
  1589. final int[] widths = new int[tHead.visibleCells.size()];
  1590. tHead.enableBrowserIntelligence();
  1591. tFoot.enableBrowserIntelligence();
  1592. // first loop: collect natural widths
  1593. while (headCells.hasNext()) {
  1594. final HeaderCell hCell = (HeaderCell) headCells.next();
  1595. final FooterCell fCell = (FooterCell) footCells.next();
  1596. int w = hCell.getWidth();
  1597. if (hCell.isDefinedWidth()) {
  1598. // server has defined column width explicitly
  1599. totalExplicitColumnsWidths += w;
  1600. } else {
  1601. if (hCell.getExpandRatio() > 0) {
  1602. expandRatioDivider += hCell.getExpandRatio();
  1603. w = 0;
  1604. } else {
  1605. // get and store greater of header width and column width,
  1606. // and
  1607. // store it as a minimumn natural col width
  1608. int headerWidth = hCell.getNaturalColumnWidth(i);
  1609. int footerWidth = fCell.getNaturalColumnWidth(i);
  1610. w = headerWidth > footerWidth ? headerWidth : footerWidth;
  1611. }
  1612. hCell.setNaturalMinimumColumnWidth(w);
  1613. fCell.setNaturalMinimumColumnWidth(w);
  1614. }
  1615. widths[i] = w;
  1616. total += w;
  1617. i++;
  1618. }
  1619. tHead.disableBrowserIntelligence();
  1620. tFoot.disableBrowserIntelligence();
  1621. boolean willHaveScrollbarz = willHaveScrollbars();
  1622. // fix "natural" width if width not set
  1623. if (width == null || "".equals(width)) {
  1624. int w = total;
  1625. w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1626. if (willHaveScrollbarz) {
  1627. w += Util.getNativeScrollbarSize();
  1628. }
  1629. setContentWidth(w);
  1630. }
  1631. int availW = scrollBody.getAvailableWidth();
  1632. if (BrowserInfo.get().isIE()) {
  1633. // Hey IE, are you really sure about this?
  1634. availW = scrollBody.getAvailableWidth();
  1635. }
  1636. availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1637. if (willHaveScrollbarz) {
  1638. availW -= Util.getNativeScrollbarSize();
  1639. }
  1640. // TODO refactor this code to be the same as in resize timer
  1641. boolean needsReLayout = false;
  1642. if (availW > total) {
  1643. // natural size is smaller than available space
  1644. final int extraSpace = availW - total;
  1645. final int totalWidthR = total - totalExplicitColumnsWidths;
  1646. int checksum = 0;
  1647. needsReLayout = true;
  1648. if (extraSpace == 1) {
  1649. // We cannot divide one single pixel so we give it the first
  1650. // undefined column
  1651. headCells = tHead.iterator();
  1652. i = 0;
  1653. checksum = availW;
  1654. while (headCells.hasNext()) {
  1655. HeaderCell hc = (HeaderCell) headCells.next();
  1656. if (!hc.isDefinedWidth()) {
  1657. widths[i]++;
  1658. break;
  1659. }
  1660. i++;
  1661. }
  1662. } else if (expandRatioDivider > 0) {
  1663. // visible columns have some active expand ratios, excess
  1664. // space is divided according to them
  1665. headCells = tHead.iterator();
  1666. i = 0;
  1667. while (headCells.hasNext()) {
  1668. HeaderCell hCell = (HeaderCell) headCells.next();
  1669. if (hCell.getExpandRatio() > 0) {
  1670. int w = widths[i];
  1671. final int newSpace = Math.round((extraSpace * (hCell
  1672. .getExpandRatio() / expandRatioDivider)));
  1673. w += newSpace;
  1674. widths[i] = w;
  1675. }
  1676. checksum += widths[i];
  1677. i++;
  1678. }
  1679. } else if (totalWidthR > 0) {
  1680. // no expand ratios defined, we will share extra space
  1681. // relatively to "natural widths" among those without
  1682. // explicit width
  1683. headCells = tHead.iterator();
  1684. i = 0;
  1685. while (headCells.hasNext()) {
  1686. HeaderCell hCell = (HeaderCell) headCells.next();
  1687. if (!hCell.isDefinedWidth()) {
  1688. int w = widths[i];
  1689. final int newSpace = Math.round((float) extraSpace
  1690. * (float) w / totalWidthR);
  1691. w += newSpace;
  1692. widths[i] = w;
  1693. }
  1694. checksum += widths[i];
  1695. i++;
  1696. }
  1697. }
  1698. if (extraSpace > 0 && checksum != availW) {
  1699. /*
  1700. * There might be in some cases a rounding error of 1px when
  1701. * extra space is divided so if there is one then we give the
  1702. * first undefined column 1 more pixel
  1703. */
  1704. headCells = tHead.iterator();
  1705. i = 0;
  1706. while (headCells.hasNext()) {
  1707. HeaderCell hc = (HeaderCell) headCells.next();
  1708. if (!hc.isDefinedWidth()) {
  1709. widths[i] += availW - checksum;
  1710. break;
  1711. }
  1712. i++;
  1713. }
  1714. }
  1715. } else {
  1716. // bodys size will be more than available and scrollbar will appear
  1717. }
  1718. // last loop: set possibly modified values or reset if new tBody
  1719. i = 0;
  1720. headCells = tHead.iterator();
  1721. while (headCells.hasNext()) {
  1722. final HeaderCell hCell = (HeaderCell) headCells.next();
  1723. if (isNewBody || hCell.getWidth() == -1) {
  1724. final int w = widths[i];
  1725. setColWidth(i, w, false);
  1726. }
  1727. i++;
  1728. }
  1729. initializedAndAttached = true;
  1730. if (needsReLayout) {
  1731. scrollBody.reLayoutComponents();
  1732. }
  1733. updatePageLength();
  1734. /*
  1735. * Fix "natural" height if height is not set. This must be after width
  1736. * fixing so the components' widths have been adjusted.
  1737. */
  1738. if (height == null || "".equals(height)) {
  1739. /*
  1740. * We must force an update of the row height as this point as it
  1741. * might have been (incorrectly) calculated earlier
  1742. */
  1743. int bodyHeight;
  1744. if (pageLength == totalRows) {
  1745. /*
  1746. * A hack to support variable height rows when paging is off.
  1747. * Generally this is not supported by scrolltable. We want to
  1748. * show all rows so the bodyHeight should be equal to the table
  1749. * height.
  1750. */
  1751. // int bodyHeight = scrollBody.getOffsetHeight();
  1752. bodyHeight = scrollBody.getRequiredHeight();
  1753. } else {
  1754. bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
  1755. * pageLength);
  1756. }
  1757. boolean needsSpaceForHorizontalSrollbar = (total > availW);
  1758. if (needsSpaceForHorizontalSrollbar) {
  1759. bodyHeight += Util.getNativeScrollbarSize();
  1760. }
  1761. scrollBodyPanel.setHeight(bodyHeight + "px");
  1762. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  1763. }
  1764. isNewBody = false;
  1765. if (firstvisible > 0) {
  1766. // Deferred due some Firefox oddities. IE & Safari could survive
  1767. // without
  1768. Scheduler.get().scheduleDeferred(new Command() {
  1769. public void execute() {
  1770. scrollBodyPanel
  1771. .setScrollPosition(measureRowHeightOffset(firstvisible));
  1772. firstRowInViewPort = firstvisible;
  1773. }
  1774. });
  1775. }
  1776. if (enabled) {
  1777. // Do we need cache rows
  1778. if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
  1779. + pageLength + (int) cache_react_rate * pageLength) {
  1780. if (totalRows - 1 > scrollBody.getLastRendered()) {
  1781. // fetch cache rows
  1782. int firstInNewSet = scrollBody.getLastRendered() + 1;
  1783. rowRequestHandler.setReqFirstRow(firstInNewSet);
  1784. int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
  1785. * pageLength);
  1786. if (lastInNewSet > totalRows - 1) {
  1787. lastInNewSet = totalRows - 1;
  1788. }
  1789. rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
  1790. + 1);
  1791. rowRequestHandler.deferRowFetch(1);
  1792. }
  1793. }
  1794. }
  1795. /*
  1796. * Ensures the column alignments are correct at initial loading. <br/>
  1797. * (child components widths are correct)
  1798. */
  1799. scrollBody.reLayoutComponents();
  1800. Scheduler.get().scheduleDeferred(new Command() {
  1801. public void execute() {
  1802. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  1803. }
  1804. });
  1805. }
  1806. /**
  1807. * Note, this method is not official api although declared as protected.
  1808. * Extend at you own risk.
  1809. *
  1810. * @return true if content area will have scrollbars visible.
  1811. */
  1812. protected boolean willHaveScrollbars() {
  1813. if (!(height != null && !height.equals(""))) {
  1814. if (pageLength < totalRows) {
  1815. return true;
  1816. }
  1817. } else {
  1818. int fakeheight = (int) Math.round(scrollBody.getRowHeight()
  1819. * totalRows);
  1820. int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
  1821. "clientHeight");
  1822. if (fakeheight > availableHeight) {
  1823. return true;
  1824. }
  1825. }
  1826. return false;
  1827. }
  1828. private void announceScrollPosition() {
  1829. if (scrollPositionElement == null) {
  1830. scrollPositionElement = DOM.createDiv();
  1831. scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
  1832. scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
  1833. scrollPositionElement.getStyle().setDisplay(Display.NONE);
  1834. getElement().appendChild(scrollPositionElement);
  1835. }
  1836. Style style = scrollPositionElement.getStyle();
  1837. style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
  1838. style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
  1839. // indexes go from 1-totalRows, as rowheaders in index-mode indicate
  1840. int last = (firstRowInViewPort + pageLength);
  1841. if (last > totalRows) {
  1842. last = totalRows;
  1843. }
  1844. scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
  1845. + " &ndash; " + (last) + "..." + "</span>");
  1846. style.setDisplay(Display.BLOCK);
  1847. }
  1848. private void hideScrollPositionAnnotation() {
  1849. if (scrollPositionElement != null) {
  1850. DOM.setStyleAttribute(scrollPositionElement, "display", "none");
  1851. }
  1852. }
  1853. private boolean isScrollPositionVisible() {
  1854. return scrollPositionElement != null
  1855. && !scrollPositionElement.getStyle().getDisplay()
  1856. .equals(Display.NONE.toString());
  1857. }
  1858. private class RowRequestHandler extends Timer {
  1859. private int reqFirstRow = 0;
  1860. private int reqRows = 0;
  1861. private boolean isRunning = false;
  1862. public void deferRowFetch() {
  1863. deferRowFetch(250);
  1864. }
  1865. public boolean isRunning() {
  1866. return isRunning;
  1867. }
  1868. public void deferRowFetch(int msec) {
  1869. isRunning = true;
  1870. if (reqRows > 0 && reqFirstRow < totalRows) {
  1871. schedule(msec);
  1872. // tell scroll position to user if currently "visible" rows are
  1873. // not rendered
  1874. if (totalRows > pageLength
  1875. && ((firstRowInViewPort + pageLength > scrollBody
  1876. .getLastRendered()) || (firstRowInViewPort < scrollBody
  1877. .getFirstRendered()))) {
  1878. announceScrollPosition();
  1879. } else {
  1880. hideScrollPositionAnnotation();
  1881. }
  1882. }
  1883. }
  1884. public void setReqFirstRow(int reqFirstRow) {
  1885. if (reqFirstRow < 0) {
  1886. reqFirstRow = 0;
  1887. } else if (reqFirstRow >= totalRows) {
  1888. reqFirstRow = totalRows - 1;
  1889. }
  1890. this.reqFirstRow = reqFirstRow;
  1891. }
  1892. public void setReqRows(int reqRows) {
  1893. this.reqRows = reqRows;
  1894. }
  1895. @Override
  1896. public void run() {
  1897. if (client.hasActiveRequest() || navKeyDown) {
  1898. // if client connection is busy, don't bother loading it more
  1899. VConsole.log("Postponed rowfetch");
  1900. schedule(250);
  1901. } else {
  1902. int firstToBeRendered = scrollBody.firstRendered;
  1903. if (reqFirstRow < firstToBeRendered) {
  1904. firstToBeRendered = reqFirstRow;
  1905. } else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
  1906. firstToBeRendered = firstRowInViewPort
  1907. - (int) (cache_rate * pageLength);
  1908. if (firstToBeRendered < 0) {
  1909. firstToBeRendered = 0;
  1910. }
  1911. }
  1912. int lastToBeRendered = scrollBody.lastRendered;
  1913. if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
  1914. lastToBeRendered = reqFirstRow + reqRows - 1;
  1915. } else if (firstRowInViewPort + pageLength + pageLength
  1916. * cache_rate < lastToBeRendered) {
  1917. lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
  1918. if (lastToBeRendered >= totalRows) {
  1919. lastToBeRendered = totalRows - 1;
  1920. }
  1921. // due Safari 3.1 bug (see #2607), verify reqrows, original
  1922. // problem unknown, but this should catch the issue
  1923. if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
  1924. reqRows = lastToBeRendered - reqFirstRow;
  1925. }
  1926. }
  1927. client.updateVariable(paintableId, "firstToBeRendered",
  1928. firstToBeRendered, false);
  1929. client.updateVariable(paintableId, "lastToBeRendered",
  1930. lastToBeRendered, false);
  1931. // remember which firstvisible we requested, in case the server
  1932. // has
  1933. // a differing opinion
  1934. lastRequestedFirstvisible = firstRowInViewPort;
  1935. client.updateVariable(paintableId, "firstvisible",
  1936. firstRowInViewPort, false);
  1937. client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
  1938. false);
  1939. client.updateVariable(paintableId, "reqrows", reqRows, true);
  1940. if (selectionChanged) {
  1941. unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
  1942. selectedRowKeys);
  1943. }
  1944. isRunning = false;
  1945. }
  1946. }
  1947. public int getReqFirstRow() {
  1948. return reqFirstRow;
  1949. }
  1950. /**
  1951. * Sends request to refresh content at this position.
  1952. */
  1953. public void refreshContent() {
  1954. isRunning = true;
  1955. int first = (int) (firstRowInViewPort - pageLength * cache_rate);
  1956. int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
  1957. if (first < 0) {
  1958. reqRows = reqRows + first;
  1959. first = 0;
  1960. }
  1961. setReqFirstRow(first);
  1962. setReqRows(reqRows);
  1963. run();
  1964. }
  1965. }
  1966. public class HeaderCell extends Widget {
  1967. Element td = DOM.createTD();
  1968. Element captionContainer = DOM.createDiv();
  1969. Element sortIndicator = DOM.createDiv();
  1970. Element colResizeWidget = DOM.createDiv();
  1971. Element floatingCopyOfHeaderCell;
  1972. private boolean sortable = false;
  1973. private final String cid;
  1974. private boolean dragging;
  1975. private int dragStartX;
  1976. private int colIndex;
  1977. private int originalWidth;
  1978. private boolean isResizing;
  1979. private int headerX;
  1980. private boolean moved;
  1981. private int closestSlot;
  1982. private int width = -1;
  1983. private int naturalWidth = -1;
  1984. private char align = ALIGN_LEFT;
  1985. boolean definedWidth = false;
  1986. private float expandRatio = 0;
  1987. private boolean sorted;
  1988. public void setSortable(boolean b) {
  1989. sortable = b;
  1990. }
  1991. /**
  1992. * Makes room for the sorting indicator in case the column that the
  1993. * header cell belongs to is sorted. This is done by resizing the width
  1994. * of the caption container element by the correct amount
  1995. */
  1996. public void resizeCaptionContainer(int rightSpacing) {
  1997. if (td.getClassName().contains("-asc")
  1998. || td.getClassName().contains("-desc")) {
  1999. /*
  2000. * Room for the sort indicator is made by subtracting the styled
  2001. * margin and width of the resizer from the width of the caption
  2002. * container.
  2003. */
  2004. int captionContainerWidth = width
  2005. - sortIndicator.getOffsetWidth()
  2006. - colResizeWidget.getOffsetWidth() - rightSpacing;
  2007. captionContainer.getStyle().setPropertyPx("width",
  2008. captionContainerWidth);
  2009. } else {
  2010. /*
  2011. * Set the caption container element as wide as possible when
  2012. * the sorting indicator is not visible.
  2013. */
  2014. captionContainer.getStyle().setPropertyPx("width",
  2015. width - rightSpacing);
  2016. }
  2017. // Apply/Remove spacing if defined
  2018. if (rightSpacing > 0) {
  2019. colResizeWidget.getStyle().setMarginLeft(rightSpacing, Unit.PX);
  2020. } else {
  2021. colResizeWidget.getStyle().clearMarginLeft();
  2022. }
  2023. }
  2024. public void setNaturalMinimumColumnWidth(int w) {
  2025. naturalWidth = w;
  2026. }
  2027. public HeaderCell(String colId, String headerText) {
  2028. cid = colId;
  2029. DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
  2030. + "-resizer");
  2031. setText(headerText);
  2032. DOM.appendChild(td, colResizeWidget);
  2033. DOM.setElementProperty(sortIndicator, "className", CLASSNAME
  2034. + "-sort-indicator");
  2035. DOM.appendChild(td, sortIndicator);
  2036. DOM.setElementProperty(captionContainer, "className", CLASSNAME
  2037. + "-caption-container");
  2038. // ensure no clipping initially (problem on column additions)
  2039. DOM.setStyleAttribute(captionContainer, "overflow", "visible");
  2040. DOM.appendChild(td, captionContainer);
  2041. DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.TOUCHEVENTS);
  2042. setElement(td);
  2043. setAlign(ALIGN_LEFT);
  2044. }
  2045. public void disableAutoWidthCalculation() {
  2046. definedWidth = true;
  2047. expandRatio = 0;
  2048. }
  2049. public void setWidth(int w, boolean ensureDefinedWidth) {
  2050. if (ensureDefinedWidth) {
  2051. definedWidth = true;
  2052. // on column resize expand ratio becomes zero
  2053. expandRatio = 0;
  2054. }
  2055. if (width == -1) {
  2056. // go to default mode, clip content if necessary
  2057. DOM.setStyleAttribute(captionContainer, "overflow", "");
  2058. }
  2059. width = w;
  2060. if (w == -1) {
  2061. DOM.setStyleAttribute(captionContainer, "width", "");
  2062. setWidth("");
  2063. } else {
  2064. tHead.resizeCaptionContainer(this);
  2065. /*
  2066. * if we already have tBody, set the header width properly, if
  2067. * not defer it. IE will fail with complex float in table header
  2068. * unless TD width is not explicitly set.
  2069. */
  2070. if (scrollBody != null) {
  2071. int tdWidth = width + scrollBody.getCellExtraWidth();
  2072. setWidth(tdWidth + "px");
  2073. } else {
  2074. Scheduler.get().scheduleDeferred(new Command() {
  2075. public void execute() {
  2076. int tdWidth = width
  2077. + scrollBody.getCellExtraWidth();
  2078. setWidth(tdWidth + "px");
  2079. }
  2080. });
  2081. }
  2082. }
  2083. }
  2084. public void setUndefinedWidth() {
  2085. definedWidth = false;
  2086. setWidth(-1, false);
  2087. }
  2088. /**
  2089. * Detects if width is fixed by developer on server side or resized to
  2090. * current width by user.
  2091. *
  2092. * @return true if defined, false if "natural" width
  2093. */
  2094. public boolean isDefinedWidth() {
  2095. return definedWidth && width >= 0;
  2096. }
  2097. public int getWidth() {
  2098. return width;
  2099. }
  2100. public void setText(String headerText) {
  2101. DOM.setInnerHTML(captionContainer, headerText);
  2102. }
  2103. public String getColKey() {
  2104. return cid;
  2105. }
  2106. private void setSorted(boolean sorted) {
  2107. this.sorted = sorted;
  2108. if (sorted) {
  2109. if (sortAscending) {
  2110. this.setStyleName(CLASSNAME + "-header-cell-asc");
  2111. } else {
  2112. this.setStyleName(CLASSNAME + "-header-cell-desc");
  2113. }
  2114. } else {
  2115. this.setStyleName(CLASSNAME + "-header-cell");
  2116. }
  2117. }
  2118. /**
  2119. * Handle column reordering.
  2120. */
  2121. @Override
  2122. public void onBrowserEvent(Event event) {
  2123. if (enabled && event != null) {
  2124. if (isResizing
  2125. || event.getEventTarget().cast() == colResizeWidget) {
  2126. if (dragging
  2127. && (event.getTypeInt() == Event.ONMOUSEUP || event
  2128. .getTypeInt() == Event.ONTOUCHEND)) {
  2129. // Handle releasing column header on spacer #5318
  2130. handleCaptionEvent(event);
  2131. } else {
  2132. onResizeEvent(event);
  2133. }
  2134. } else {
  2135. /*
  2136. * Ensure focus before handling caption event. Otherwise
  2137. * variables changed from caption event may be before
  2138. * variables from other components that fire variables when
  2139. * they lose focus.
  2140. */
  2141. if (event.getTypeInt() == Event.ONMOUSEDOWN
  2142. || event.getTypeInt() == Event.ONTOUCHSTART) {
  2143. scrollBodyPanel.setFocus(true);
  2144. }
  2145. handleCaptionEvent(event);
  2146. event.stopPropagation();
  2147. event.preventDefault();
  2148. }
  2149. }
  2150. }
  2151. private void createFloatingCopy() {
  2152. floatingCopyOfHeaderCell = DOM.createDiv();
  2153. DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
  2154. floatingCopyOfHeaderCell = DOM
  2155. .getChild(floatingCopyOfHeaderCell, 2);
  2156. DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
  2157. CLASSNAME + "-header-drag");
  2158. // otherwise might wrap or be cut if narrow column
  2159. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "width", "auto");
  2160. updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
  2161. DOM.getAbsoluteTop(td));
  2162. DOM.appendChild(RootPanel.get().getElement(),
  2163. floatingCopyOfHeaderCell);
  2164. }
  2165. private void updateFloatingCopysPosition(int x, int y) {
  2166. x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
  2167. "offsetWidth") / 2;
  2168. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
  2169. if (y > 0) {
  2170. DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
  2171. + "px");
  2172. }
  2173. }
  2174. private void hideFloatingCopy() {
  2175. DOM.removeChild(RootPanel.get().getElement(),
  2176. floatingCopyOfHeaderCell);
  2177. floatingCopyOfHeaderCell = null;
  2178. }
  2179. /**
  2180. * Fires a header click event after the user has clicked a column header
  2181. * cell
  2182. *
  2183. * @param event
  2184. * The click event
  2185. */
  2186. private void fireHeaderClickedEvent(Event event) {
  2187. if (client.hasEventListeners(VScrollTable.this,
  2188. HEADER_CLICK_EVENT_ID)) {
  2189. MouseEventDetails details = new MouseEventDetails(event);
  2190. client.updateVariable(paintableId, "headerClickEvent",
  2191. details.toString(), false);
  2192. client.updateVariable(paintableId, "headerClickCID", cid, true);
  2193. }
  2194. }
  2195. protected void handleCaptionEvent(Event event) {
  2196. switch (DOM.eventGetType(event)) {
  2197. case Event.ONTOUCHSTART:
  2198. case Event.ONMOUSEDOWN:
  2199. if (columnReordering) {
  2200. if (event.getTypeInt() == Event.ONTOUCHSTART) {
  2201. /*
  2202. * prevent using this event in e.g. scrolling
  2203. */
  2204. event.stopPropagation();
  2205. }
  2206. dragging = true;
  2207. moved = false;
  2208. colIndex = getColIndexByKey(cid);
  2209. DOM.setCapture(getElement());
  2210. headerX = tHead.getAbsoluteLeft();
  2211. event.preventDefault(); // prevent selecting text &&
  2212. // generated touch events
  2213. }
  2214. break;
  2215. case Event.ONMOUSEUP:
  2216. case Event.ONTOUCHEND:
  2217. case Event.ONTOUCHCANCEL:
  2218. if (columnReordering) {
  2219. dragging = false;
  2220. DOM.releaseCapture(getElement());
  2221. if (moved) {
  2222. hideFloatingCopy();
  2223. tHead.removeSlotFocus();
  2224. if (closestSlot != colIndex
  2225. && closestSlot != (colIndex + 1)) {
  2226. if (closestSlot > colIndex) {
  2227. reOrderColumn(cid, closestSlot - 1);
  2228. } else {
  2229. reOrderColumn(cid, closestSlot);
  2230. }
  2231. }
  2232. }
  2233. if (Util.isTouchEvent(event)) {
  2234. /*
  2235. * Prevent using in e.g. scrolling and prevent generated
  2236. * events.
  2237. */
  2238. event.preventDefault();
  2239. event.stopPropagation();
  2240. }
  2241. }
  2242. if (!moved) {
  2243. // mouse event was a click to header -> sort column
  2244. if (sortable) {
  2245. if (sortColumn.equals(cid)) {
  2246. // just toggle order
  2247. client.updateVariable(paintableId, "sortascending",
  2248. !sortAscending, false);
  2249. } else {
  2250. // set table sorted by this column
  2251. client.updateVariable(paintableId, "sortcolumn",
  2252. cid, false);
  2253. }
  2254. // get also cache columns at the same request
  2255. scrollBodyPanel.setScrollPosition(0);
  2256. firstvisible = 0;
  2257. rowRequestHandler.setReqFirstRow(0);
  2258. rowRequestHandler.setReqRows((int) (2 * pageLength
  2259. * cache_rate + pageLength));
  2260. rowRequestHandler.deferRowFetch(); // some validation +
  2261. // defer 250ms
  2262. rowRequestHandler.cancel(); // instead of waiting
  2263. rowRequestHandler.run(); // run immediately
  2264. }
  2265. fireHeaderClickedEvent(event);
  2266. if (Util.isTouchEvent(event)) {
  2267. /*
  2268. * Prevent using in e.g. scrolling and prevent generated
  2269. * events.
  2270. */
  2271. event.preventDefault();
  2272. event.stopPropagation();
  2273. }
  2274. break;
  2275. }
  2276. break;
  2277. case Event.ONTOUCHMOVE:
  2278. case Event.ONMOUSEMOVE:
  2279. if (dragging) {
  2280. if (event.getTypeInt() == Event.ONTOUCHMOVE) {
  2281. /*
  2282. * prevent using this event in e.g. scrolling
  2283. */
  2284. event.stopPropagation();
  2285. }
  2286. if (!moved) {
  2287. createFloatingCopy();
  2288. moved = true;
  2289. }
  2290. final int clientX = Util.getTouchOrMouseClientX(event);
  2291. final int x = clientX + tHead.hTableWrapper.getScrollLeft();
  2292. int slotX = headerX;
  2293. closestSlot = colIndex;
  2294. int closestDistance = -1;
  2295. int start = 0;
  2296. if (showRowHeaders) {
  2297. start++;
  2298. }
  2299. final int visibleCellCount = tHead.getVisibleCellCount();
  2300. for (int i = start; i <= visibleCellCount; i++) {
  2301. if (i > 0) {
  2302. final String colKey = getColKeyByIndex(i - 1);
  2303. slotX += getColWidth(colKey);
  2304. }
  2305. final int dist = Math.abs(x - slotX);
  2306. if (closestDistance == -1 || dist < closestDistance) {
  2307. closestDistance = dist;
  2308. closestSlot = i;
  2309. }
  2310. }
  2311. tHead.focusSlot(closestSlot);
  2312. updateFloatingCopysPosition(clientX, -1);
  2313. }
  2314. break;
  2315. default:
  2316. break;
  2317. }
  2318. }
  2319. private void onResizeEvent(Event event) {
  2320. switch (DOM.eventGetType(event)) {
  2321. case Event.ONMOUSEDOWN:
  2322. isResizing = true;
  2323. DOM.setCapture(getElement());
  2324. dragStartX = DOM.eventGetClientX(event);
  2325. colIndex = getColIndexByKey(cid);
  2326. originalWidth = getWidth();
  2327. DOM.eventPreventDefault(event);
  2328. break;
  2329. case Event.ONMOUSEUP:
  2330. isResizing = false;
  2331. DOM.releaseCapture(getElement());
  2332. tHead.disableAutoColumnWidthCalculation(this);
  2333. // Ensure last header cell is taking into account possible
  2334. // column selector
  2335. HeaderCell lastCell = tHead.getHeaderCell(tHead
  2336. .getVisibleCellCount() - 1);
  2337. tHead.resizeCaptionContainer(lastCell);
  2338. triggerLazyColumnAdjustment(true);
  2339. fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
  2340. break;
  2341. case Event.ONMOUSEMOVE:
  2342. if (isResizing) {
  2343. final int deltaX = DOM.eventGetClientX(event) - dragStartX;
  2344. if (deltaX == 0) {
  2345. return;
  2346. }
  2347. tHead.disableAutoColumnWidthCalculation(this);
  2348. int newWidth = originalWidth + deltaX;
  2349. if (newWidth < getMinWidth()) {
  2350. newWidth = getMinWidth();
  2351. }
  2352. setColWidth(colIndex, newWidth, true);
  2353. triggerLazyColumnAdjustment(false);
  2354. forceRealignColumnHeaders();
  2355. }
  2356. break;
  2357. default:
  2358. break;
  2359. }
  2360. }
  2361. public int getMinWidth() {
  2362. int cellExtraWidth = 0;
  2363. if (scrollBody != null) {
  2364. cellExtraWidth += scrollBody.getCellExtraWidth();
  2365. }
  2366. return cellExtraWidth + sortIndicator.getOffsetWidth();
  2367. }
  2368. public String getCaption() {
  2369. return DOM.getInnerText(captionContainer);
  2370. }
  2371. public boolean isEnabled() {
  2372. return getParent() != null;
  2373. }
  2374. public void setAlign(char c) {
  2375. final String ALIGN_PREFIX = CLASSNAME + "-caption-container-align-";
  2376. if (align != c) {
  2377. captionContainer.removeClassName(ALIGN_PREFIX + "center");
  2378. captionContainer.removeClassName(ALIGN_PREFIX + "right");
  2379. captionContainer.removeClassName(ALIGN_PREFIX + "left");
  2380. switch (c) {
  2381. case ALIGN_CENTER:
  2382. captionContainer.addClassName(ALIGN_PREFIX + "center");
  2383. break;
  2384. case ALIGN_RIGHT:
  2385. captionContainer.addClassName(ALIGN_PREFIX + "right");
  2386. break;
  2387. default:
  2388. captionContainer.addClassName(ALIGN_PREFIX + "left");
  2389. break;
  2390. }
  2391. }
  2392. align = c;
  2393. }
  2394. public char getAlign() {
  2395. return align;
  2396. }
  2397. /**
  2398. * Detects the natural minimum width for the column of this header cell.
  2399. * If column is resized by user or the width is defined by server the
  2400. * actual width is returned. Else the natural min width is returned.
  2401. *
  2402. * @param columnIndex
  2403. * column index hint, if -1 (unknown) it will be detected
  2404. *
  2405. * @return
  2406. */
  2407. public int getNaturalColumnWidth(int columnIndex) {
  2408. if (isDefinedWidth()) {
  2409. return width;
  2410. } else {
  2411. if (naturalWidth < 0) {
  2412. // This is recently revealed column. Try to detect a proper
  2413. // value (greater of header and data
  2414. // cols)
  2415. int hw = captionContainer.getOffsetWidth()
  2416. + scrollBody.getCellExtraWidth();
  2417. if (BrowserInfo.get().isGecko()) {
  2418. hw += sortIndicator.getOffsetWidth();
  2419. }
  2420. if (columnIndex < 0) {
  2421. columnIndex = 0;
  2422. for (Iterator<Widget> it = tHead.iterator(); it
  2423. .hasNext(); columnIndex++) {
  2424. if (it.next() == this) {
  2425. break;
  2426. }
  2427. }
  2428. }
  2429. final int cw = scrollBody.getColWidth(columnIndex);
  2430. naturalWidth = (hw > cw ? hw : cw);
  2431. }
  2432. return naturalWidth;
  2433. }
  2434. }
  2435. public void setExpandRatio(float floatAttribute) {
  2436. if (floatAttribute != expandRatio) {
  2437. triggerLazyColumnAdjustment(false);
  2438. }
  2439. expandRatio = floatAttribute;
  2440. }
  2441. public float getExpandRatio() {
  2442. return expandRatio;
  2443. }
  2444. public boolean isSorted() {
  2445. return sorted;
  2446. }
  2447. }
  2448. /**
  2449. * HeaderCell that is header cell for row headers.
  2450. *
  2451. * Reordering disabled and clicking on it resets sorting.
  2452. */
  2453. public class RowHeadersHeaderCell extends HeaderCell {
  2454. RowHeadersHeaderCell() {
  2455. super(ROW_HEADER_COLUMN_KEY, "");
  2456. this.setStyleName(CLASSNAME + "-header-cell-rowheader");
  2457. }
  2458. @Override
  2459. protected void handleCaptionEvent(Event event) {
  2460. // NOP: RowHeaders cannot be reordered
  2461. // TODO It'd be nice to reset sorting here
  2462. }
  2463. }
  2464. public class TableHead extends Panel implements ActionOwner {
  2465. private static final int WRAPPER_WIDTH = 900000;
  2466. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  2467. HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
  2468. Element div = DOM.createDiv();
  2469. Element hTableWrapper = DOM.createDiv();
  2470. Element hTableContainer = DOM.createDiv();
  2471. Element table = DOM.createTable();
  2472. Element headerTableBody = DOM.createTBody();
  2473. Element tr = DOM.createTR();
  2474. private final Element columnSelector = DOM.createDiv();
  2475. private int focusedSlot = -1;
  2476. public TableHead() {
  2477. if (BrowserInfo.get().isIE()) {
  2478. table.setPropertyInt("cellSpacing", 0);
  2479. }
  2480. DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
  2481. DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
  2482. + "-header");
  2483. // TODO move styles to CSS
  2484. DOM.setElementProperty(columnSelector, "className", CLASSNAME
  2485. + "-column-selector");
  2486. DOM.setStyleAttribute(columnSelector, "display", "none");
  2487. DOM.appendChild(table, headerTableBody);
  2488. DOM.appendChild(headerTableBody, tr);
  2489. DOM.appendChild(hTableContainer, table);
  2490. DOM.appendChild(hTableWrapper, hTableContainer);
  2491. DOM.appendChild(div, hTableWrapper);
  2492. DOM.appendChild(div, columnSelector);
  2493. setElement(div);
  2494. setStyleName(CLASSNAME + "-header-wrap");
  2495. DOM.sinkEvents(columnSelector, Event.ONCLICK);
  2496. availableCells.put(ROW_HEADER_COLUMN_KEY,
  2497. new RowHeadersHeaderCell());
  2498. }
  2499. public void resizeCaptionContainer(HeaderCell cell) {
  2500. HeaderCell lastcell = getHeaderCell(visibleCells.size() - 1);
  2501. // Measure column widths
  2502. int columnTotalWidth = 0;
  2503. for (Widget w : visibleCells) {
  2504. columnTotalWidth += w.getOffsetWidth();
  2505. }
  2506. if (cell == lastcell
  2507. && columnSelector.getOffsetWidth() > 0
  2508. && columnTotalWidth >= div.getOffsetWidth()
  2509. - columnSelector.getOffsetWidth()
  2510. && !hasVerticalScrollbar()) {
  2511. // Ensure column caption is visible when placed under the column
  2512. // selector widget by shifting and resizing the caption.
  2513. int offset = 0;
  2514. int diff = div.getOffsetWidth() - columnTotalWidth;
  2515. if (diff < columnSelector.getOffsetWidth() && diff > 0) {
  2516. // If the difference is less than the column selectors width
  2517. // then just offset by the
  2518. // difference
  2519. offset = columnSelector.getOffsetWidth() - diff;
  2520. } else {
  2521. // Else offset by the whole column selector
  2522. offset = columnSelector.getOffsetWidth();
  2523. }
  2524. lastcell.resizeCaptionContainer(offset);
  2525. } else {
  2526. cell.resizeCaptionContainer(0);
  2527. }
  2528. }
  2529. @Override
  2530. public void clear() {
  2531. for (String cid : availableCells.keySet()) {
  2532. removeCell(cid);
  2533. }
  2534. availableCells.clear();
  2535. availableCells.put(ROW_HEADER_COLUMN_KEY,
  2536. new RowHeadersHeaderCell());
  2537. }
  2538. public void updateCellsFromUIDL(UIDL uidl) {
  2539. Iterator<?> it = uidl.getChildIterator();
  2540. HashSet<String> updated = new HashSet<String>();
  2541. boolean refreshContentWidths = false;
  2542. while (it.hasNext()) {
  2543. final UIDL col = (UIDL) it.next();
  2544. final String cid = col.getStringAttribute("cid");
  2545. updated.add(cid);
  2546. String caption = buildCaptionHtmlSnippet(col);
  2547. HeaderCell c = getHeaderCell(cid);
  2548. if (c == null) {
  2549. c = new HeaderCell(cid, caption);
  2550. availableCells.put(cid, c);
  2551. if (initializedAndAttached) {
  2552. // we will need a column width recalculation
  2553. initializedAndAttached = false;
  2554. initialContentReceived = false;
  2555. isNewBody = true;
  2556. }
  2557. } else {
  2558. c.setText(caption);
  2559. }
  2560. if (col.hasAttribute("sortable")) {
  2561. c.setSortable(true);
  2562. if (cid.equals(sortColumn)) {
  2563. c.setSorted(true);
  2564. } else {
  2565. c.setSorted(false);
  2566. }
  2567. } else {
  2568. c.setSortable(false);
  2569. }
  2570. if (col.hasAttribute("align")) {
  2571. c.setAlign(col.getStringAttribute("align").charAt(0));
  2572. } else {
  2573. c.setAlign(ALIGN_LEFT);
  2574. }
  2575. if (col.hasAttribute("width")) {
  2576. final String widthStr = col.getStringAttribute("width");
  2577. // Make sure to accomodate for the sort indicator if
  2578. // necessary.
  2579. int width = Integer.parseInt(widthStr);
  2580. if (width < c.getMinWidth()) {
  2581. width = c.getMinWidth();
  2582. }
  2583. if (width != c.getWidth() && scrollBody != null) {
  2584. // Do a more thorough update if a column is resized from
  2585. // the server *after* the header has been properly
  2586. // initialized
  2587. final int colIx = getColIndexByKey(c.cid);
  2588. final int newWidth = width;
  2589. Scheduler.get().scheduleDeferred(
  2590. new ScheduledCommand() {
  2591. public void execute() {
  2592. setColWidth(colIx, newWidth, true);
  2593. }
  2594. });
  2595. refreshContentWidths = true;
  2596. } else {
  2597. c.setWidth(width, true);
  2598. }
  2599. } else if (recalcWidths) {
  2600. c.setUndefinedWidth();
  2601. }
  2602. if (col.hasAttribute("er")) {
  2603. c.setExpandRatio(col.getFloatAttribute("er"));
  2604. }
  2605. if (col.hasAttribute("collapsed")) {
  2606. // ensure header is properly removed from parent (case when
  2607. // collapsing happens via servers side api)
  2608. if (c.isAttached()) {
  2609. c.removeFromParent();
  2610. headerChangedDuringUpdate = true;
  2611. }
  2612. }
  2613. }
  2614. if (refreshContentWidths) {
  2615. // Recalculate the column sizings if any column has changed
  2616. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  2617. public void execute() {
  2618. triggerLazyColumnAdjustment(true);
  2619. }
  2620. });
  2621. }
  2622. // check for orphaned header cells
  2623. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  2624. .hasNext();) {
  2625. String cid = cit.next();
  2626. if (!updated.contains(cid)) {
  2627. removeCell(cid);
  2628. cit.remove();
  2629. // we will need a column width recalculation, since columns
  2630. // with expand ratios should expand to fill the void.
  2631. initializedAndAttached = false;
  2632. initialContentReceived = false;
  2633. isNewBody = true;
  2634. }
  2635. }
  2636. }
  2637. public void enableColumn(String cid, int index) {
  2638. final HeaderCell c = getHeaderCell(cid);
  2639. if (!c.isEnabled() || getHeaderCell(index) != c) {
  2640. setHeaderCell(index, c);
  2641. if (initializedAndAttached) {
  2642. headerChangedDuringUpdate = true;
  2643. }
  2644. }
  2645. }
  2646. public int getVisibleCellCount() {
  2647. return visibleCells.size();
  2648. }
  2649. public void setHorizontalScrollPosition(int scrollLeft) {
  2650. hTableWrapper.setScrollLeft(scrollLeft);
  2651. }
  2652. public void setColumnCollapsingAllowed(boolean cc) {
  2653. if (cc) {
  2654. columnSelector.getStyle().setDisplay(Display.BLOCK);
  2655. } else {
  2656. columnSelector.getStyle().setDisplay(Display.NONE);
  2657. }
  2658. }
  2659. public void disableBrowserIntelligence() {
  2660. hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
  2661. }
  2662. public void enableBrowserIntelligence() {
  2663. hTableContainer.getStyle().clearWidth();
  2664. }
  2665. public void setHeaderCell(int index, HeaderCell cell) {
  2666. if (cell.isEnabled()) {
  2667. // we're moving the cell
  2668. DOM.removeChild(tr, cell.getElement());
  2669. orphan(cell);
  2670. visibleCells.remove(cell);
  2671. }
  2672. if (index < visibleCells.size()) {
  2673. // insert to right slot
  2674. DOM.insertChild(tr, cell.getElement(), index);
  2675. adopt(cell);
  2676. visibleCells.add(index, cell);
  2677. } else if (index == visibleCells.size()) {
  2678. // simply append
  2679. DOM.appendChild(tr, cell.getElement());
  2680. adopt(cell);
  2681. visibleCells.add(cell);
  2682. } else {
  2683. throw new RuntimeException(
  2684. "Header cells must be appended in order");
  2685. }
  2686. }
  2687. public HeaderCell getHeaderCell(int index) {
  2688. if (index >= 0 && index < visibleCells.size()) {
  2689. return (HeaderCell) visibleCells.get(index);
  2690. } else {
  2691. return null;
  2692. }
  2693. }
  2694. /**
  2695. * Get's HeaderCell by it's column Key.
  2696. *
  2697. * Note that this returns HeaderCell even if it is currently collapsed.
  2698. *
  2699. * @param cid
  2700. * Column key of accessed HeaderCell
  2701. * @return HeaderCell
  2702. */
  2703. public HeaderCell getHeaderCell(String cid) {
  2704. return availableCells.get(cid);
  2705. }
  2706. public void moveCell(int oldIndex, int newIndex) {
  2707. final HeaderCell hCell = getHeaderCell(oldIndex);
  2708. final Element cell = hCell.getElement();
  2709. visibleCells.remove(oldIndex);
  2710. DOM.removeChild(tr, cell);
  2711. DOM.insertChild(tr, cell, newIndex);
  2712. visibleCells.add(newIndex, hCell);
  2713. }
  2714. public Iterator<Widget> iterator() {
  2715. return visibleCells.iterator();
  2716. }
  2717. @Override
  2718. public boolean remove(Widget w) {
  2719. if (visibleCells.contains(w)) {
  2720. visibleCells.remove(w);
  2721. orphan(w);
  2722. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  2723. return true;
  2724. }
  2725. return false;
  2726. }
  2727. public void removeCell(String colKey) {
  2728. final HeaderCell c = getHeaderCell(colKey);
  2729. remove(c);
  2730. }
  2731. private void focusSlot(int index) {
  2732. removeSlotFocus();
  2733. if (index > 0) {
  2734. DOM.setElementProperty(
  2735. DOM.getFirstChild(DOM.getChild(tr, index - 1)),
  2736. "className", CLASSNAME + "-resizer " + CLASSNAME
  2737. + "-focus-slot-right");
  2738. } else {
  2739. DOM.setElementProperty(
  2740. DOM.getFirstChild(DOM.getChild(tr, index)),
  2741. "className", CLASSNAME + "-resizer " + CLASSNAME
  2742. + "-focus-slot-left");
  2743. }
  2744. focusedSlot = index;
  2745. }
  2746. private void removeSlotFocus() {
  2747. if (focusedSlot < 0) {
  2748. return;
  2749. }
  2750. if (focusedSlot == 0) {
  2751. DOM.setElementProperty(
  2752. DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
  2753. "className", CLASSNAME + "-resizer");
  2754. } else if (focusedSlot > 0) {
  2755. DOM.setElementProperty(
  2756. DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
  2757. "className", CLASSNAME + "-resizer");
  2758. }
  2759. focusedSlot = -1;
  2760. }
  2761. @Override
  2762. public void onBrowserEvent(Event event) {
  2763. if (enabled) {
  2764. if (event.getEventTarget().cast() == columnSelector) {
  2765. final int left = DOM.getAbsoluteLeft(columnSelector);
  2766. final int top = DOM.getAbsoluteTop(columnSelector)
  2767. + DOM.getElementPropertyInt(columnSelector,
  2768. "offsetHeight");
  2769. client.getContextMenu().showAt(this, left, top);
  2770. }
  2771. }
  2772. }
  2773. @Override
  2774. protected void onDetach() {
  2775. super.onDetach();
  2776. if (client != null) {
  2777. client.getContextMenu().ensureHidden(this);
  2778. }
  2779. }
  2780. class VisibleColumnAction extends Action {
  2781. String colKey;
  2782. private boolean collapsed;
  2783. private VScrollTableRow currentlyFocusedRow;
  2784. public VisibleColumnAction(String colKey) {
  2785. super(VScrollTable.TableHead.this);
  2786. this.colKey = colKey;
  2787. caption = tHead.getHeaderCell(colKey).getCaption();
  2788. currentlyFocusedRow = focusedRow;
  2789. }
  2790. @Override
  2791. public void execute() {
  2792. client.getContextMenu().hide();
  2793. // toggle selected column
  2794. if (collapsedColumns.contains(colKey)) {
  2795. collapsedColumns.remove(colKey);
  2796. } else {
  2797. tHead.removeCell(colKey);
  2798. collapsedColumns.add(colKey);
  2799. triggerLazyColumnAdjustment(true);
  2800. }
  2801. // update variable to server
  2802. client.updateVariable(paintableId, "collapsedcolumns",
  2803. collapsedColumns.toArray(new String[collapsedColumns
  2804. .size()]), false);
  2805. // let rowRequestHandler determine proper rows
  2806. rowRequestHandler.refreshContent();
  2807. lazyRevertFocusToRow(currentlyFocusedRow);
  2808. }
  2809. public void setCollapsed(boolean b) {
  2810. collapsed = b;
  2811. }
  2812. /**
  2813. * Override default method to distinguish on/off columns
  2814. */
  2815. @Override
  2816. public String getHTML() {
  2817. final StringBuffer buf = new StringBuffer();
  2818. if (collapsed) {
  2819. buf.append("<span class=\"v-off\">");
  2820. } else {
  2821. buf.append("<span class=\"v-on\">");
  2822. }
  2823. buf.append(super.getHTML());
  2824. buf.append("</span>");
  2825. return buf.toString();
  2826. }
  2827. }
  2828. /*
  2829. * Returns columns as Action array for column select popup
  2830. */
  2831. public Action[] getActions() {
  2832. Object[] cols;
  2833. if (columnReordering && columnOrder != null) {
  2834. cols = columnOrder;
  2835. } else {
  2836. // if columnReordering is disabled, we need different way to get
  2837. // all available columns
  2838. cols = visibleColOrder;
  2839. cols = new Object[visibleColOrder.length
  2840. + collapsedColumns.size()];
  2841. int i;
  2842. for (i = 0; i < visibleColOrder.length; i++) {
  2843. cols[i] = visibleColOrder[i];
  2844. }
  2845. for (final Iterator<String> it = collapsedColumns.iterator(); it
  2846. .hasNext();) {
  2847. cols[i++] = it.next();
  2848. }
  2849. }
  2850. final Action[] actions = new Action[cols.length];
  2851. for (int i = 0; i < cols.length; i++) {
  2852. final String cid = (String) cols[i];
  2853. final HeaderCell c = getHeaderCell(cid);
  2854. final VisibleColumnAction a = new VisibleColumnAction(
  2855. c.getColKey());
  2856. a.setCaption(c.getCaption());
  2857. if (!c.isEnabled()) {
  2858. a.setCollapsed(true);
  2859. }
  2860. actions[i] = a;
  2861. }
  2862. return actions;
  2863. }
  2864. public ApplicationConnection getClient() {
  2865. return client;
  2866. }
  2867. public String getPaintableId() {
  2868. return paintableId;
  2869. }
  2870. /**
  2871. * Returns column alignments for visible columns
  2872. */
  2873. public char[] getColumnAlignments() {
  2874. final Iterator<Widget> it = visibleCells.iterator();
  2875. final char[] aligns = new char[visibleCells.size()];
  2876. int colIndex = 0;
  2877. while (it.hasNext()) {
  2878. aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
  2879. }
  2880. return aligns;
  2881. }
  2882. /**
  2883. * Disables the automatic calculation of all column widths by forcing
  2884. * the widths to be "defined" thus turning off expand ratios and such.
  2885. */
  2886. public void disableAutoColumnWidthCalculation(HeaderCell source) {
  2887. for (HeaderCell cell : availableCells.values()) {
  2888. cell.disableAutoWidthCalculation();
  2889. }
  2890. // fire column resize events for all columns but the source of the
  2891. // resize action, since an event will fire separately for this.
  2892. ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
  2893. availableCells.values());
  2894. columns.remove(source);
  2895. sendColumnWidthUpdates(columns);
  2896. forceRealignColumnHeaders();
  2897. }
  2898. }
  2899. /**
  2900. * A cell in the footer
  2901. */
  2902. public class FooterCell extends Widget {
  2903. private final Element td = DOM.createTD();
  2904. private final Element captionContainer = DOM.createDiv();
  2905. private char align = ALIGN_LEFT;
  2906. private int width = -1;
  2907. private float expandRatio = 0;
  2908. private final String cid;
  2909. boolean definedWidth = false;
  2910. private int naturalWidth = -1;
  2911. public FooterCell(String colId, String headerText) {
  2912. cid = colId;
  2913. setText(headerText);
  2914. DOM.setElementProperty(captionContainer, "className", CLASSNAME
  2915. + "-footer-container");
  2916. // ensure no clipping initially (problem on column additions)
  2917. DOM.setStyleAttribute(captionContainer, "overflow", "visible");
  2918. DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
  2919. DOM.appendChild(td, captionContainer);
  2920. DOM.sinkEvents(td, Event.MOUSEEVENTS);
  2921. setElement(td);
  2922. }
  2923. /**
  2924. * Sets the text of the footer
  2925. *
  2926. * @param footerText
  2927. * The text in the footer
  2928. */
  2929. public void setText(String footerText) {
  2930. DOM.setInnerHTML(captionContainer, footerText);
  2931. }
  2932. /**
  2933. * Set alignment of the text in the cell
  2934. *
  2935. * @param c
  2936. * The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
  2937. * ALIGN_RIGHT
  2938. */
  2939. public void setAlign(char c) {
  2940. if (align != c) {
  2941. switch (c) {
  2942. case ALIGN_CENTER:
  2943. DOM.setStyleAttribute(captionContainer, "textAlign",
  2944. "center");
  2945. break;
  2946. case ALIGN_RIGHT:
  2947. DOM.setStyleAttribute(captionContainer, "textAlign",
  2948. "right");
  2949. break;
  2950. default:
  2951. DOM.setStyleAttribute(captionContainer, "textAlign", "");
  2952. break;
  2953. }
  2954. }
  2955. align = c;
  2956. }
  2957. /**
  2958. * Get the alignment of the text int the cell
  2959. *
  2960. * @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
  2961. */
  2962. public char getAlign() {
  2963. return align;
  2964. }
  2965. /**
  2966. * Sets the width of the cell
  2967. *
  2968. * @param w
  2969. * The width of the cell
  2970. * @param ensureDefinedWidth
  2971. * Ensures the the given width is not recalculated
  2972. */
  2973. public void setWidth(int w, boolean ensureDefinedWidth) {
  2974. if (ensureDefinedWidth) {
  2975. definedWidth = true;
  2976. // on column resize expand ratio becomes zero
  2977. expandRatio = 0;
  2978. }
  2979. if (width == w) {
  2980. return;
  2981. }
  2982. if (width == -1) {
  2983. // go to default mode, clip content if necessary
  2984. DOM.setStyleAttribute(captionContainer, "overflow", "");
  2985. }
  2986. width = w;
  2987. if (w == -1) {
  2988. DOM.setStyleAttribute(captionContainer, "width", "");
  2989. setWidth("");
  2990. } else {
  2991. /*
  2992. * Reduce width with one pixel for the right border since the
  2993. * footers does not have any spacers between them.
  2994. */
  2995. int borderWidths = 1;
  2996. // Set the container width (check for negative value)
  2997. if (w - borderWidths >= 0) {
  2998. captionContainer.getStyle().setPropertyPx("width",
  2999. w - borderWidths);
  3000. } else {
  3001. captionContainer.getStyle().setPropertyPx("width", 0);
  3002. }
  3003. /*
  3004. * if we already have tBody, set the header width properly, if
  3005. * not defer it. IE will fail with complex float in table header
  3006. * unless TD width is not explicitly set.
  3007. */
  3008. if (scrollBody != null) {
  3009. /*
  3010. * Reduce with one since footer does not have any spacers,
  3011. * instead a 1 pixel border.
  3012. */
  3013. int tdWidth = width + scrollBody.getCellExtraWidth()
  3014. - borderWidths;
  3015. setWidth(tdWidth + "px");
  3016. } else {
  3017. Scheduler.get().scheduleDeferred(new Command() {
  3018. public void execute() {
  3019. int borderWidths = 1;
  3020. int tdWidth = width
  3021. + scrollBody.getCellExtraWidth()
  3022. - borderWidths;
  3023. setWidth(tdWidth + "px");
  3024. }
  3025. });
  3026. }
  3027. }
  3028. }
  3029. /**
  3030. * Sets the width to undefined
  3031. */
  3032. public void setUndefinedWidth() {
  3033. setWidth(-1, false);
  3034. }
  3035. /**
  3036. * Detects if width is fixed by developer on server side or resized to
  3037. * current width by user.
  3038. *
  3039. * @return true if defined, false if "natural" width
  3040. */
  3041. public boolean isDefinedWidth() {
  3042. return definedWidth && width >= 0;
  3043. }
  3044. /**
  3045. * Returns the pixels width of the footer cell
  3046. *
  3047. * @return The width in pixels
  3048. */
  3049. public int getWidth() {
  3050. return width;
  3051. }
  3052. /**
  3053. * Sets the expand ratio of the cell
  3054. *
  3055. * @param floatAttribute
  3056. * The expand ratio
  3057. */
  3058. public void setExpandRatio(float floatAttribute) {
  3059. expandRatio = floatAttribute;
  3060. }
  3061. /**
  3062. * Returns the expand ration of the cell
  3063. *
  3064. * @return The expand ratio
  3065. */
  3066. public float getExpandRatio() {
  3067. return expandRatio;
  3068. }
  3069. /**
  3070. * Is the cell enabled?
  3071. *
  3072. * @return True if enabled else False
  3073. */
  3074. public boolean isEnabled() {
  3075. return getParent() != null;
  3076. }
  3077. /**
  3078. * Handle column clicking
  3079. */
  3080. @Override
  3081. public void onBrowserEvent(Event event) {
  3082. if (enabled && event != null) {
  3083. handleCaptionEvent(event);
  3084. if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
  3085. scrollBodyPanel.setFocus(true);
  3086. }
  3087. event.stopPropagation();
  3088. event.preventDefault();
  3089. }
  3090. }
  3091. /**
  3092. * Handles a event on the captions
  3093. *
  3094. * @param event
  3095. * The event to handle
  3096. */
  3097. protected void handleCaptionEvent(Event event) {
  3098. if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
  3099. fireFooterClickedEvent(event);
  3100. }
  3101. }
  3102. /**
  3103. * Fires a footer click event after the user has clicked a column footer
  3104. * cell
  3105. *
  3106. * @param event
  3107. * The click event
  3108. */
  3109. private void fireFooterClickedEvent(Event event) {
  3110. if (client.hasEventListeners(VScrollTable.this,
  3111. FOOTER_CLICK_EVENT_ID)) {
  3112. MouseEventDetails details = new MouseEventDetails(event);
  3113. client.updateVariable(paintableId, "footerClickEvent",
  3114. details.toString(), false);
  3115. client.updateVariable(paintableId, "footerClickCID", cid, true);
  3116. }
  3117. }
  3118. /**
  3119. * Returns the column key of the column
  3120. *
  3121. * @return The column key
  3122. */
  3123. public String getColKey() {
  3124. return cid;
  3125. }
  3126. /**
  3127. * Detects the natural minimum width for the column of this header cell.
  3128. * If column is resized by user or the width is defined by server the
  3129. * actual width is returned. Else the natural min width is returned.
  3130. *
  3131. * @param columnIndex
  3132. * column index hint, if -1 (unknown) it will be detected
  3133. *
  3134. * @return
  3135. */
  3136. public int getNaturalColumnWidth(int columnIndex) {
  3137. if (isDefinedWidth()) {
  3138. return width;
  3139. } else {
  3140. if (naturalWidth < 0) {
  3141. // This is recently revealed column. Try to detect a proper
  3142. // value (greater of header and data
  3143. // cols)
  3144. final int hw = ((Element) getElement().getLastChild())
  3145. .getOffsetWidth() + scrollBody.getCellExtraWidth();
  3146. if (columnIndex < 0) {
  3147. columnIndex = 0;
  3148. for (Iterator<Widget> it = tHead.iterator(); it
  3149. .hasNext(); columnIndex++) {
  3150. if (it.next() == this) {
  3151. break;
  3152. }
  3153. }
  3154. }
  3155. final int cw = scrollBody.getColWidth(columnIndex);
  3156. naturalWidth = (hw > cw ? hw : cw);
  3157. }
  3158. return naturalWidth;
  3159. }
  3160. }
  3161. public void setNaturalMinimumColumnWidth(int w) {
  3162. naturalWidth = w;
  3163. }
  3164. }
  3165. /**
  3166. * HeaderCell that is header cell for row headers.
  3167. *
  3168. * Reordering disabled and clicking on it resets sorting.
  3169. */
  3170. public class RowHeadersFooterCell extends FooterCell {
  3171. RowHeadersFooterCell() {
  3172. super(ROW_HEADER_COLUMN_KEY, "");
  3173. }
  3174. @Override
  3175. protected void handleCaptionEvent(Event event) {
  3176. // NOP: RowHeaders cannot be reordered
  3177. // TODO It'd be nice to reset sorting here
  3178. }
  3179. }
  3180. /**
  3181. * The footer of the table which can be seen in the bottom of the Table.
  3182. */
  3183. public class TableFooter extends Panel {
  3184. private static final int WRAPPER_WIDTH = 900000;
  3185. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  3186. HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
  3187. Element div = DOM.createDiv();
  3188. Element hTableWrapper = DOM.createDiv();
  3189. Element hTableContainer = DOM.createDiv();
  3190. Element table = DOM.createTable();
  3191. Element headerTableBody = DOM.createTBody();
  3192. Element tr = DOM.createTR();
  3193. public TableFooter() {
  3194. DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
  3195. DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
  3196. + "-footer");
  3197. DOM.appendChild(table, headerTableBody);
  3198. DOM.appendChild(headerTableBody, tr);
  3199. DOM.appendChild(hTableContainer, table);
  3200. DOM.appendChild(hTableWrapper, hTableContainer);
  3201. DOM.appendChild(div, hTableWrapper);
  3202. setElement(div);
  3203. setStyleName(CLASSNAME + "-footer-wrap");
  3204. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3205. new RowHeadersFooterCell());
  3206. }
  3207. @Override
  3208. public void clear() {
  3209. for (String cid : availableCells.keySet()) {
  3210. removeCell(cid);
  3211. }
  3212. availableCells.clear();
  3213. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3214. new RowHeadersFooterCell());
  3215. }
  3216. /*
  3217. * (non-Javadoc)
  3218. *
  3219. * @see
  3220. * com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
  3221. * .ui.Widget)
  3222. */
  3223. @Override
  3224. public boolean remove(Widget w) {
  3225. if (visibleCells.contains(w)) {
  3226. visibleCells.remove(w);
  3227. orphan(w);
  3228. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  3229. return true;
  3230. }
  3231. return false;
  3232. }
  3233. /*
  3234. * (non-Javadoc)
  3235. *
  3236. * @see com.google.gwt.user.client.ui.HasWidgets#iterator()
  3237. */
  3238. public Iterator<Widget> iterator() {
  3239. return visibleCells.iterator();
  3240. }
  3241. /**
  3242. * Gets a footer cell which represents the given columnId
  3243. *
  3244. * @param cid
  3245. * The columnId
  3246. *
  3247. * @return The cell
  3248. */
  3249. public FooterCell getFooterCell(String cid) {
  3250. return availableCells.get(cid);
  3251. }
  3252. /**
  3253. * Gets a footer cell by using a column index
  3254. *
  3255. * @param index
  3256. * The index of the column
  3257. * @return The Cell
  3258. */
  3259. public FooterCell getFooterCell(int index) {
  3260. if (index < visibleCells.size()) {
  3261. return (FooterCell) visibleCells.get(index);
  3262. } else {
  3263. return null;
  3264. }
  3265. }
  3266. /**
  3267. * Updates the cells contents when updateUIDL request is received
  3268. *
  3269. * @param uidl
  3270. * The UIDL
  3271. */
  3272. public void updateCellsFromUIDL(UIDL uidl) {
  3273. Iterator<?> columnIterator = uidl.getChildIterator();
  3274. HashSet<String> updated = new HashSet<String>();
  3275. while (columnIterator.hasNext()) {
  3276. final UIDL col = (UIDL) columnIterator.next();
  3277. final String cid = col.getStringAttribute("cid");
  3278. updated.add(cid);
  3279. String caption = col.hasAttribute("fcaption") ? col
  3280. .getStringAttribute("fcaption") : "";
  3281. FooterCell c = getFooterCell(cid);
  3282. if (c == null) {
  3283. c = new FooterCell(cid, caption);
  3284. availableCells.put(cid, c);
  3285. if (initializedAndAttached) {
  3286. // we will need a column width recalculation
  3287. initializedAndAttached = false;
  3288. initialContentReceived = false;
  3289. isNewBody = true;
  3290. }
  3291. } else {
  3292. c.setText(caption);
  3293. }
  3294. if (col.hasAttribute("align")) {
  3295. c.setAlign(col.getStringAttribute("align").charAt(0));
  3296. } else {
  3297. c.setAlign(ALIGN_LEFT);
  3298. }
  3299. if (col.hasAttribute("width")) {
  3300. if (scrollBody == null) {
  3301. // Already updated by setColWidth called from
  3302. // TableHeads.updateCellsFromUIDL in case of a server
  3303. // side resize
  3304. final String width = col.getStringAttribute("width");
  3305. c.setWidth(Integer.parseInt(width), true);
  3306. }
  3307. } else if (recalcWidths) {
  3308. c.setUndefinedWidth();
  3309. }
  3310. if (col.hasAttribute("er")) {
  3311. c.setExpandRatio(col.getFloatAttribute("er"));
  3312. }
  3313. if (col.hasAttribute("collapsed")) {
  3314. // ensure header is properly removed from parent (case when
  3315. // collapsing happens via servers side api)
  3316. if (c.isAttached()) {
  3317. c.removeFromParent();
  3318. headerChangedDuringUpdate = true;
  3319. }
  3320. }
  3321. }
  3322. // check for orphaned header cells
  3323. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  3324. .hasNext();) {
  3325. String cid = cit.next();
  3326. if (!updated.contains(cid)) {
  3327. removeCell(cid);
  3328. cit.remove();
  3329. }
  3330. }
  3331. }
  3332. /**
  3333. * Set a footer cell for a specified column index
  3334. *
  3335. * @param index
  3336. * The index
  3337. * @param cell
  3338. * The footer cell
  3339. */
  3340. public void setFooterCell(int index, FooterCell cell) {
  3341. if (cell.isEnabled()) {
  3342. // we're moving the cell
  3343. DOM.removeChild(tr, cell.getElement());
  3344. orphan(cell);
  3345. visibleCells.remove(cell);
  3346. }
  3347. if (index < visibleCells.size()) {
  3348. // insert to right slot
  3349. DOM.insertChild(tr, cell.getElement(), index);
  3350. adopt(cell);
  3351. visibleCells.add(index, cell);
  3352. } else if (index == visibleCells.size()) {
  3353. // simply append
  3354. DOM.appendChild(tr, cell.getElement());
  3355. adopt(cell);
  3356. visibleCells.add(cell);
  3357. } else {
  3358. throw new RuntimeException(
  3359. "Header cells must be appended in order");
  3360. }
  3361. }
  3362. /**
  3363. * Remove a cell by using the columnId
  3364. *
  3365. * @param colKey
  3366. * The columnId to remove
  3367. */
  3368. public void removeCell(String colKey) {
  3369. final FooterCell c = getFooterCell(colKey);
  3370. remove(c);
  3371. }
  3372. /**
  3373. * Enable a column (Sets the footer cell)
  3374. *
  3375. * @param cid
  3376. * The columnId
  3377. * @param index
  3378. * The index of the column
  3379. */
  3380. public void enableColumn(String cid, int index) {
  3381. final FooterCell c = getFooterCell(cid);
  3382. if (!c.isEnabled() || getFooterCell(index) != c) {
  3383. setFooterCell(index, c);
  3384. if (initializedAndAttached) {
  3385. headerChangedDuringUpdate = true;
  3386. }
  3387. }
  3388. }
  3389. /**
  3390. * Disable browser measurement of the table width
  3391. */
  3392. public void disableBrowserIntelligence() {
  3393. DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
  3394. + "px");
  3395. }
  3396. /**
  3397. * Enable browser measurement of the table width
  3398. */
  3399. public void enableBrowserIntelligence() {
  3400. DOM.setStyleAttribute(hTableContainer, "width", "");
  3401. }
  3402. /**
  3403. * Set the horizontal position in the cell in the footer. This is done
  3404. * when a horizontal scrollbar is present.
  3405. *
  3406. * @param scrollLeft
  3407. * The value of the leftScroll
  3408. */
  3409. public void setHorizontalScrollPosition(int scrollLeft) {
  3410. hTableWrapper.setScrollLeft(scrollLeft);
  3411. }
  3412. /**
  3413. * Swap cells when the column are dragged
  3414. *
  3415. * @param oldIndex
  3416. * The old index of the cell
  3417. * @param newIndex
  3418. * The new index of the cell
  3419. */
  3420. public void moveCell(int oldIndex, int newIndex) {
  3421. final FooterCell hCell = getFooterCell(oldIndex);
  3422. final Element cell = hCell.getElement();
  3423. visibleCells.remove(oldIndex);
  3424. DOM.removeChild(tr, cell);
  3425. DOM.insertChild(tr, cell, newIndex);
  3426. visibleCells.add(newIndex, hCell);
  3427. }
  3428. }
  3429. /**
  3430. * This Panel can only contain VScrollTableRow type of widgets. This
  3431. * "simulates" very large table, keeping spacers which take room of
  3432. * unrendered rows.
  3433. *
  3434. */
  3435. public class VScrollTableBody extends Panel {
  3436. public static final int DEFAULT_ROW_HEIGHT = 24;
  3437. private double rowHeight = -1;
  3438. private final LinkedList<Widget> renderedRows = new LinkedList<Widget>();
  3439. /**
  3440. * Due some optimizations row height measuring is deferred and initial
  3441. * set of rows is rendered detached. Flag set on when table body has
  3442. * been attached in dom and rowheight has been measured.
  3443. */
  3444. private boolean tBodyMeasurementsDone = false;
  3445. Element preSpacer = DOM.createDiv();
  3446. Element postSpacer = DOM.createDiv();
  3447. Element container = DOM.createDiv();
  3448. TableSectionElement tBodyElement = Document.get().createTBodyElement();
  3449. Element table = DOM.createTable();
  3450. private int firstRendered;
  3451. private int lastRendered;
  3452. private char[] aligns;
  3453. protected VScrollTableBody() {
  3454. constructDOM();
  3455. setElement(container);
  3456. }
  3457. public VScrollTableRow getRowByRowIndex(int indexInTable) {
  3458. int internalIndex = indexInTable - firstRendered;
  3459. if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
  3460. return (VScrollTableRow) renderedRows.get(internalIndex);
  3461. } else {
  3462. return null;
  3463. }
  3464. }
  3465. /**
  3466. * @return the height of scrollable body, subpixels ceiled.
  3467. */
  3468. public int getRequiredHeight() {
  3469. return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
  3470. + Util.getRequiredHeight(table);
  3471. }
  3472. private void constructDOM() {
  3473. DOM.setElementProperty(table, "className", CLASSNAME + "-table");
  3474. if (BrowserInfo.get().isIE()) {
  3475. table.setPropertyInt("cellSpacing", 0);
  3476. }
  3477. DOM.setElementProperty(preSpacer, "className", CLASSNAME
  3478. + "-row-spacer");
  3479. DOM.setElementProperty(postSpacer, "className", CLASSNAME
  3480. + "-row-spacer");
  3481. table.appendChild(tBodyElement);
  3482. DOM.appendChild(container, preSpacer);
  3483. DOM.appendChild(container, table);
  3484. DOM.appendChild(container, postSpacer);
  3485. }
  3486. public int getAvailableWidth() {
  3487. int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
  3488. return availW;
  3489. }
  3490. public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
  3491. firstRendered = firstIndex;
  3492. lastRendered = firstIndex + rows - 1;
  3493. final Iterator<?> it = rowData.getChildIterator();
  3494. aligns = tHead.getColumnAlignments();
  3495. while (it.hasNext()) {
  3496. final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
  3497. addRow(row);
  3498. }
  3499. if (isAttached()) {
  3500. fixSpacers();
  3501. }
  3502. }
  3503. public void renderRows(UIDL rowData, int firstIndex, int rows) {
  3504. // FIXME REVIEW
  3505. aligns = tHead.getColumnAlignments();
  3506. final Iterator<?> it = rowData.getChildIterator();
  3507. if (firstIndex == lastRendered + 1) {
  3508. while (it.hasNext()) {
  3509. final VScrollTableRow row = prepareRow((UIDL) it.next());
  3510. addRow(row);
  3511. lastRendered++;
  3512. }
  3513. fixSpacers();
  3514. } else if (firstIndex + rows == firstRendered) {
  3515. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  3516. int i = rows;
  3517. while (it.hasNext()) {
  3518. i--;
  3519. rowArray[i] = prepareRow((UIDL) it.next());
  3520. }
  3521. for (i = 0; i < rows; i++) {
  3522. addRowBeforeFirstRendered(rowArray[i]);
  3523. firstRendered--;
  3524. }
  3525. } else {
  3526. // completely new set of rows
  3527. while (lastRendered + 1 > firstRendered) {
  3528. unlinkRow(false);
  3529. }
  3530. final VScrollTableRow row = prepareRow((UIDL) it.next());
  3531. firstRendered = firstIndex;
  3532. lastRendered = firstIndex - 1;
  3533. addRow(row);
  3534. lastRendered++;
  3535. setContainerHeight();
  3536. fixSpacers();
  3537. while (it.hasNext()) {
  3538. addRow(prepareRow((UIDL) it.next()));
  3539. lastRendered++;
  3540. }
  3541. fixSpacers();
  3542. }
  3543. // this may be a new set of rows due content change,
  3544. // ensure we have proper cache rows
  3545. ensureCacheFilled();
  3546. }
  3547. /**
  3548. * Ensure we have the correct set of rows on client side, e.g. if the
  3549. * content on the server side has changed, or the client scroll position
  3550. * has changed since the last request.
  3551. */
  3552. protected void ensureCacheFilled() {
  3553. int reactFirstRow = (int) (firstRowInViewPort - pageLength
  3554. * cache_react_rate);
  3555. int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
  3556. * cache_react_rate);
  3557. if (reactFirstRow < 0) {
  3558. reactFirstRow = 0;
  3559. }
  3560. if (reactLastRow >= totalRows) {
  3561. reactLastRow = totalRows - 1;
  3562. }
  3563. if (lastRendered < reactFirstRow || firstRendered > reactLastRow) {
  3564. /*
  3565. * #8040 - scroll position is completely changed since the
  3566. * latest request, so request a new set of rows.
  3567. *
  3568. * TODO: We should probably check whether the fetched rows match
  3569. * the current scroll position right when they arrive, so as to
  3570. * not waste time rendering a set of rows that will never be
  3571. * visible...
  3572. */
  3573. rowRequestHandler.setReqFirstRow(reactFirstRow);
  3574. rowRequestHandler.setReqRows(reactLastRow - reactFirstRow + 1);
  3575. rowRequestHandler.deferRowFetch(1);
  3576. } else if (lastRendered < reactLastRow) {
  3577. // get some cache rows below visible area
  3578. rowRequestHandler.setReqFirstRow(lastRendered + 1);
  3579. rowRequestHandler.setReqRows(reactLastRow - lastRendered);
  3580. rowRequestHandler.deferRowFetch(1);
  3581. } else if (firstRendered > reactFirstRow) {
  3582. /*
  3583. * Branch for fetching cache above visible area.
  3584. *
  3585. * If cache needed for both before and after visible area, this
  3586. * will be rendered after-cache is received and rendered. So in
  3587. * some rare situations the table may make two cache visits to
  3588. * server.
  3589. */
  3590. rowRequestHandler.setReqFirstRow(reactFirstRow);
  3591. rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
  3592. rowRequestHandler.deferRowFetch(1);
  3593. }
  3594. }
  3595. /**
  3596. * Inserts rows as provided in the rowData starting at firstIndex.
  3597. *
  3598. * @param rowData
  3599. * @param firstIndex
  3600. * @param rows
  3601. * the number of rows
  3602. * @return a list of the rows added.
  3603. */
  3604. protected List<VScrollTableRow> insertRows(UIDL rowData,
  3605. int firstIndex, int rows) {
  3606. aligns = tHead.getColumnAlignments();
  3607. final Iterator<?> it = rowData.getChildIterator();
  3608. List<VScrollTableRow> insertedRows = new ArrayList<VScrollTableRow>();
  3609. if (firstIndex == lastRendered + 1) {
  3610. while (it.hasNext()) {
  3611. final VScrollTableRow row = prepareRow((UIDL) it.next());
  3612. addRow(row);
  3613. insertedRows.add(row);
  3614. lastRendered++;
  3615. }
  3616. fixSpacers();
  3617. } else if (firstIndex + rows == firstRendered) {
  3618. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  3619. int i = rows;
  3620. while (it.hasNext()) {
  3621. i--;
  3622. rowArray[i] = prepareRow((UIDL) it.next());
  3623. }
  3624. for (i = 0; i < rows; i++) {
  3625. addRowBeforeFirstRendered(rowArray[i]);
  3626. insertedRows.add(rowArray[i]);
  3627. firstRendered--;
  3628. }
  3629. } else {
  3630. // insert in the middle
  3631. int ix = firstIndex;
  3632. while (it.hasNext()) {
  3633. VScrollTableRow row = prepareRow((UIDL) it.next());
  3634. insertRowAt(row, ix);
  3635. insertedRows.add(row);
  3636. lastRendered++;
  3637. ix++;
  3638. }
  3639. fixSpacers();
  3640. }
  3641. return insertedRows;
  3642. }
  3643. protected List<VScrollTableRow> insertAndReindexRows(UIDL rowData,
  3644. int firstIndex, int rows) {
  3645. List<VScrollTableRow> inserted = insertRows(rowData, firstIndex,
  3646. rows);
  3647. int actualIxOfFirstRowAfterInserted = firstIndex + rows
  3648. - firstRendered;
  3649. for (int ix = actualIxOfFirstRowAfterInserted; ix < renderedRows
  3650. .size(); ix++) {
  3651. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  3652. r.setIndex(r.getIndex() + rows);
  3653. }
  3654. setContainerHeight();
  3655. return inserted;
  3656. }
  3657. protected void insertRowsDeleteBelow(UIDL rowData, int firstIndex,
  3658. int rows) {
  3659. unlinkAllRowsStartingAt(firstIndex);
  3660. insertRows(rowData, firstIndex, rows);
  3661. setContainerHeight();
  3662. }
  3663. /**
  3664. * This method is used to instantiate new rows for this table. It
  3665. * automatically sets correct widths to rows cells and assigns correct
  3666. * client reference for child widgets.
  3667. *
  3668. * This method can be called only after table has been initialized
  3669. *
  3670. * @param uidl
  3671. */
  3672. private VScrollTableRow prepareRow(UIDL uidl) {
  3673. final VScrollTableRow row = createRow(uidl, aligns);
  3674. row.initCellWidths();
  3675. return row;
  3676. }
  3677. protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
  3678. if (uidl.hasAttribute("gen_html")) {
  3679. // This is a generated row.
  3680. return new VScrollTableGeneratedRow(uidl, aligns2);
  3681. }
  3682. return new VScrollTableRow(uidl, aligns2);
  3683. }
  3684. private void addRowBeforeFirstRendered(VScrollTableRow row) {
  3685. row.setIndex(firstRendered - 1);
  3686. if (row.isSelected()) {
  3687. row.addStyleName("v-selected");
  3688. }
  3689. tBodyElement.insertBefore(row.getElement(),
  3690. tBodyElement.getFirstChild());
  3691. adopt(row);
  3692. renderedRows.add(0, row);
  3693. }
  3694. private void addRow(VScrollTableRow row) {
  3695. row.setIndex(firstRendered + renderedRows.size());
  3696. if (row.isSelected()) {
  3697. row.addStyleName("v-selected");
  3698. }
  3699. tBodyElement.appendChild(row.getElement());
  3700. adopt(row);
  3701. renderedRows.add(row);
  3702. }
  3703. private void insertRowAt(VScrollTableRow row, int index) {
  3704. row.setIndex(index);
  3705. if (row.isSelected()) {
  3706. row.addStyleName("v-selected");
  3707. }
  3708. if (index > 0) {
  3709. VScrollTableRow sibling = getRowByRowIndex(index - 1);
  3710. tBodyElement
  3711. .insertAfter(row.getElement(), sibling.getElement());
  3712. } else {
  3713. VScrollTableRow sibling = getRowByRowIndex(index);
  3714. tBodyElement.insertBefore(row.getElement(),
  3715. sibling.getElement());
  3716. }
  3717. adopt(row);
  3718. int actualIx = index - firstRendered;
  3719. renderedRows.add(actualIx, row);
  3720. }
  3721. public Iterator<Widget> iterator() {
  3722. return renderedRows.iterator();
  3723. }
  3724. /**
  3725. * @return false if couldn't remove row
  3726. */
  3727. protected boolean unlinkRow(boolean fromBeginning) {
  3728. if (lastRendered - firstRendered < 0) {
  3729. return false;
  3730. }
  3731. int actualIx;
  3732. if (fromBeginning) {
  3733. actualIx = 0;
  3734. firstRendered++;
  3735. } else {
  3736. actualIx = renderedRows.size() - 1;
  3737. lastRendered--;
  3738. }
  3739. if (actualIx >= 0) {
  3740. unlinkRowAtActualIndex(actualIx);
  3741. fixSpacers();
  3742. return true;
  3743. }
  3744. return false;
  3745. }
  3746. protected void unlinkRows(int firstIndex, int count) {
  3747. if (count < 1) {
  3748. return;
  3749. }
  3750. if (firstRendered > firstIndex
  3751. && firstRendered < firstIndex + count) {
  3752. firstIndex = firstRendered;
  3753. }
  3754. int lastIndex = firstIndex + count - 1;
  3755. if (lastRendered < lastIndex) {
  3756. lastIndex = lastRendered;
  3757. }
  3758. for (int ix = lastIndex; ix >= firstIndex; ix--) {
  3759. unlinkRowAtActualIndex(actualIndex(ix));
  3760. lastRendered--;
  3761. }
  3762. fixSpacers();
  3763. }
  3764. protected void unlinkAndReindexRows(int firstIndex, int count) {
  3765. unlinkRows(firstIndex, count);
  3766. int actualFirstIx = firstIndex - firstRendered;
  3767. for (int ix = actualFirstIx; ix < renderedRows.size(); ix++) {
  3768. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  3769. r.setIndex(r.getIndex() - count);
  3770. }
  3771. setContainerHeight();
  3772. }
  3773. protected void unlinkAllRowsStartingAt(int index) {
  3774. if (firstRendered > index) {
  3775. index = firstRendered;
  3776. }
  3777. for (int ix = renderedRows.size() - 1; ix >= index; ix--) {
  3778. unlinkRowAtActualIndex(actualIndex(ix));
  3779. lastRendered--;
  3780. }
  3781. fixSpacers();
  3782. }
  3783. private int actualIndex(int index) {
  3784. return index - firstRendered;
  3785. }
  3786. private void unlinkRowAtActualIndex(int index) {
  3787. final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
  3788. .get(index);
  3789. // Unregister row tooltip
  3790. client.registerTooltip(VScrollTable.this, toBeRemoved.getElement(),
  3791. null);
  3792. for (int i = 0; i < toBeRemoved.getElement().getChildCount(); i++) {
  3793. // Unregister cell tooltips
  3794. Element td = toBeRemoved.getElement().getChild(i).cast();
  3795. client.registerTooltip(VScrollTable.this, td, null);
  3796. }
  3797. lazyUnregistryBag.add(toBeRemoved);
  3798. tBodyElement.removeChild(toBeRemoved.getElement());
  3799. orphan(toBeRemoved);
  3800. renderedRows.remove(index);
  3801. }
  3802. @Override
  3803. public boolean remove(Widget w) {
  3804. throw new UnsupportedOperationException();
  3805. }
  3806. @Override
  3807. protected void onAttach() {
  3808. super.onAttach();
  3809. setContainerHeight();
  3810. }
  3811. /**
  3812. * Fix container blocks height according to totalRows to avoid
  3813. * "bouncing" when scrolling
  3814. */
  3815. private void setContainerHeight() {
  3816. fixSpacers();
  3817. DOM.setStyleAttribute(container, "height",
  3818. measureRowHeightOffset(totalRows) + "px");
  3819. }
  3820. private void fixSpacers() {
  3821. int prepx = measureRowHeightOffset(firstRendered);
  3822. if (prepx < 0) {
  3823. prepx = 0;
  3824. }
  3825. preSpacer.getStyle().setPropertyPx("height", prepx);
  3826. int postpx = measureRowHeightOffset(totalRows - 1)
  3827. - measureRowHeightOffset(lastRendered);
  3828. if (postpx < 0) {
  3829. postpx = 0;
  3830. }
  3831. postSpacer.getStyle().setPropertyPx("height", postpx);
  3832. }
  3833. public double getRowHeight() {
  3834. return getRowHeight(false);
  3835. }
  3836. public double getRowHeight(boolean forceUpdate) {
  3837. if (tBodyMeasurementsDone && !forceUpdate) {
  3838. return rowHeight;
  3839. } else {
  3840. if (tBodyElement.getRows().getLength() > 0) {
  3841. int tableHeight = getTableHeight();
  3842. int rowCount = tBodyElement.getRows().getLength();
  3843. rowHeight = tableHeight / (double) rowCount;
  3844. } else {
  3845. if (isAttached()) {
  3846. // measure row height by adding a dummy row
  3847. VScrollTableRow scrollTableRow = new VScrollTableRow();
  3848. tBodyElement.appendChild(scrollTableRow.getElement());
  3849. getRowHeight(forceUpdate);
  3850. tBodyElement.removeChild(scrollTableRow.getElement());
  3851. } else {
  3852. // TODO investigate if this can never happen anymore
  3853. return DEFAULT_ROW_HEIGHT;
  3854. }
  3855. }
  3856. tBodyMeasurementsDone = true;
  3857. return rowHeight;
  3858. }
  3859. }
  3860. public int getTableHeight() {
  3861. return table.getOffsetHeight();
  3862. }
  3863. /**
  3864. * Returns the width available for column content.
  3865. *
  3866. * @param columnIndex
  3867. * @return
  3868. */
  3869. public int getColWidth(int columnIndex) {
  3870. if (tBodyMeasurementsDone) {
  3871. if (renderedRows.isEmpty()) {
  3872. // no rows yet rendered
  3873. return 0;
  3874. }
  3875. for (Widget row : renderedRows) {
  3876. if (!(row instanceof VScrollTableGeneratedRow)) {
  3877. TableRowElement tr = row.getElement().cast();
  3878. Element wrapperdiv = tr.getCells().getItem(columnIndex)
  3879. .getFirstChildElement().cast();
  3880. return wrapperdiv.getOffsetWidth();
  3881. }
  3882. }
  3883. return 0;
  3884. } else {
  3885. return 0;
  3886. }
  3887. }
  3888. /**
  3889. * Sets the content width of a column.
  3890. *
  3891. * Due IE limitation, we must set the width to a wrapper elements inside
  3892. * table cells (with overflow hidden, which does not work on td
  3893. * elements).
  3894. *
  3895. * To get this work properly crossplatform, we will also set the width
  3896. * of td.
  3897. *
  3898. * @param colIndex
  3899. * @param w
  3900. */
  3901. public void setColWidth(int colIndex, int w) {
  3902. for (Widget row : renderedRows) {
  3903. ((VScrollTableRow) row).setCellWidth(colIndex, w);
  3904. }
  3905. }
  3906. private int cellExtraWidth = -1;
  3907. /**
  3908. * Method to return the space used for cell paddings + border.
  3909. */
  3910. private int getCellExtraWidth() {
  3911. if (cellExtraWidth < 0) {
  3912. detectExtrawidth();
  3913. }
  3914. return cellExtraWidth;
  3915. }
  3916. private void detectExtrawidth() {
  3917. NodeList<TableRowElement> rows = tBodyElement.getRows();
  3918. if (rows.getLength() == 0) {
  3919. /* need to temporary add empty row and detect */
  3920. VScrollTableRow scrollTableRow = new VScrollTableRow();
  3921. tBodyElement.appendChild(scrollTableRow.getElement());
  3922. detectExtrawidth();
  3923. tBodyElement.removeChild(scrollTableRow.getElement());
  3924. } else {
  3925. boolean noCells = false;
  3926. TableRowElement item = rows.getItem(0);
  3927. TableCellElement firstTD = item.getCells().getItem(0);
  3928. if (firstTD == null) {
  3929. // content is currently empty, we need to add a fake cell
  3930. // for measuring
  3931. noCells = true;
  3932. VScrollTableRow next = (VScrollTableRow) iterator().next();
  3933. boolean sorted = tHead.getHeaderCell(0) != null ? tHead
  3934. .getHeaderCell(0).isSorted() : false;
  3935. next.addCell(null, "", ALIGN_LEFT, "", true, sorted);
  3936. firstTD = item.getCells().getItem(0);
  3937. }
  3938. com.google.gwt.dom.client.Element wrapper = firstTD
  3939. .getFirstChildElement();
  3940. cellExtraWidth = firstTD.getOffsetWidth()
  3941. - wrapper.getOffsetWidth();
  3942. if (noCells) {
  3943. firstTD.getParentElement().removeChild(firstTD);
  3944. }
  3945. }
  3946. }
  3947. private void reLayoutComponents() {
  3948. for (Widget w : this) {
  3949. VScrollTableRow r = (VScrollTableRow) w;
  3950. for (Widget widget : r) {
  3951. client.handleComponentRelativeSize(widget);
  3952. }
  3953. }
  3954. }
  3955. public int getLastRendered() {
  3956. return lastRendered;
  3957. }
  3958. public int getFirstRendered() {
  3959. return firstRendered;
  3960. }
  3961. public void moveCol(int oldIndex, int newIndex) {
  3962. // loop all rows and move given index to its new place
  3963. final Iterator<?> rows = iterator();
  3964. while (rows.hasNext()) {
  3965. final VScrollTableRow row = (VScrollTableRow) rows.next();
  3966. final Element td = DOM.getChild(row.getElement(), oldIndex);
  3967. if (td != null) {
  3968. DOM.removeChild(row.getElement(), td);
  3969. DOM.insertChild(row.getElement(), td, newIndex);
  3970. }
  3971. }
  3972. }
  3973. /**
  3974. * Restore row visibility which is set to "none" when the row is
  3975. * rendered (due a performance optimization).
  3976. */
  3977. private void restoreRowVisibility() {
  3978. for (Widget row : renderedRows) {
  3979. row.getElement().getStyle().setProperty("visibility", "");
  3980. }
  3981. }
  3982. public class VScrollTableRow extends Panel implements ActionOwner,
  3983. Container {
  3984. private static final int TOUCHSCROLL_TIMEOUT = 70;
  3985. private static final int DRAGMODE_MULTIROW = 2;
  3986. protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
  3987. private boolean selected = false;
  3988. protected final int rowKey;
  3989. private List<UIDL> pendingComponentPaints;
  3990. private String[] actionKeys = null;
  3991. private final TableRowElement rowElement;
  3992. private boolean mDown;
  3993. private int index;
  3994. private Event touchStart;
  3995. private static final String ROW_CLASSNAME_EVEN = CLASSNAME + "-row";
  3996. private static final String ROW_CLASSNAME_ODD = CLASSNAME
  3997. + "-row-odd";
  3998. private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
  3999. private Timer contextTouchTimeout;
  4000. private int touchStartY;
  4001. private int touchStartX;
  4002. private VScrollTableRow(int rowKey) {
  4003. this.rowKey = rowKey;
  4004. rowElement = Document.get().createTRElement();
  4005. setElement(rowElement);
  4006. DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
  4007. | Event.TOUCHEVENTS | Event.ONDBLCLICK
  4008. | Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS);
  4009. }
  4010. public VScrollTableRow(UIDL uidl, char[] aligns) {
  4011. this(uidl.getIntAttribute("key"));
  4012. /*
  4013. * Rendering the rows as hidden improves Firefox and Safari
  4014. * performance drastically.
  4015. */
  4016. getElement().getStyle().setProperty("visibility", "hidden");
  4017. String rowStyle = uidl.getStringAttribute("rowstyle");
  4018. if (rowStyle != null) {
  4019. addStyleName(CLASSNAME + "-row-" + rowStyle);
  4020. }
  4021. String rowDescription = uidl.getStringAttribute("rowdescr");
  4022. if (rowDescription != null && !rowDescription.equals("")) {
  4023. TooltipInfo info = new TooltipInfo(rowDescription);
  4024. client.registerTooltip(VScrollTable.this, rowElement, info);
  4025. } else {
  4026. // Remove possibly previously set tooltip
  4027. client.registerTooltip(VScrollTable.this, rowElement, null);
  4028. }
  4029. tHead.getColumnAlignments();
  4030. int col = 0;
  4031. int visibleColumnIndex = -1;
  4032. // row header
  4033. if (showRowHeaders) {
  4034. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4035. addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
  4036. "rowheader", true, sorted);
  4037. visibleColumnIndex++;
  4038. }
  4039. if (uidl.hasAttribute("al")) {
  4040. actionKeys = uidl.getStringArrayAttribute("al");
  4041. }
  4042. addCellsFromUIDL(uidl, aligns, col, visibleColumnIndex);
  4043. if (uidl.hasAttribute("selected") && !isSelected()) {
  4044. toggleSelection();
  4045. }
  4046. }
  4047. /**
  4048. * Add a dummy row, used for measurements if Table is empty.
  4049. */
  4050. public VScrollTableRow() {
  4051. this(0);
  4052. addStyleName(CLASSNAME + "-row");
  4053. addCell(null, "_", 'b', "", true, false);
  4054. }
  4055. protected void initCellWidths() {
  4056. final int cells = tHead.getVisibleCellCount();
  4057. for (int i = 0; i < cells; i++) {
  4058. int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
  4059. if (w < 0) {
  4060. w = 0;
  4061. }
  4062. setCellWidth(i, w);
  4063. }
  4064. }
  4065. protected void setCellWidth(int cellIx, int width) {
  4066. final Element cell = DOM.getChild(getElement(), cellIx);
  4067. cell.getFirstChildElement().getStyle()
  4068. .setPropertyPx("width", width);
  4069. cell.getStyle().setPropertyPx("width", width);
  4070. }
  4071. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  4072. int visibleColumnIndex) {
  4073. final Iterator<?> cells = uidl.getChildIterator();
  4074. while (cells.hasNext()) {
  4075. final Object cell = cells.next();
  4076. visibleColumnIndex++;
  4077. String columnId = visibleColOrder[visibleColumnIndex];
  4078. String style = "";
  4079. if (uidl.hasAttribute("style-" + columnId)) {
  4080. style = uidl.getStringAttribute("style-" + columnId);
  4081. }
  4082. String description = null;
  4083. if (uidl.hasAttribute("descr-" + columnId)) {
  4084. description = uidl.getStringAttribute("descr-"
  4085. + columnId);
  4086. }
  4087. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4088. if (cell instanceof String) {
  4089. addCell(uidl, cell.toString(), aligns[col++], style,
  4090. isRenderHtmlInCells(), sorted, description);
  4091. } else {
  4092. final VPaintableWidget cellContent = client
  4093. .getPaintable((UIDL) cell);
  4094. addCell(uidl, cellContent.getWidgetForPaintable(),
  4095. aligns[col++], style, sorted);
  4096. paintComponent(cellContent, (UIDL) cell);
  4097. }
  4098. }
  4099. }
  4100. /**
  4101. * Overriding this and returning true causes all text cells to be
  4102. * rendered as HTML.
  4103. *
  4104. * @return always returns false in the default implementation
  4105. */
  4106. protected boolean isRenderHtmlInCells() {
  4107. return false;
  4108. }
  4109. /**
  4110. * Detects whether row is visible in tables viewport.
  4111. *
  4112. * @return
  4113. */
  4114. public boolean isInViewPort() {
  4115. int absoluteTop = getAbsoluteTop();
  4116. int scrollPosition = scrollBodyPanel.getScrollPosition();
  4117. if (absoluteTop < scrollPosition) {
  4118. return false;
  4119. }
  4120. int maxVisible = scrollPosition
  4121. + scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
  4122. if (absoluteTop > maxVisible) {
  4123. return false;
  4124. }
  4125. return true;
  4126. }
  4127. /**
  4128. * Makes a check based on indexes whether the row is before the
  4129. * compared row.
  4130. *
  4131. * @param row1
  4132. * @return true if this rows index is smaller than in the row1
  4133. */
  4134. public boolean isBefore(VScrollTableRow row1) {
  4135. return getIndex() < row1.getIndex();
  4136. }
  4137. /**
  4138. * Sets the index of the row in the whole table. Currently used just
  4139. * to set even/odd classname
  4140. *
  4141. * @param indexInWholeTable
  4142. */
  4143. private void setIndex(int indexInWholeTable) {
  4144. index = indexInWholeTable;
  4145. boolean isOdd = indexInWholeTable % 2 == 0;
  4146. // Inverted logic to be backwards compatible with earlier 6.4.
  4147. // It is very strange because rows 1,3,5 are considered "even"
  4148. // and 2,4,6 "odd".
  4149. //
  4150. // First remove any old styles so that both styles aren't
  4151. // applied when indexes are updated.
  4152. removeStyleName(ROW_CLASSNAME_ODD);
  4153. removeStyleName(ROW_CLASSNAME_EVEN);
  4154. if (!isOdd) {
  4155. addStyleName(ROW_CLASSNAME_ODD);
  4156. } else {
  4157. addStyleName(ROW_CLASSNAME_EVEN);
  4158. }
  4159. }
  4160. public int getIndex() {
  4161. return index;
  4162. }
  4163. protected void paintComponent(VPaintableWidget p, UIDL uidl) {
  4164. if (isAttached()) {
  4165. p.updateFromUIDL(uidl, client);
  4166. } else {
  4167. if (pendingComponentPaints == null) {
  4168. pendingComponentPaints = new LinkedList<UIDL>();
  4169. }
  4170. pendingComponentPaints.add(uidl);
  4171. }
  4172. }
  4173. @Override
  4174. protected void onAttach() {
  4175. super.onAttach();
  4176. if (pendingComponentPaints != null) {
  4177. for (UIDL uidl : pendingComponentPaints) {
  4178. VPaintableWidget paintable = (VPaintableWidget) VPaintableMap
  4179. .get(client).getPaintable(uidl.getId());
  4180. paintable.updateFromUIDL(uidl, client);
  4181. }
  4182. }
  4183. }
  4184. @Override
  4185. protected void onDetach() {
  4186. super.onDetach();
  4187. client.getContextMenu().ensureHidden(this);
  4188. }
  4189. public String getKey() {
  4190. return String.valueOf(rowKey);
  4191. }
  4192. public void addCell(UIDL rowUidl, String text, char align,
  4193. String style, boolean textIsHTML, boolean sorted) {
  4194. addCell(rowUidl, text, align, style, textIsHTML, sorted, null);
  4195. }
  4196. public void addCell(UIDL rowUidl, String text, char align,
  4197. String style, boolean textIsHTML, boolean sorted,
  4198. String description) {
  4199. // String only content is optimized by not using Label widget
  4200. final TableCellElement td = DOM.createTD().cast();
  4201. initCellWithText(text, align, style, textIsHTML, sorted,
  4202. description, td);
  4203. }
  4204. protected void initCellWithText(String text, char align,
  4205. String style, boolean textIsHTML, boolean sorted,
  4206. String description, final TableCellElement td) {
  4207. final Element container = DOM.createDiv();
  4208. String className = CLASSNAME + "-cell-content";
  4209. if (style != null && !style.equals("")) {
  4210. className += " " + CLASSNAME + "-cell-content-" + style;
  4211. }
  4212. if (sorted) {
  4213. className += " " + CLASSNAME + "-cell-content-sorted";
  4214. }
  4215. td.setClassName(className);
  4216. container.setClassName(CLASSNAME + "-cell-wrapper");
  4217. if (textIsHTML) {
  4218. container.setInnerHTML(text);
  4219. } else {
  4220. container.setInnerText(text);
  4221. }
  4222. if (align != ALIGN_LEFT) {
  4223. switch (align) {
  4224. case ALIGN_CENTER:
  4225. container.getStyle().setProperty("textAlign", "center");
  4226. break;
  4227. case ALIGN_RIGHT:
  4228. default:
  4229. container.getStyle().setProperty("textAlign", "right");
  4230. break;
  4231. }
  4232. }
  4233. if (description != null && !description.equals("")) {
  4234. TooltipInfo info = new TooltipInfo(description);
  4235. client.registerTooltip(VScrollTable.this, td, info);
  4236. } else {
  4237. // Remove possibly previously set tooltip
  4238. client.registerTooltip(VScrollTable.this, td, null);
  4239. }
  4240. td.appendChild(container);
  4241. getElement().appendChild(td);
  4242. }
  4243. public void addCell(UIDL rowUidl, Widget w, char align,
  4244. String style, boolean sorted) {
  4245. final TableCellElement td = DOM.createTD().cast();
  4246. initCellWithWidget(w, align, style, sorted, td);
  4247. }
  4248. protected void initCellWithWidget(Widget w, char align,
  4249. String style, boolean sorted, final TableCellElement td) {
  4250. final Element container = DOM.createDiv();
  4251. String className = CLASSNAME + "-cell-content";
  4252. if (style != null && !style.equals("")) {
  4253. className += " " + CLASSNAME + "-cell-content-" + style;
  4254. }
  4255. if (sorted) {
  4256. className += " " + CLASSNAME + "-cell-content-sorted";
  4257. }
  4258. td.setClassName(className);
  4259. container.setClassName(CLASSNAME + "-cell-wrapper");
  4260. // TODO most components work with this, but not all (e.g.
  4261. // Select)
  4262. // Old comment: make widget cells respect align.
  4263. // text-align:center for IE, margin: auto for others
  4264. if (align != ALIGN_LEFT) {
  4265. switch (align) {
  4266. case ALIGN_CENTER:
  4267. container.getStyle().setProperty("textAlign", "center");
  4268. break;
  4269. case ALIGN_RIGHT:
  4270. default:
  4271. container.getStyle().setProperty("textAlign", "right");
  4272. break;
  4273. }
  4274. }
  4275. td.appendChild(container);
  4276. getElement().appendChild(td);
  4277. // ensure widget not attached to another element (possible tBody
  4278. // change)
  4279. w.removeFromParent();
  4280. container.appendChild(w.getElement());
  4281. adopt(w);
  4282. childWidgets.add(w);
  4283. }
  4284. public Iterator<Widget> iterator() {
  4285. return childWidgets.iterator();
  4286. }
  4287. @Override
  4288. public boolean remove(Widget w) {
  4289. if (childWidgets.contains(w)) {
  4290. orphan(w);
  4291. DOM.removeChild(DOM.getParent(w.getElement()),
  4292. w.getElement());
  4293. childWidgets.remove(w);
  4294. return true;
  4295. } else {
  4296. return false;
  4297. }
  4298. }
  4299. /**
  4300. * If there are registered click listeners, sends a click event and
  4301. * returns true. Otherwise, does nothing and returns false.
  4302. *
  4303. * @param event
  4304. * @param targetTdOrTr
  4305. * @param immediate
  4306. * Whether the event is sent immediately
  4307. * @return Whether a click event was sent
  4308. */
  4309. private boolean handleClickEvent(Event event, Element targetTdOrTr,
  4310. boolean immediate) {
  4311. if (!client.hasEventListeners(VScrollTable.this,
  4312. ITEM_CLICK_EVENT_ID)) {
  4313. // Don't send an event if nobody is listening
  4314. return false;
  4315. }
  4316. // This row was clicked
  4317. client.updateVariable(paintableId, "clickedKey", "" + rowKey,
  4318. false);
  4319. if (getElement() == targetTdOrTr.getParentElement()) {
  4320. // A specific column was clicked
  4321. int childIndex = DOM.getChildIndex(getElement(),
  4322. targetTdOrTr);
  4323. String colKey = null;
  4324. colKey = tHead.getHeaderCell(childIndex).getColKey();
  4325. client.updateVariable(paintableId, "clickedColKey", colKey,
  4326. false);
  4327. }
  4328. MouseEventDetails details = new MouseEventDetails(event);
  4329. client.updateVariable(paintableId, "clickEvent",
  4330. details.toString(), immediate);
  4331. return true;
  4332. }
  4333. private void handleTooltips(final Event event, Element target) {
  4334. if (target.hasTagName("TD")) {
  4335. // Table cell (td)
  4336. Element container = target.getFirstChildElement().cast();
  4337. Element widget = container.getFirstChildElement().cast();
  4338. boolean containsWidget = false;
  4339. for (Widget w : childWidgets) {
  4340. if (widget == w.getElement()) {
  4341. containsWidget = true;
  4342. break;
  4343. }
  4344. }
  4345. if (!containsWidget) {
  4346. // Only text nodes has tooltips
  4347. if (client.getTooltipTitleInfo(VScrollTable.this,
  4348. target) != null) {
  4349. // Cell has description, use it
  4350. client.handleTooltipEvent(event, VScrollTable.this,
  4351. target);
  4352. } else {
  4353. // Cell might have row description, use row
  4354. // description
  4355. client.handleTooltipEvent(event, VScrollTable.this,
  4356. target.getParentElement());
  4357. }
  4358. }
  4359. } else {
  4360. // Table row (tr)
  4361. client.handleTooltipEvent(event, VScrollTable.this, target);
  4362. }
  4363. }
  4364. /*
  4365. * React on click that occur on content cells only
  4366. */
  4367. @Override
  4368. public void onBrowserEvent(final Event event) {
  4369. if (enabled) {
  4370. final int type = event.getTypeInt();
  4371. final Element targetTdOrTr = getEventTargetTdOrTr(event);
  4372. if (type == Event.ONCONTEXTMENU) {
  4373. showContextMenu(event);
  4374. if (enabled
  4375. && (actionKeys != null || client
  4376. .hasEventListeners(VScrollTable.this,
  4377. ITEM_CLICK_EVENT_ID))) {
  4378. /*
  4379. * Prevent browser context menu only if there are
  4380. * action handlers or item click listeners
  4381. * registered
  4382. */
  4383. event.stopPropagation();
  4384. event.preventDefault();
  4385. }
  4386. return;
  4387. }
  4388. boolean targetCellOrRowFound = targetTdOrTr != null;
  4389. if (targetCellOrRowFound) {
  4390. handleTooltips(event, targetTdOrTr);
  4391. }
  4392. switch (type) {
  4393. case Event.ONDBLCLICK:
  4394. if (targetCellOrRowFound) {
  4395. handleClickEvent(event, targetTdOrTr, true);
  4396. }
  4397. break;
  4398. case Event.ONMOUSEUP:
  4399. if (targetCellOrRowFound) {
  4400. mDown = false;
  4401. /*
  4402. * Queue here, send at the same time as the
  4403. * corresponding value change event - see #7127
  4404. */
  4405. boolean clickEventSent = handleClickEvent(event,
  4406. targetTdOrTr, false);
  4407. if (event.getButton() == Event.BUTTON_LEFT
  4408. && isSelectable()) {
  4409. // Ctrl+Shift click
  4410. if ((event.getCtrlKey() || event.getMetaKey())
  4411. && event.getShiftKey()
  4412. && isMultiSelectModeDefault()) {
  4413. toggleShiftSelection(false);
  4414. setRowFocus(this);
  4415. // Ctrl click
  4416. } else if ((event.getCtrlKey() || event
  4417. .getMetaKey())
  4418. && isMultiSelectModeDefault()) {
  4419. boolean wasSelected = isSelected();
  4420. toggleSelection();
  4421. setRowFocus(this);
  4422. /*
  4423. * next possible range select must start on
  4424. * this row
  4425. */
  4426. selectionRangeStart = this;
  4427. if (wasSelected) {
  4428. removeRowFromUnsentSelectionRanges(this);
  4429. }
  4430. } else if ((event.getCtrlKey() || event
  4431. .getMetaKey()) && isSingleSelectMode()) {
  4432. // Ctrl (or meta) click (Single selection)
  4433. if (!isSelected()
  4434. || (isSelected() && nullSelectionAllowed)) {
  4435. if (!isSelected()) {
  4436. deselectAll();
  4437. }
  4438. toggleSelection();
  4439. setRowFocus(this);
  4440. }
  4441. } else if (event.getShiftKey()
  4442. && isMultiSelectModeDefault()) {
  4443. // Shift click
  4444. toggleShiftSelection(true);
  4445. } else {
  4446. // click
  4447. boolean currentlyJustThisRowSelected = selectedRowKeys
  4448. .size() == 1
  4449. && selectedRowKeys
  4450. .contains(getKey());
  4451. if (!currentlyJustThisRowSelected) {
  4452. if (isSingleSelectMode()
  4453. || isMultiSelectModeDefault()) {
  4454. /*
  4455. * For default multi select mode
  4456. * (ctrl/shift) and for single
  4457. * select mode we need to clear the
  4458. * previous selection before
  4459. * selecting a new one when the user
  4460. * clicks on a row. Only in
  4461. * multiselect/simple mode the old
  4462. * selection should remain after a
  4463. * normal click.
  4464. */
  4465. deselectAll();
  4466. }
  4467. toggleSelection();
  4468. } else if ((isSingleSelectMode() || isMultiSelectModeSimple())
  4469. && nullSelectionAllowed) {
  4470. toggleSelection();
  4471. }/*
  4472. * else NOP to avoid excessive server
  4473. * visits (selection is removed with
  4474. * CTRL/META click)
  4475. */
  4476. selectionRangeStart = this;
  4477. setRowFocus(this);
  4478. }
  4479. // Remove IE text selection hack
  4480. if (BrowserInfo.get().isIE()) {
  4481. ((Element) event.getEventTarget().cast())
  4482. .setPropertyJSO("onselectstart",
  4483. null);
  4484. }
  4485. // Queue value change
  4486. sendSelectedRows(false);
  4487. }
  4488. /*
  4489. * Send queued click and value change events if any
  4490. * If a click event is sent, send value change with
  4491. * it regardless of the immediate flag, see #7127
  4492. */
  4493. if (immediate || clickEventSent) {
  4494. client.sendPendingVariableChanges();
  4495. }
  4496. }
  4497. break;
  4498. case Event.ONTOUCHEND:
  4499. case Event.ONTOUCHCANCEL:
  4500. if (touchStart != null) {
  4501. /*
  4502. * Touch has not been handled as neither context or
  4503. * drag start, handle it as a click.
  4504. */
  4505. Util.simulateClickFromTouchEvent(touchStart, this);
  4506. touchStart = null;
  4507. }
  4508. if (contextTouchTimeout != null) {
  4509. contextTouchTimeout.cancel();
  4510. }
  4511. break;
  4512. case Event.ONTOUCHMOVE:
  4513. if (isSignificantMove(event)) {
  4514. /*
  4515. * TODO figure out scroll delegate don't eat events
  4516. * if row is selected. Null check for active
  4517. * delegate is as a workaround.
  4518. */
  4519. if (dragmode != 0
  4520. && touchStart != null
  4521. && (TouchScrollDelegate
  4522. .getActiveScrollDelegate() == null)) {
  4523. startRowDrag(touchStart, type, targetTdOrTr);
  4524. }
  4525. if (contextTouchTimeout != null) {
  4526. contextTouchTimeout.cancel();
  4527. }
  4528. /*
  4529. * Avoid clicks and drags by clearing touch start
  4530. * flag.
  4531. */
  4532. touchStart = null;
  4533. }
  4534. break;
  4535. case Event.ONTOUCHSTART:
  4536. touchStart = event;
  4537. Touch touch = event.getChangedTouches().get(0);
  4538. // save position to fields, touches in events are same
  4539. // isntance during the operation.
  4540. touchStartX = touch.getClientX();
  4541. touchStartY = touch.getClientY();
  4542. /*
  4543. * Prevent simulated mouse events.
  4544. */
  4545. touchStart.preventDefault();
  4546. if (dragmode != 0 || actionKeys != null) {
  4547. new Timer() {
  4548. @Override
  4549. public void run() {
  4550. TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
  4551. .getActiveScrollDelegate();
  4552. if (activeScrollDelegate != null
  4553. && !activeScrollDelegate.isMoved()) {
  4554. /*
  4555. * scrolling hasn't started. Cancel
  4556. * scrolling and let row handle this as
  4557. * drag start or context menu.
  4558. */
  4559. activeScrollDelegate.stopScrolling();
  4560. } else {
  4561. /*
  4562. * Scrolled or scrolling, clear touch
  4563. * start to indicate that row shouldn't
  4564. * handle touch move/end events.
  4565. */
  4566. touchStart = null;
  4567. }
  4568. }
  4569. }.schedule(TOUCHSCROLL_TIMEOUT);
  4570. if (contextTouchTimeout == null
  4571. && actionKeys != null) {
  4572. contextTouchTimeout = new Timer() {
  4573. @Override
  4574. public void run() {
  4575. if (touchStart != null) {
  4576. showContextMenu(touchStart);
  4577. touchStart = null;
  4578. }
  4579. }
  4580. };
  4581. }
  4582. contextTouchTimeout.cancel();
  4583. contextTouchTimeout
  4584. .schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  4585. }
  4586. break;
  4587. case Event.ONMOUSEDOWN:
  4588. if (targetCellOrRowFound) {
  4589. setRowFocus(this);
  4590. ensureFocus();
  4591. if (dragmode != 0
  4592. && (event.getButton() == NativeEvent.BUTTON_LEFT)) {
  4593. startRowDrag(event, type, targetTdOrTr);
  4594. } else if (event.getCtrlKey()
  4595. || event.getShiftKey()
  4596. || event.getMetaKey()
  4597. && isMultiSelectModeDefault()) {
  4598. // Prevent default text selection in Firefox
  4599. event.preventDefault();
  4600. // Prevent default text selection in IE
  4601. if (BrowserInfo.get().isIE()) {
  4602. ((Element) event.getEventTarget().cast())
  4603. .setPropertyJSO(
  4604. "onselectstart",
  4605. getPreventTextSelectionIEHack());
  4606. }
  4607. event.stopPropagation();
  4608. }
  4609. }
  4610. break;
  4611. case Event.ONMOUSEOUT:
  4612. if (targetCellOrRowFound) {
  4613. mDown = false;
  4614. }
  4615. break;
  4616. default:
  4617. break;
  4618. }
  4619. }
  4620. super.onBrowserEvent(event);
  4621. }
  4622. private boolean isSignificantMove(Event event) {
  4623. if (touchStart == null) {
  4624. // no touch start
  4625. return false;
  4626. }
  4627. /*
  4628. * TODO calculate based on real distance instead of separate
  4629. * axis checks
  4630. */
  4631. Touch touch = event.getChangedTouches().get(0);
  4632. if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  4633. return true;
  4634. }
  4635. if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  4636. return true;
  4637. }
  4638. return false;
  4639. }
  4640. protected void startRowDrag(Event event, final int type,
  4641. Element targetTdOrTr) {
  4642. mDown = true;
  4643. VTransferable transferable = new VTransferable();
  4644. transferable.setDragSource(VScrollTable.this);
  4645. transferable.setData("itemId", "" + rowKey);
  4646. NodeList<TableCellElement> cells = rowElement.getCells();
  4647. for (int i = 0; i < cells.getLength(); i++) {
  4648. if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
  4649. HeaderCell headerCell = tHead.getHeaderCell(i);
  4650. transferable.setData("propertyId", headerCell.cid);
  4651. break;
  4652. }
  4653. }
  4654. VDragEvent ev = VDragAndDropManager.get().startDrag(
  4655. transferable, event, true);
  4656. if (dragmode == DRAGMODE_MULTIROW && isMultiSelectModeAny()
  4657. && selectedRowKeys.contains("" + rowKey)) {
  4658. ev.createDragImage(
  4659. (Element) scrollBody.tBodyElement.cast(), true);
  4660. Element dragImage = ev.getDragImage();
  4661. int i = 0;
  4662. for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
  4663. .hasNext();) {
  4664. VScrollTableRow next = (VScrollTableRow) iterator
  4665. .next();
  4666. Element child = (Element) dragImage.getChild(i++);
  4667. if (!selectedRowKeys.contains("" + next.rowKey)) {
  4668. child.getStyle().setVisibility(Visibility.HIDDEN);
  4669. }
  4670. }
  4671. } else {
  4672. ev.createDragImage(getElement(), true);
  4673. }
  4674. if (type == Event.ONMOUSEDOWN) {
  4675. event.preventDefault();
  4676. }
  4677. event.stopPropagation();
  4678. }
  4679. /**
  4680. * Finds the TD that the event interacts with. Returns null if the
  4681. * target of the event should not be handled. If the event target is
  4682. * the row directly this method returns the TR element instead of
  4683. * the TD.
  4684. *
  4685. * @param event
  4686. * @return TD or TR element that the event targets (the actual event
  4687. * target is this element or a child of it)
  4688. */
  4689. private Element getEventTargetTdOrTr(Event event) {
  4690. final Element eventTarget = event.getEventTarget().cast();
  4691. Widget widget = Util.findWidget(eventTarget, null);
  4692. final Element thisTrElement = getElement();
  4693. if (widget != this) {
  4694. /*
  4695. * This is a workaround to make Labels, read only TextFields
  4696. * and Embedded in a Table clickable (see #2688). It is
  4697. * really not a fix as it does not work with a custom read
  4698. * only components (not extending VLabel/VEmbedded).
  4699. */
  4700. while (widget != null && widget.getParent() != this) {
  4701. widget = widget.getParent();
  4702. }
  4703. if (!(widget instanceof VLabel)
  4704. && !(widget instanceof VEmbedded)
  4705. && !(widget instanceof VTextField && ((VTextField) widget)
  4706. .isReadOnly())) {
  4707. return null;
  4708. }
  4709. }
  4710. if (eventTarget == thisTrElement) {
  4711. // This was a click on the TR element
  4712. return thisTrElement;
  4713. }
  4714. // Iterate upwards until we find the TR element
  4715. Element element = eventTarget;
  4716. while (element != null
  4717. && element.getParentElement().cast() != thisTrElement) {
  4718. element = element.getParentElement().cast();
  4719. }
  4720. return element;
  4721. }
  4722. public void showContextMenu(Event event) {
  4723. if (enabled && actionKeys != null) {
  4724. // Show context menu if there are registered action handlers
  4725. int left = Util.getTouchOrMouseClientX(event);
  4726. int top = Util.getTouchOrMouseClientY(event);
  4727. top += Window.getScrollTop();
  4728. left += Window.getScrollLeft();
  4729. client.getContextMenu().showAt(this, left, top);
  4730. }
  4731. }
  4732. /**
  4733. * Has the row been selected?
  4734. *
  4735. * @return Returns true if selected, else false
  4736. */
  4737. public boolean isSelected() {
  4738. return selected;
  4739. }
  4740. /**
  4741. * Toggle the selection of the row
  4742. */
  4743. public void toggleSelection() {
  4744. selected = !selected;
  4745. selectionChanged = true;
  4746. if (selected) {
  4747. selectedRowKeys.add(String.valueOf(rowKey));
  4748. addStyleName("v-selected");
  4749. } else {
  4750. removeStyleName("v-selected");
  4751. selectedRowKeys.remove(String.valueOf(rowKey));
  4752. }
  4753. }
  4754. /**
  4755. * Is called when a user clicks an item when holding SHIFT key down.
  4756. * This will select a new range from the last focused row
  4757. *
  4758. * @param deselectPrevious
  4759. * Should the previous selected range be deselected
  4760. */
  4761. private void toggleShiftSelection(boolean deselectPrevious) {
  4762. /*
  4763. * Ensures that we are in multiselect mode and that we have a
  4764. * previous selection which was not a deselection
  4765. */
  4766. if (isSingleSelectMode()) {
  4767. // No previous selection found
  4768. deselectAll();
  4769. toggleSelection();
  4770. return;
  4771. }
  4772. // Set the selectable range
  4773. VScrollTableRow endRow = this;
  4774. VScrollTableRow startRow = selectionRangeStart;
  4775. if (startRow == null) {
  4776. startRow = focusedRow;
  4777. // If start row is null then we have a multipage selection
  4778. // from
  4779. // above
  4780. if (startRow == null) {
  4781. startRow = (VScrollTableRow) scrollBody.iterator()
  4782. .next();
  4783. setRowFocus(endRow);
  4784. }
  4785. }
  4786. // Deselect previous items if so desired
  4787. if (deselectPrevious) {
  4788. deselectAll();
  4789. }
  4790. // we'll ensure GUI state from top down even though selection
  4791. // was the opposite way
  4792. if (!startRow.isBefore(endRow)) {
  4793. VScrollTableRow tmp = startRow;
  4794. startRow = endRow;
  4795. endRow = tmp;
  4796. }
  4797. SelectionRange range = new SelectionRange(startRow, endRow);
  4798. for (Widget w : scrollBody) {
  4799. VScrollTableRow row = (VScrollTableRow) w;
  4800. if (range.inRange(row)) {
  4801. if (!row.isSelected()) {
  4802. row.toggleSelection();
  4803. }
  4804. selectedRowKeys.add(row.getKey());
  4805. }
  4806. }
  4807. // Add range
  4808. if (startRow != endRow) {
  4809. selectedRowRanges.add(range);
  4810. }
  4811. }
  4812. /*
  4813. * (non-Javadoc)
  4814. *
  4815. * @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
  4816. */
  4817. public Action[] getActions() {
  4818. if (actionKeys == null) {
  4819. return new Action[] {};
  4820. }
  4821. final Action[] actions = new Action[actionKeys.length];
  4822. for (int i = 0; i < actions.length; i++) {
  4823. final String actionKey = actionKeys[i];
  4824. final TreeAction a = new TreeAction(this,
  4825. String.valueOf(rowKey), actionKey) {
  4826. @Override
  4827. public void execute() {
  4828. super.execute();
  4829. lazyRevertFocusToRow(VScrollTableRow.this);
  4830. }
  4831. };
  4832. a.setCaption(getActionCaption(actionKey));
  4833. a.setIconUrl(getActionIcon(actionKey));
  4834. actions[i] = a;
  4835. }
  4836. return actions;
  4837. }
  4838. public ApplicationConnection getClient() {
  4839. return client;
  4840. }
  4841. public String getPaintableId() {
  4842. return paintableId;
  4843. }
  4844. public RenderSpace getAllocatedSpace(Widget child) {
  4845. int w = 0;
  4846. int i = getColIndexOf(child);
  4847. HeaderCell headerCell = tHead.getHeaderCell(i);
  4848. if (headerCell != null) {
  4849. if (initializedAndAttached) {
  4850. w = headerCell.getWidth();
  4851. } else {
  4852. // header offset width is not absolutely correct value,
  4853. // but a best guess (expecting similar content in all
  4854. // columns ->
  4855. // if one component is relative width so are others)
  4856. w = headerCell.getOffsetWidth() - getCellExtraWidth();
  4857. }
  4858. }
  4859. return new RenderSpace(w, 0) {
  4860. @Override
  4861. public int getHeight() {
  4862. return (int) getRowHeight();
  4863. }
  4864. };
  4865. }
  4866. private int getColIndexOf(Widget child) {
  4867. com.google.gwt.dom.client.Element widgetCell = child
  4868. .getElement().getParentElement().getParentElement();
  4869. NodeList<TableCellElement> cells = rowElement.getCells();
  4870. for (int i = 0; i < cells.getLength(); i++) {
  4871. if (cells.getItem(i) == widgetCell) {
  4872. return i;
  4873. }
  4874. }
  4875. return -1;
  4876. }
  4877. public boolean hasChildComponent(Widget component) {
  4878. return childWidgets.contains(component);
  4879. }
  4880. public void replaceChildComponent(Widget oldComponent,
  4881. Widget newComponent) {
  4882. com.google.gwt.dom.client.Element parentElement = oldComponent
  4883. .getElement().getParentElement();
  4884. int index = childWidgets.indexOf(oldComponent);
  4885. oldComponent.removeFromParent();
  4886. parentElement.appendChild(newComponent.getElement());
  4887. childWidgets.add(index, newComponent);
  4888. adopt(newComponent);
  4889. }
  4890. public boolean requestLayout(Set<Widget> children) {
  4891. // row size should never change and system wouldn't event
  4892. // survive as this is a kind of fake paitable
  4893. return true;
  4894. }
  4895. public void updateCaption(VPaintableWidget component, UIDL uidl) {
  4896. // NOP, not rendered
  4897. }
  4898. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  4899. // Should never be called,
  4900. // Component container interface faked here to get layouts
  4901. // render properly
  4902. }
  4903. public Widget getWidgetForPaintable() {
  4904. return this;
  4905. }
  4906. }
  4907. protected class VScrollTableGeneratedRow extends VScrollTableRow {
  4908. private boolean spanColumns;
  4909. private boolean htmlContentAllowed;
  4910. public VScrollTableGeneratedRow(UIDL uidl, char[] aligns) {
  4911. super(uidl, aligns);
  4912. addStyleName("v-table-generated-row");
  4913. }
  4914. public boolean isSpanColumns() {
  4915. return spanColumns;
  4916. }
  4917. @Override
  4918. protected void initCellWidths() {
  4919. if (spanColumns) {
  4920. setSpannedColumnWidthAfterDOMFullyInited();
  4921. } else {
  4922. super.initCellWidths();
  4923. }
  4924. }
  4925. private void setSpannedColumnWidthAfterDOMFullyInited() {
  4926. // Defer setting width on spanned columns to make sure that
  4927. // they are added to the DOM before trying to calculate
  4928. // widths.
  4929. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  4930. public void execute() {
  4931. if (showRowHeaders) {
  4932. setCellWidth(0, tHead.getHeaderCell(0).getWidth());
  4933. calcAndSetSpanWidthOnCell(1);
  4934. } else {
  4935. calcAndSetSpanWidthOnCell(0);
  4936. }
  4937. }
  4938. });
  4939. }
  4940. @Override
  4941. protected boolean isRenderHtmlInCells() {
  4942. return htmlContentAllowed;
  4943. }
  4944. @Override
  4945. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  4946. int visibleColumnIndex) {
  4947. htmlContentAllowed = uidl.getBooleanAttribute("gen_html");
  4948. spanColumns = uidl.getBooleanAttribute("gen_span");
  4949. final Iterator<?> cells = uidl.getChildIterator();
  4950. if (spanColumns) {
  4951. int colCount = uidl.getChildCount();
  4952. if (cells.hasNext()) {
  4953. final Object cell = cells.next();
  4954. if (cell instanceof String) {
  4955. addSpannedCell(uidl, cell.toString(), aligns[0],
  4956. "", htmlContentAllowed, false, null,
  4957. colCount);
  4958. } else {
  4959. addSpannedCell(uidl, (Widget) cell, aligns[0], "",
  4960. false, colCount);
  4961. }
  4962. }
  4963. } else {
  4964. super.addCellsFromUIDL(uidl, aligns, col,
  4965. visibleColumnIndex);
  4966. }
  4967. }
  4968. private void addSpannedCell(UIDL rowUidl, Widget w, char align,
  4969. String style, boolean sorted, int colCount) {
  4970. TableCellElement td = DOM.createTD().cast();
  4971. td.setColSpan(colCount);
  4972. initCellWithWidget(w, align, style, sorted, td);
  4973. }
  4974. private void addSpannedCell(UIDL rowUidl, String text, char align,
  4975. String style, boolean textIsHTML, boolean sorted,
  4976. String description, int colCount) {
  4977. // String only content is optimized by not using Label widget
  4978. final TableCellElement td = DOM.createTD().cast();
  4979. td.setColSpan(colCount);
  4980. initCellWithText(text, align, style, textIsHTML, sorted,
  4981. description, td);
  4982. }
  4983. @Override
  4984. protected void setCellWidth(int cellIx, int width) {
  4985. if (isSpanColumns()) {
  4986. if (showRowHeaders) {
  4987. if (cellIx == 0) {
  4988. super.setCellWidth(0, width);
  4989. } else {
  4990. // We need to recalculate the spanning TDs width for
  4991. // every cellIx in order to support column resizing.
  4992. calcAndSetSpanWidthOnCell(1);
  4993. }
  4994. } else {
  4995. // Same as above.
  4996. calcAndSetSpanWidthOnCell(0);
  4997. }
  4998. } else {
  4999. super.setCellWidth(cellIx, width);
  5000. }
  5001. }
  5002. private void calcAndSetSpanWidthOnCell(final int cellIx) {
  5003. int spanWidth = 0;
  5004. for (int ix = (showRowHeaders ? 1 : 0); ix < tHead
  5005. .getVisibleCellCount(); ix++) {
  5006. spanWidth += tHead.getHeaderCell(ix).getOffsetWidth();
  5007. }
  5008. Util.setWidthExcludingPaddingAndBorder((Element) getElement()
  5009. .getChild(cellIx), spanWidth, 13, false);
  5010. }
  5011. }
  5012. /**
  5013. * Ensure the component has a focus.
  5014. *
  5015. * TODO the current implementation simply always calls focus for the
  5016. * component. In case the Table at some point implements focus/blur
  5017. * listeners, this method needs to be evolved to conditionally call
  5018. * focus only if not currently focused.
  5019. */
  5020. protected void ensureFocus() {
  5021. if (!hasFocus) {
  5022. scrollBodyPanel.setFocus(true);
  5023. }
  5024. }
  5025. }
  5026. /**
  5027. * Deselects all items
  5028. */
  5029. public void deselectAll() {
  5030. for (Widget w : scrollBody) {
  5031. VScrollTableRow row = (VScrollTableRow) w;
  5032. if (row.isSelected()) {
  5033. row.toggleSelection();
  5034. }
  5035. }
  5036. // still ensure all selects are removed from (not necessary rendered)
  5037. selectedRowKeys.clear();
  5038. selectedRowRanges.clear();
  5039. // also notify server that it clears all previous selections (the client
  5040. // side does not know about the invisible ones)
  5041. instructServerToForgetPreviousSelections();
  5042. }
  5043. /**
  5044. * Used in multiselect mode when the client side knows that all selections
  5045. * are in the next request.
  5046. */
  5047. private void instructServerToForgetPreviousSelections() {
  5048. client.updateVariable(paintableId, "clearSelections", true, false);
  5049. }
  5050. /**
  5051. * Determines the pagelength when the table height is fixed.
  5052. */
  5053. public void updatePageLength() {
  5054. // Only update if visible and enabled
  5055. if (!isVisible() || !enabled) {
  5056. return;
  5057. }
  5058. if (scrollBody == null) {
  5059. return;
  5060. }
  5061. if (height == null || height.equals("")) {
  5062. return;
  5063. }
  5064. int rowHeight = (int) Math.round(scrollBody.getRowHeight());
  5065. int bodyH = scrollBodyPanel.getOffsetHeight();
  5066. int rowsAtOnce = bodyH / rowHeight;
  5067. boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
  5068. if (anotherPartlyVisible) {
  5069. rowsAtOnce++;
  5070. }
  5071. if (pageLength != rowsAtOnce) {
  5072. pageLength = rowsAtOnce;
  5073. client.updateVariable(paintableId, "pagelength", pageLength, false);
  5074. if (!rendering) {
  5075. int currentlyVisible = scrollBody.lastRendered
  5076. - scrollBody.firstRendered;
  5077. if (currentlyVisible < pageLength
  5078. && currentlyVisible < totalRows) {
  5079. // shake scrollpanel to fill empty space
  5080. scrollBodyPanel.setScrollPosition(scrollTop + 1);
  5081. scrollBodyPanel.setScrollPosition(scrollTop - 1);
  5082. }
  5083. }
  5084. }
  5085. }
  5086. @Override
  5087. public void setWidth(String width) {
  5088. if (this.width.equals(width)) {
  5089. return;
  5090. }
  5091. if (!isVisible()) {
  5092. /*
  5093. * Do not update size when the table is hidden as all column widths
  5094. * will be set to zero and they won't be recalculated when the table
  5095. * is set visible again (until the size changes again)
  5096. */
  5097. return;
  5098. }
  5099. this.width = width;
  5100. if (width != null && !"".equals(width)) {
  5101. super.setWidth(width);
  5102. int innerPixels = getOffsetWidth() - getBorderWidth();
  5103. if (innerPixels < 0) {
  5104. innerPixels = 0;
  5105. }
  5106. setContentWidth(innerPixels);
  5107. // readjust undefined width columns
  5108. triggerLazyColumnAdjustment(false);
  5109. } else {
  5110. // Undefined width
  5111. super.setWidth("");
  5112. // Readjust size of table
  5113. sizeInit();
  5114. // readjust undefined width columns
  5115. triggerLazyColumnAdjustment(false);
  5116. }
  5117. /*
  5118. * setting width may affect wheter the component has scrollbars -> needs
  5119. * scrolling or not
  5120. */
  5121. setProperTabIndex();
  5122. }
  5123. private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
  5124. private final Timer lazyAdjustColumnWidths = new Timer() {
  5125. /**
  5126. * Check for column widths, and available width, to see if we can fix
  5127. * column widths "optimally". Doing this lazily to avoid expensive
  5128. * calculation when resizing is not yet finished.
  5129. */
  5130. @Override
  5131. public void run() {
  5132. if (scrollBody == null) {
  5133. // Try again later if we get here before scrollBody has been
  5134. // initalized
  5135. triggerLazyColumnAdjustment(false);
  5136. return;
  5137. }
  5138. Iterator<Widget> headCells = tHead.iterator();
  5139. int usedMinimumWidth = 0;
  5140. int totalExplicitColumnsWidths = 0;
  5141. float expandRatioDivider = 0;
  5142. int colIndex = 0;
  5143. while (headCells.hasNext()) {
  5144. final HeaderCell hCell = (HeaderCell) headCells.next();
  5145. if (hCell.isDefinedWidth()) {
  5146. totalExplicitColumnsWidths += hCell.getWidth();
  5147. usedMinimumWidth += hCell.getWidth();
  5148. } else {
  5149. usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
  5150. expandRatioDivider += hCell.getExpandRatio();
  5151. }
  5152. colIndex++;
  5153. }
  5154. int availW = scrollBody.getAvailableWidth();
  5155. // Hey IE, are you really sure about this?
  5156. availW = scrollBody.getAvailableWidth();
  5157. int visibleCellCount = tHead.getVisibleCellCount();
  5158. availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
  5159. if (willHaveScrollbars()) {
  5160. availW -= Util.getNativeScrollbarSize();
  5161. }
  5162. int extraSpace = availW - usedMinimumWidth;
  5163. if (extraSpace < 0) {
  5164. extraSpace = 0;
  5165. }
  5166. int totalUndefinedNaturalWidths = usedMinimumWidth
  5167. - totalExplicitColumnsWidths;
  5168. // we have some space that can be divided optimally
  5169. HeaderCell hCell;
  5170. colIndex = 0;
  5171. headCells = tHead.iterator();
  5172. int checksum = 0;
  5173. while (headCells.hasNext()) {
  5174. hCell = (HeaderCell) headCells.next();
  5175. if (!hCell.isDefinedWidth()) {
  5176. int w = hCell.getNaturalColumnWidth(colIndex);
  5177. int newSpace;
  5178. if (expandRatioDivider > 0) {
  5179. // divide excess space by expand ratios
  5180. newSpace = Math.round((w + extraSpace
  5181. * hCell.getExpandRatio() / expandRatioDivider));
  5182. } else {
  5183. if (totalUndefinedNaturalWidths != 0) {
  5184. // divide relatively to natural column widths
  5185. newSpace = Math.round(w + (float) extraSpace
  5186. * (float) w / totalUndefinedNaturalWidths);
  5187. } else {
  5188. newSpace = w;
  5189. }
  5190. }
  5191. checksum += newSpace;
  5192. setColWidth(colIndex, newSpace, false);
  5193. } else {
  5194. checksum += hCell.getWidth();
  5195. }
  5196. colIndex++;
  5197. }
  5198. if (extraSpace > 0 && checksum != availW) {
  5199. /*
  5200. * There might be in some cases a rounding error of 1px when
  5201. * extra space is divided so if there is one then we give the
  5202. * first undefined column 1 more pixel
  5203. */
  5204. headCells = tHead.iterator();
  5205. colIndex = 0;
  5206. while (headCells.hasNext()) {
  5207. HeaderCell hc = (HeaderCell) headCells.next();
  5208. if (!hc.isDefinedWidth()) {
  5209. setColWidth(colIndex,
  5210. hc.getWidth() + availW - checksum, false);
  5211. break;
  5212. }
  5213. colIndex++;
  5214. }
  5215. }
  5216. if ((height == null || "".equals(height))
  5217. && totalRows == pageLength) {
  5218. // fix body height (may vary if lazy loading is offhorizontal
  5219. // scrollbar appears/disappears)
  5220. int bodyHeight = scrollBody.getRequiredHeight();
  5221. boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
  5222. if (needsSpaceForHorizontalScrollbar) {
  5223. bodyHeight += Util.getNativeScrollbarSize();
  5224. }
  5225. int heightBefore = getOffsetHeight();
  5226. scrollBodyPanel.setHeight(bodyHeight + "px");
  5227. if (heightBefore != getOffsetHeight()) {
  5228. Util.notifyParentOfSizeChange(VScrollTable.this, false);
  5229. }
  5230. }
  5231. scrollBody.reLayoutComponents();
  5232. Scheduler.get().scheduleDeferred(new Command() {
  5233. public void execute() {
  5234. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  5235. }
  5236. });
  5237. forceRealignColumnHeaders();
  5238. }
  5239. };
  5240. private void forceRealignColumnHeaders() {
  5241. if (BrowserInfo.get().isIE()) {
  5242. /*
  5243. * IE does not fire onscroll event if scroll position is reverted to
  5244. * 0 due to the content element size growth. Ensure headers are in
  5245. * sync with content manually. Safe to use null event as we don't
  5246. * actually use the event object in listener.
  5247. */
  5248. onScroll(null);
  5249. }
  5250. }
  5251. /**
  5252. * helper to set pixel size of head and body part
  5253. *
  5254. * @param pixels
  5255. */
  5256. private void setContentWidth(int pixels) {
  5257. tHead.setWidth(pixels + "px");
  5258. scrollBodyPanel.setWidth(pixels + "px");
  5259. tFoot.setWidth(pixels + "px");
  5260. }
  5261. private int borderWidth = -1;
  5262. /**
  5263. * @return border left + border right
  5264. */
  5265. private int getBorderWidth() {
  5266. if (borderWidth < 0) {
  5267. borderWidth = Util.measureHorizontalPaddingAndBorder(
  5268. scrollBodyPanel.getElement(), 2);
  5269. if (borderWidth < 0) {
  5270. borderWidth = 0;
  5271. }
  5272. }
  5273. return borderWidth;
  5274. }
  5275. /**
  5276. * Ensures scrollable area is properly sized. This method is used when fixed
  5277. * size is used.
  5278. */
  5279. private int containerHeight;
  5280. private void setContainerHeight() {
  5281. if (height != null && !"".equals(height)) {
  5282. containerHeight = getOffsetHeight();
  5283. containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
  5284. containerHeight -= tFoot.getOffsetHeight();
  5285. containerHeight -= getContentAreaBorderHeight();
  5286. if (containerHeight < 0) {
  5287. containerHeight = 0;
  5288. }
  5289. scrollBodyPanel.setHeight(containerHeight + "px");
  5290. }
  5291. }
  5292. private int contentAreaBorderHeight = -1;
  5293. private int scrollLeft;
  5294. private int scrollTop;
  5295. private VScrollTableDropHandler dropHandler;
  5296. private boolean navKeyDown;
  5297. private boolean multiselectPending;
  5298. /**
  5299. * @return border top + border bottom of the scrollable area of table
  5300. */
  5301. private int getContentAreaBorderHeight() {
  5302. if (contentAreaBorderHeight < 0) {
  5303. DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
  5304. "hidden");
  5305. int oh = scrollBodyPanel.getOffsetHeight();
  5306. int ch = scrollBodyPanel.getElement()
  5307. .getPropertyInt("clientHeight");
  5308. contentAreaBorderHeight = oh - ch;
  5309. DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
  5310. "auto");
  5311. }
  5312. return contentAreaBorderHeight;
  5313. }
  5314. @Override
  5315. public void setHeight(String height) {
  5316. this.height = height;
  5317. super.setHeight(height);
  5318. setContainerHeight();
  5319. if (initializedAndAttached) {
  5320. updatePageLength();
  5321. }
  5322. if (!rendering) {
  5323. // Webkit may sometimes get an odd rendering bug (white space
  5324. // between header and body), see bug #3875. Running
  5325. // overflow hack here to shake body element a bit.
  5326. Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  5327. }
  5328. /*
  5329. * setting height may affect wheter the component has scrollbars ->
  5330. * needs scrolling or not
  5331. */
  5332. setProperTabIndex();
  5333. }
  5334. /*
  5335. * Overridden due Table might not survive of visibility change (scroll pos
  5336. * lost). Example ITabPanel just set contained components invisible and back
  5337. * when changing tabs.
  5338. */
  5339. @Override
  5340. public void setVisible(boolean visible) {
  5341. if (isVisible() != visible) {
  5342. super.setVisible(visible);
  5343. if (initializedAndAttached) {
  5344. if (visible) {
  5345. Scheduler.get().scheduleDeferred(new Command() {
  5346. public void execute() {
  5347. scrollBodyPanel
  5348. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  5349. }
  5350. });
  5351. }
  5352. }
  5353. }
  5354. }
  5355. /**
  5356. * Helper function to build html snippet for column or row headers
  5357. *
  5358. * @param uidl
  5359. * possibly with values caption and icon
  5360. * @return html snippet containing possibly an icon + caption text
  5361. */
  5362. protected String buildCaptionHtmlSnippet(UIDL uidl) {
  5363. String s = uidl.hasAttribute("caption") ? uidl
  5364. .getStringAttribute("caption") : "";
  5365. if (uidl.hasAttribute("icon")) {
  5366. s = "<img src=\""
  5367. + Util.escapeAttribute(client.translateVaadinUri(uidl
  5368. .getStringAttribute("icon")))
  5369. + "\" alt=\"icon\" class=\"v-icon\">" + s;
  5370. }
  5371. return s;
  5372. }
  5373. /**
  5374. * This method has logic which rows needs to be requested from server when
  5375. * user scrolls
  5376. */
  5377. public void onScroll(ScrollEvent event) {
  5378. scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
  5379. scrollTop = scrollBodyPanel.getScrollPosition();
  5380. if (!initializedAndAttached) {
  5381. return;
  5382. }
  5383. if (!enabled) {
  5384. scrollBodyPanel
  5385. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  5386. return;
  5387. }
  5388. rowRequestHandler.cancel();
  5389. if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
  5390. // due to the webkitoverflowworkaround, top may sometimes report 0
  5391. // for webkit, although it really is not. Expecting to have the
  5392. // correct
  5393. // value available soon.
  5394. Scheduler.get().scheduleDeferred(new Command() {
  5395. public void execute() {
  5396. onScroll(null);
  5397. }
  5398. });
  5399. return;
  5400. }
  5401. // fix headers horizontal scrolling
  5402. tHead.setHorizontalScrollPosition(scrollLeft);
  5403. // fix footers horizontal scrolling
  5404. tFoot.setHorizontalScrollPosition(scrollLeft);
  5405. firstRowInViewPort = calcFirstRowInViewPort();
  5406. if (firstRowInViewPort > totalRows - pageLength) {
  5407. firstRowInViewPort = totalRows - pageLength;
  5408. }
  5409. int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
  5410. * cache_react_rate);
  5411. if (postLimit > totalRows - 1) {
  5412. postLimit = totalRows - 1;
  5413. }
  5414. int preLimit = (int) (firstRowInViewPort - pageLength
  5415. * cache_react_rate);
  5416. if (preLimit < 0) {
  5417. preLimit = 0;
  5418. }
  5419. final int lastRendered = scrollBody.getLastRendered();
  5420. final int firstRendered = scrollBody.getFirstRendered();
  5421. if (postLimit <= lastRendered && preLimit >= firstRendered) {
  5422. // we're within no-react area, no need to request more rows
  5423. // remember which firstvisible we requested, in case the server has
  5424. // a differing opinion
  5425. lastRequestedFirstvisible = firstRowInViewPort;
  5426. client.updateVariable(paintableId, "firstvisible",
  5427. firstRowInViewPort, false);
  5428. return;
  5429. }
  5430. if (firstRowInViewPort - pageLength * cache_rate > lastRendered
  5431. || firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
  5432. // need a totally new set of rows
  5433. rowRequestHandler
  5434. .setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
  5435. int last = firstRowInViewPort + (int) (cache_rate * pageLength)
  5436. + pageLength - 1;
  5437. if (last >= totalRows) {
  5438. last = totalRows - 1;
  5439. }
  5440. rowRequestHandler.setReqRows(last
  5441. - rowRequestHandler.getReqFirstRow() + 1);
  5442. rowRequestHandler.deferRowFetch();
  5443. return;
  5444. }
  5445. if (preLimit < firstRendered) {
  5446. // need some rows to the beginning of the rendered area
  5447. rowRequestHandler
  5448. .setReqFirstRow((int) (firstRowInViewPort - pageLength
  5449. * cache_rate));
  5450. rowRequestHandler.setReqRows(firstRendered
  5451. - rowRequestHandler.getReqFirstRow());
  5452. rowRequestHandler.deferRowFetch();
  5453. return;
  5454. }
  5455. if (postLimit > lastRendered) {
  5456. // need some rows to the end of the rendered area
  5457. rowRequestHandler.setReqFirstRow(lastRendered + 1);
  5458. rowRequestHandler.setReqRows((int) ((firstRowInViewPort
  5459. + pageLength + pageLength * cache_rate) - lastRendered));
  5460. rowRequestHandler.deferRowFetch();
  5461. }
  5462. }
  5463. protected int calcFirstRowInViewPort() {
  5464. return (int) Math.ceil(scrollTop / scrollBody.getRowHeight());
  5465. }
  5466. public VScrollTableDropHandler getDropHandler() {
  5467. return dropHandler;
  5468. }
  5469. private static class TableDDDetails {
  5470. int overkey = -1;
  5471. VerticalDropLocation dropLocation;
  5472. String colkey;
  5473. @Override
  5474. public boolean equals(Object obj) {
  5475. if (obj instanceof TableDDDetails) {
  5476. TableDDDetails other = (TableDDDetails) obj;
  5477. return dropLocation == other.dropLocation
  5478. && overkey == other.overkey
  5479. && ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
  5480. }
  5481. return false;
  5482. }
  5483. // @Override
  5484. // public int hashCode() {
  5485. // return overkey;
  5486. // }
  5487. }
  5488. public class VScrollTableDropHandler extends VAbstractDropHandler {
  5489. private static final String ROWSTYLEBASE = "v-table-row-drag-";
  5490. private TableDDDetails dropDetails;
  5491. private TableDDDetails lastEmphasized;
  5492. @Override
  5493. public void dragEnter(VDragEvent drag) {
  5494. updateDropDetails(drag);
  5495. super.dragEnter(drag);
  5496. }
  5497. private void updateDropDetails(VDragEvent drag) {
  5498. dropDetails = new TableDDDetails();
  5499. Element elementOver = drag.getElementOver();
  5500. VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
  5501. if (row != null) {
  5502. dropDetails.overkey = row.rowKey;
  5503. Element tr = row.getElement();
  5504. Element element = elementOver;
  5505. while (element != null && element.getParentElement() != tr) {
  5506. element = (Element) element.getParentElement();
  5507. }
  5508. int childIndex = DOM.getChildIndex(tr, element);
  5509. dropDetails.colkey = tHead.getHeaderCell(childIndex)
  5510. .getColKey();
  5511. dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
  5512. row.getElement(), drag.getCurrentGwtEvent(), 0.2);
  5513. }
  5514. drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
  5515. drag.getDropDetails().put(
  5516. "detail",
  5517. dropDetails.dropLocation != null ? dropDetails.dropLocation
  5518. .toString() : null);
  5519. }
  5520. private Class<? extends Widget> getRowClass() {
  5521. // get the row type this way to make dd work in derived
  5522. // implementations
  5523. return scrollBody.iterator().next().getClass();
  5524. }
  5525. @Override
  5526. public void dragOver(VDragEvent drag) {
  5527. TableDDDetails oldDetails = dropDetails;
  5528. updateDropDetails(drag);
  5529. if (!oldDetails.equals(dropDetails)) {
  5530. deEmphasis();
  5531. final TableDDDetails newDetails = dropDetails;
  5532. VAcceptCallback cb = new VAcceptCallback() {
  5533. public void accepted(VDragEvent event) {
  5534. if (newDetails.equals(dropDetails)) {
  5535. dragAccepted(event);
  5536. }
  5537. /*
  5538. * Else new target slot already defined, ignore
  5539. */
  5540. }
  5541. };
  5542. validate(cb, drag);
  5543. }
  5544. }
  5545. @Override
  5546. public void dragLeave(VDragEvent drag) {
  5547. deEmphasis();
  5548. super.dragLeave(drag);
  5549. }
  5550. @Override
  5551. public boolean drop(VDragEvent drag) {
  5552. deEmphasis();
  5553. return super.drop(drag);
  5554. }
  5555. private void deEmphasis() {
  5556. UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
  5557. if (lastEmphasized == null) {
  5558. return;
  5559. }
  5560. for (Widget w : scrollBody.renderedRows) {
  5561. VScrollTableRow row = (VScrollTableRow) w;
  5562. if (lastEmphasized != null
  5563. && row.rowKey == lastEmphasized.overkey) {
  5564. String stylename = ROWSTYLEBASE
  5565. + lastEmphasized.dropLocation.toString()
  5566. .toLowerCase();
  5567. VScrollTableRow.setStyleName(row.getElement(), stylename,
  5568. false);
  5569. lastEmphasized = null;
  5570. return;
  5571. }
  5572. }
  5573. }
  5574. /**
  5575. * TODO needs different drop modes ?? (on cells, on rows), now only
  5576. * supports rows
  5577. */
  5578. private void emphasis(TableDDDetails details) {
  5579. deEmphasis();
  5580. UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
  5581. // iterate old and new emphasized row
  5582. for (Widget w : scrollBody.renderedRows) {
  5583. VScrollTableRow row = (VScrollTableRow) w;
  5584. if (details != null && details.overkey == row.rowKey) {
  5585. String stylename = ROWSTYLEBASE
  5586. + details.dropLocation.toString().toLowerCase();
  5587. VScrollTableRow.setStyleName(row.getElement(), stylename,
  5588. true);
  5589. lastEmphasized = details;
  5590. return;
  5591. }
  5592. }
  5593. }
  5594. @Override
  5595. protected void dragAccepted(VDragEvent drag) {
  5596. emphasis(dropDetails);
  5597. }
  5598. @Override
  5599. public VPaintableWidget getPaintable() {
  5600. return VScrollTable.this;
  5601. }
  5602. public ApplicationConnection getApplicationConnection() {
  5603. return client;
  5604. }
  5605. }
  5606. protected VScrollTableRow getFocusedRow() {
  5607. return focusedRow;
  5608. }
  5609. /**
  5610. * Moves the selection head to a specific row
  5611. *
  5612. * @param row
  5613. * The row to where the selection head should move
  5614. * @return Returns true if focus was moved successfully, else false
  5615. */
  5616. protected boolean setRowFocus(VScrollTableRow row) {
  5617. if (!isSelectable()) {
  5618. return false;
  5619. }
  5620. // Remove previous selection
  5621. if (focusedRow != null && focusedRow != row) {
  5622. focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
  5623. }
  5624. if (row != null) {
  5625. // Apply focus style to new selection
  5626. row.addStyleName(CLASSNAME_SELECTION_FOCUS);
  5627. /*
  5628. * Trying to set focus on already focused row
  5629. */
  5630. if (row == focusedRow) {
  5631. return false;
  5632. }
  5633. // Set new focused row
  5634. focusedRow = row;
  5635. ensureRowIsVisible(row);
  5636. return true;
  5637. }
  5638. return false;
  5639. }
  5640. /**
  5641. * Ensures that the row is visible
  5642. *
  5643. * @param row
  5644. * The row to ensure is visible
  5645. */
  5646. private void ensureRowIsVisible(VScrollTableRow row) {
  5647. Util.scrollIntoViewVertically(row.getElement());
  5648. }
  5649. /**
  5650. * Handles the keyboard events handled by the table
  5651. *
  5652. * @param event
  5653. * The keyboard event received
  5654. * @return true iff the navigation event was handled
  5655. */
  5656. protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  5657. if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
  5658. // Do not handle tab key
  5659. return false;
  5660. }
  5661. // Down navigation
  5662. if (!isSelectable() && keycode == getNavigationDownKey()) {
  5663. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  5664. .getScrollPosition() + scrollingVelocity);
  5665. return true;
  5666. } else if (keycode == getNavigationDownKey()) {
  5667. if (isMultiSelectModeAny() && moveFocusDown()) {
  5668. selectFocusedRow(ctrl, shift);
  5669. } else if (isSingleSelectMode() && !shift && moveFocusDown()) {
  5670. selectFocusedRow(ctrl, shift);
  5671. }
  5672. return true;
  5673. }
  5674. // Up navigation
  5675. if (!isSelectable() && keycode == getNavigationUpKey()) {
  5676. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  5677. .getScrollPosition() - scrollingVelocity);
  5678. return true;
  5679. } else if (keycode == getNavigationUpKey()) {
  5680. if (isMultiSelectModeAny() && moveFocusUp()) {
  5681. selectFocusedRow(ctrl, shift);
  5682. } else if (isSingleSelectMode() && !shift && moveFocusUp()) {
  5683. selectFocusedRow(ctrl, shift);
  5684. }
  5685. return true;
  5686. }
  5687. if (keycode == getNavigationLeftKey()) {
  5688. // Left navigation
  5689. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  5690. .getHorizontalScrollPosition() - scrollingVelocity);
  5691. return true;
  5692. } else if (keycode == getNavigationRightKey()) {
  5693. // Right navigation
  5694. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  5695. .getHorizontalScrollPosition() + scrollingVelocity);
  5696. return true;
  5697. }
  5698. // Select navigation
  5699. if (isSelectable() && keycode == getNavigationSelectKey()) {
  5700. if (isSingleSelectMode()) {
  5701. boolean wasSelected = focusedRow.isSelected();
  5702. deselectAll();
  5703. if (!wasSelected || !nullSelectionAllowed) {
  5704. focusedRow.toggleSelection();
  5705. }
  5706. } else {
  5707. focusedRow.toggleSelection();
  5708. removeRowFromUnsentSelectionRanges(focusedRow);
  5709. }
  5710. sendSelectedRows();
  5711. return true;
  5712. }
  5713. // Page Down navigation
  5714. if (keycode == getNavigationPageDownKey()) {
  5715. if (isSelectable()) {
  5716. /*
  5717. * If selectable we plagiate MSW behaviour: first scroll to the
  5718. * end of current view. If at the end, scroll down one page
  5719. * length and keep the selected row in the bottom part of
  5720. * visible area.
  5721. */
  5722. if (!isFocusAtTheEndOfTable()) {
  5723. VScrollTableRow lastVisibleRowInViewPort = scrollBody
  5724. .getRowByRowIndex(firstRowInViewPort
  5725. + getFullyVisibleRowCount() - 1);
  5726. if (lastVisibleRowInViewPort != null
  5727. && lastVisibleRowInViewPort != focusedRow) {
  5728. // focused row is not at the end of the table, move
  5729. // focus and select the last visible row
  5730. setRowFocus(lastVisibleRowInViewPort);
  5731. selectFocusedRow(ctrl, shift);
  5732. sendSelectedRows();
  5733. } else {
  5734. int indexOfToBeFocused = focusedRow.getIndex()
  5735. + getFullyVisibleRowCount();
  5736. if (indexOfToBeFocused >= totalRows) {
  5737. indexOfToBeFocused = totalRows - 1;
  5738. }
  5739. VScrollTableRow toBeFocusedRow = scrollBody
  5740. .getRowByRowIndex(indexOfToBeFocused);
  5741. if (toBeFocusedRow != null) {
  5742. /*
  5743. * if the next focused row is rendered
  5744. */
  5745. setRowFocus(toBeFocusedRow);
  5746. selectFocusedRow(ctrl, shift);
  5747. // TODO needs scrollintoview ?
  5748. sendSelectedRows();
  5749. } else {
  5750. // scroll down by pixels and return, to wait for
  5751. // new rows, then select the last item in the
  5752. // viewport
  5753. selectLastItemInNextRender = true;
  5754. multiselectPending = shift;
  5755. scrollByPagelenght(1);
  5756. }
  5757. }
  5758. }
  5759. } else {
  5760. /* No selections, go page down by scrolling */
  5761. scrollByPagelenght(1);
  5762. }
  5763. return true;
  5764. }
  5765. // Page Up navigation
  5766. if (keycode == getNavigationPageUpKey()) {
  5767. if (isSelectable()) {
  5768. /*
  5769. * If selectable we plagiate MSW behaviour: first scroll to the
  5770. * end of current view. If at the end, scroll down one page
  5771. * length and keep the selected row in the bottom part of
  5772. * visible area.
  5773. */
  5774. if (!isFocusAtTheBeginningOfTable()) {
  5775. VScrollTableRow firstVisibleRowInViewPort = scrollBody
  5776. .getRowByRowIndex(firstRowInViewPort);
  5777. if (firstVisibleRowInViewPort != null
  5778. && firstVisibleRowInViewPort != focusedRow) {
  5779. // focus is not at the beginning of the table, move
  5780. // focus and select the first visible row
  5781. setRowFocus(firstVisibleRowInViewPort);
  5782. selectFocusedRow(ctrl, shift);
  5783. sendSelectedRows();
  5784. } else {
  5785. int indexOfToBeFocused = focusedRow.getIndex()
  5786. - getFullyVisibleRowCount();
  5787. if (indexOfToBeFocused < 0) {
  5788. indexOfToBeFocused = 0;
  5789. }
  5790. VScrollTableRow toBeFocusedRow = scrollBody
  5791. .getRowByRowIndex(indexOfToBeFocused);
  5792. if (toBeFocusedRow != null) { // if the next focused row
  5793. // is rendered
  5794. setRowFocus(toBeFocusedRow);
  5795. selectFocusedRow(ctrl, shift);
  5796. // TODO needs scrollintoview ?
  5797. sendSelectedRows();
  5798. } else {
  5799. // unless waiting for the next rowset already
  5800. // scroll down by pixels and return, to wait for
  5801. // new rows, then select the last item in the
  5802. // viewport
  5803. selectFirstItemInNextRender = true;
  5804. multiselectPending = shift;
  5805. scrollByPagelenght(-1);
  5806. }
  5807. }
  5808. }
  5809. } else {
  5810. /* No selections, go page up by scrolling */
  5811. scrollByPagelenght(-1);
  5812. }
  5813. return true;
  5814. }
  5815. // Goto start navigation
  5816. if (keycode == getNavigationStartKey()) {
  5817. scrollBodyPanel.setScrollPosition(0);
  5818. if (isSelectable()) {
  5819. if (focusedRow != null && focusedRow.getIndex() == 0) {
  5820. return false;
  5821. } else {
  5822. VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
  5823. .iterator().next();
  5824. if (rowByRowIndex.getIndex() == 0) {
  5825. setRowFocus(rowByRowIndex);
  5826. selectFocusedRow(ctrl, shift);
  5827. sendSelectedRows();
  5828. } else {
  5829. // first row of table will come in next row fetch
  5830. if (ctrl) {
  5831. focusFirstItemInNextRender = true;
  5832. } else {
  5833. selectFirstItemInNextRender = true;
  5834. multiselectPending = shift;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. return true;
  5840. }
  5841. // Goto end navigation
  5842. if (keycode == getNavigationEndKey()) {
  5843. scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
  5844. if (isSelectable()) {
  5845. final int lastRendered = scrollBody.getLastRendered();
  5846. if (lastRendered + 1 == totalRows) {
  5847. VScrollTableRow rowByRowIndex = scrollBody
  5848. .getRowByRowIndex(lastRendered);
  5849. if (focusedRow != rowByRowIndex) {
  5850. setRowFocus(rowByRowIndex);
  5851. selectFocusedRow(ctrl, shift);
  5852. sendSelectedRows();
  5853. }
  5854. } else {
  5855. if (ctrl) {
  5856. focusLastItemInNextRender = true;
  5857. } else {
  5858. selectLastItemInNextRender = true;
  5859. multiselectPending = shift;
  5860. }
  5861. }
  5862. }
  5863. return true;
  5864. }
  5865. return false;
  5866. }
  5867. private boolean isFocusAtTheBeginningOfTable() {
  5868. return focusedRow.getIndex() == 0;
  5869. }
  5870. private boolean isFocusAtTheEndOfTable() {
  5871. return focusedRow.getIndex() + 1 >= totalRows;
  5872. }
  5873. private int getFullyVisibleRowCount() {
  5874. return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
  5875. .getRowHeight());
  5876. }
  5877. private void scrollByPagelenght(int i) {
  5878. int pixels = i * scrollBodyPanel.getOffsetHeight();
  5879. int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
  5880. if (newPixels < 0) {
  5881. newPixels = 0;
  5882. } // else if too high, NOP (all know browsers accept illegally big
  5883. // values here)
  5884. scrollBodyPanel.setScrollPosition(newPixels);
  5885. }
  5886. /*
  5887. * (non-Javadoc)
  5888. *
  5889. * @see
  5890. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  5891. * .dom.client.FocusEvent)
  5892. */
  5893. public void onFocus(FocusEvent event) {
  5894. if (isFocusable()) {
  5895. hasFocus = true;
  5896. // Focus a row if no row is in focus
  5897. if (focusedRow == null) {
  5898. focusRowFromBody();
  5899. } else {
  5900. setRowFocus(focusedRow);
  5901. }
  5902. }
  5903. }
  5904. /*
  5905. * (non-Javadoc)
  5906. *
  5907. * @see
  5908. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  5909. * .dom.client.BlurEvent)
  5910. */
  5911. public void onBlur(BlurEvent event) {
  5912. hasFocus = false;
  5913. navKeyDown = false;
  5914. if (BrowserInfo.get().isIE()) {
  5915. // IE sometimes moves focus to a clicked table cell...
  5916. Element focusedElement = Util.getIEFocusedElement();
  5917. if (Util.getPaintableForElement(client, getParent(), focusedElement) == this) {
  5918. // ..in that case, steal the focus back to the focus handler
  5919. // but not if focus is in a child component instead (#7965)
  5920. focus();
  5921. return;
  5922. }
  5923. }
  5924. if (isFocusable()) {
  5925. // Unfocus any row
  5926. setRowFocus(null);
  5927. }
  5928. }
  5929. /**
  5930. * Removes a key from a range if the key is found in a selected range
  5931. *
  5932. * @param key
  5933. * The key to remove
  5934. */
  5935. private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
  5936. Collection<SelectionRange> newRanges = null;
  5937. for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
  5938. .hasNext();) {
  5939. SelectionRange range = iterator.next();
  5940. if (range.inRange(row)) {
  5941. // Split the range if given row is in range
  5942. Collection<SelectionRange> splitranges = range.split(row);
  5943. if (newRanges == null) {
  5944. newRanges = new ArrayList<SelectionRange>();
  5945. }
  5946. newRanges.addAll(splitranges);
  5947. iterator.remove();
  5948. }
  5949. }
  5950. if (newRanges != null) {
  5951. selectedRowRanges.addAll(newRanges);
  5952. }
  5953. }
  5954. /**
  5955. * Can the Table be focused?
  5956. *
  5957. * @return True if the table can be focused, else false
  5958. */
  5959. public boolean isFocusable() {
  5960. if (scrollBody != null && enabled) {
  5961. return !(!hasHorizontalScrollbar() && !hasVerticalScrollbar() && !isSelectable());
  5962. }
  5963. return false;
  5964. }
  5965. private boolean hasHorizontalScrollbar() {
  5966. return scrollBody.getOffsetWidth() > scrollBodyPanel.getOffsetWidth();
  5967. }
  5968. private boolean hasVerticalScrollbar() {
  5969. return scrollBody.getOffsetHeight() > scrollBodyPanel.getOffsetHeight();
  5970. }
  5971. /*
  5972. * (non-Javadoc)
  5973. *
  5974. * @see com.vaadin.terminal.gwt.client.Focusable#focus()
  5975. */
  5976. public void focus() {
  5977. if (isFocusable()) {
  5978. scrollBodyPanel.focus();
  5979. }
  5980. }
  5981. /**
  5982. * Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
  5983. * component).
  5984. *
  5985. * If the component has no explicit tabIndex a zero is given (default
  5986. * tabbing order based on dom hierarchy) or -1 if the component does not
  5987. * need to gain focus. The component needs no focus if it has no scrollabars
  5988. * (not scrollable) and not selectable. Note that in the future shortcut
  5989. * actions may need focus.
  5990. *
  5991. */
  5992. private void setProperTabIndex() {
  5993. int storedScrollTop = 0;
  5994. int storedScrollLeft = 0;
  5995. if (BrowserInfo.get().getOperaVersion() >= 11) {
  5996. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  5997. storedScrollTop = scrollBodyPanel.getScrollPosition();
  5998. storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
  5999. }
  6000. if (tabIndex == 0 && !isFocusable()) {
  6001. scrollBodyPanel.setTabIndex(-1);
  6002. } else {
  6003. scrollBodyPanel.setTabIndex(tabIndex);
  6004. }
  6005. if (BrowserInfo.get().getOperaVersion() >= 11) {
  6006. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  6007. scrollBodyPanel.setScrollPosition(storedScrollTop);
  6008. scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
  6009. }
  6010. }
  6011. public void startScrollingVelocityTimer() {
  6012. if (scrollingVelocityTimer == null) {
  6013. scrollingVelocityTimer = new Timer() {
  6014. @Override
  6015. public void run() {
  6016. scrollingVelocity++;
  6017. }
  6018. };
  6019. scrollingVelocityTimer.scheduleRepeating(100);
  6020. }
  6021. }
  6022. public void cancelScrollingVelocityTimer() {
  6023. if (scrollingVelocityTimer != null) {
  6024. // Remove velocityTimer if it exists and the Table is disabled
  6025. scrollingVelocityTimer.cancel();
  6026. scrollingVelocityTimer = null;
  6027. scrollingVelocity = 10;
  6028. }
  6029. }
  6030. /**
  6031. *
  6032. * @param keyCode
  6033. * @return true if the given keyCode is used by the table for navigation
  6034. */
  6035. private boolean isNavigationKey(int keyCode) {
  6036. return keyCode == getNavigationUpKey()
  6037. || keyCode == getNavigationLeftKey()
  6038. || keyCode == getNavigationRightKey()
  6039. || keyCode == getNavigationDownKey()
  6040. || keyCode == getNavigationPageUpKey()
  6041. || keyCode == getNavigationPageDownKey()
  6042. || keyCode == getNavigationEndKey()
  6043. || keyCode == getNavigationStartKey();
  6044. }
  6045. public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
  6046. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  6047. public void execute() {
  6048. if (currentlyFocusedRow != null) {
  6049. setRowFocus(currentlyFocusedRow);
  6050. } else {
  6051. VConsole.log("no row?");
  6052. focusRowFromBody();
  6053. }
  6054. scrollBody.ensureFocus();
  6055. }
  6056. });
  6057. }
  6058. public Action[] getActions() {
  6059. if (bodyActionKeys == null) {
  6060. return new Action[] {};
  6061. }
  6062. final Action[] actions = new Action[bodyActionKeys.length];
  6063. for (int i = 0; i < actions.length; i++) {
  6064. final String actionKey = bodyActionKeys[i];
  6065. Action bodyAction = new TreeAction(this, null, actionKey);
  6066. bodyAction.setCaption(getActionCaption(actionKey));
  6067. bodyAction.setIconUrl(getActionIcon(actionKey));
  6068. actions[i] = bodyAction;
  6069. }
  6070. return actions;
  6071. }
  6072. public ApplicationConnection getClient() {
  6073. return client;
  6074. }
  6075. public String getPaintableId() {
  6076. return paintableId;
  6077. }
  6078. /**
  6079. * Add this to the element mouse down event by using element.setPropertyJSO
  6080. * ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
  6081. * when the mouse is depressed in the mouse up event.
  6082. *
  6083. * @return Returns the JSO preventing text selection
  6084. */
  6085. private static native JavaScriptObject getPreventTextSelectionIEHack()
  6086. /*-{
  6087. return function(){ return false; };
  6088. }-*/;
  6089. protected void triggerLazyColumnAdjustment(boolean now) {
  6090. lazyAdjustColumnWidths.cancel();
  6091. if (now) {
  6092. lazyAdjustColumnWidths.run();
  6093. } else {
  6094. lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
  6095. }
  6096. }
  6097. private void debug(String msg) {
  6098. if (enableDebug) {
  6099. VConsole.error(msg);
  6100. }
  6101. }
  6102. public Widget getWidgetForPaintable() {
  6103. return this;
  6104. }
  6105. }