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

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