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

VScrollTable.java 242KB

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