Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

VScrollTable.java 288KB

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