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

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