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

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