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

VScrollTable.java 311KB

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