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

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