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

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