Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.widgets;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Map.Entry;
  28. import java.util.Set;
  29. import java.util.TreeMap;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;
  32. import com.google.gwt.core.client.Scheduler;
  33. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  34. import com.google.gwt.core.shared.GWT;
  35. import com.google.gwt.dom.client.BrowserEvents;
  36. import com.google.gwt.dom.client.DivElement;
  37. import com.google.gwt.dom.client.Document;
  38. import com.google.gwt.dom.client.Element;
  39. import com.google.gwt.dom.client.EventTarget;
  40. import com.google.gwt.dom.client.NativeEvent;
  41. import com.google.gwt.dom.client.Node;
  42. import com.google.gwt.dom.client.Style;
  43. import com.google.gwt.dom.client.Style.Display;
  44. import com.google.gwt.dom.client.Style.Unit;
  45. import com.google.gwt.dom.client.TableCellElement;
  46. import com.google.gwt.dom.client.TableRowElement;
  47. import com.google.gwt.dom.client.TableSectionElement;
  48. import com.google.gwt.dom.client.Touch;
  49. import com.google.gwt.event.dom.client.ClickEvent;
  50. import com.google.gwt.event.dom.client.ClickHandler;
  51. import com.google.gwt.event.dom.client.KeyCodes;
  52. import com.google.gwt.event.dom.client.KeyDownEvent;
  53. import com.google.gwt.event.dom.client.KeyDownHandler;
  54. import com.google.gwt.event.dom.client.KeyEvent;
  55. import com.google.gwt.event.dom.client.MouseEvent;
  56. import com.google.gwt.event.logical.shared.CloseEvent;
  57. import com.google.gwt.event.logical.shared.CloseHandler;
  58. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  59. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  60. import com.google.gwt.event.shared.HandlerRegistration;
  61. import com.google.gwt.touch.client.Point;
  62. import com.google.gwt.user.client.DOM;
  63. import com.google.gwt.user.client.Event;
  64. import com.google.gwt.user.client.Event.NativePreviewEvent;
  65. import com.google.gwt.user.client.Event.NativePreviewHandler;
  66. import com.google.gwt.user.client.Timer;
  67. import com.google.gwt.user.client.ui.Button;
  68. import com.google.gwt.user.client.ui.CheckBox;
  69. import com.google.gwt.user.client.ui.Composite;
  70. import com.google.gwt.user.client.ui.FlowPanel;
  71. import com.google.gwt.user.client.ui.HasEnabled;
  72. import com.google.gwt.user.client.ui.HasWidgets;
  73. import com.google.gwt.user.client.ui.MenuBar;
  74. import com.google.gwt.user.client.ui.MenuItem;
  75. import com.google.gwt.user.client.ui.PopupPanel;
  76. import com.google.gwt.user.client.ui.ResizeComposite;
  77. import com.google.gwt.user.client.ui.Widget;
  78. import com.vaadin.client.BrowserInfo;
  79. import com.vaadin.client.DeferredWorker;
  80. import com.vaadin.client.Focusable;
  81. import com.vaadin.client.WidgetUtil;
  82. import com.vaadin.client.data.DataChangeHandler;
  83. import com.vaadin.client.data.DataSource;
  84. import com.vaadin.client.data.DataSource.RowHandle;
  85. import com.vaadin.client.renderers.ComplexRenderer;
  86. import com.vaadin.client.renderers.Renderer;
  87. import com.vaadin.client.renderers.WidgetRenderer;
  88. import com.vaadin.client.ui.FocusUtil;
  89. import com.vaadin.client.ui.SubPartAware;
  90. import com.vaadin.client.ui.dd.DragAndDropHandler;
  91. import com.vaadin.client.ui.dd.DragAndDropHandler.DragAndDropCallback;
  92. import com.vaadin.client.ui.dd.DragHandle;
  93. import com.vaadin.client.ui.dd.DragHandle.DragHandleCallback;
  94. import com.vaadin.client.widget.escalator.Cell;
  95. import com.vaadin.client.widget.escalator.ColumnConfiguration;
  96. import com.vaadin.client.widget.escalator.EscalatorUpdater;
  97. import com.vaadin.client.widget.escalator.FlyweightCell;
  98. import com.vaadin.client.widget.escalator.Row;
  99. import com.vaadin.client.widget.escalator.RowContainer;
  100. import com.vaadin.client.widget.escalator.RowVisibilityChangeEvent;
  101. import com.vaadin.client.widget.escalator.RowVisibilityChangeHandler;
  102. import com.vaadin.client.widget.escalator.ScrollbarBundle.Direction;
  103. import com.vaadin.client.widget.escalator.Spacer;
  104. import com.vaadin.client.widget.escalator.SpacerUpdater;
  105. import com.vaadin.client.widget.escalator.events.RowHeightChangedEvent;
  106. import com.vaadin.client.widget.escalator.events.RowHeightChangedHandler;
  107. import com.vaadin.client.widget.grid.AutoScroller;
  108. import com.vaadin.client.widget.grid.AutoScroller.AutoScrollerCallback;
  109. import com.vaadin.client.widget.grid.AutoScroller.ScrollAxis;
  110. import com.vaadin.client.widget.grid.CellReference;
  111. import com.vaadin.client.widget.grid.CellStyleGenerator;
  112. import com.vaadin.client.widget.grid.DataAvailableEvent;
  113. import com.vaadin.client.widget.grid.DataAvailableHandler;
  114. import com.vaadin.client.widget.grid.DefaultEditorEventHandler;
  115. import com.vaadin.client.widget.grid.DetailsGenerator;
  116. import com.vaadin.client.widget.grid.EditorHandler;
  117. import com.vaadin.client.widget.grid.EditorHandler.EditorRequest;
  118. import com.vaadin.client.widget.grid.EventCellReference;
  119. import com.vaadin.client.widget.grid.HeightAwareDetailsGenerator;
  120. import com.vaadin.client.widget.grid.RendererCellReference;
  121. import com.vaadin.client.widget.grid.RowReference;
  122. import com.vaadin.client.widget.grid.RowStyleGenerator;
  123. import com.vaadin.client.widget.grid.events.AbstractGridKeyEventHandler;
  124. import com.vaadin.client.widget.grid.events.AbstractGridMouseEventHandler;
  125. import com.vaadin.client.widget.grid.events.BodyClickHandler;
  126. import com.vaadin.client.widget.grid.events.BodyDoubleClickHandler;
  127. import com.vaadin.client.widget.grid.events.BodyKeyDownHandler;
  128. import com.vaadin.client.widget.grid.events.BodyKeyPressHandler;
  129. import com.vaadin.client.widget.grid.events.BodyKeyUpHandler;
  130. import com.vaadin.client.widget.grid.events.ColumnReorderEvent;
  131. import com.vaadin.client.widget.grid.events.ColumnReorderHandler;
  132. import com.vaadin.client.widget.grid.events.ColumnResizeEvent;
  133. import com.vaadin.client.widget.grid.events.ColumnResizeHandler;
  134. import com.vaadin.client.widget.grid.events.ColumnVisibilityChangeEvent;
  135. import com.vaadin.client.widget.grid.events.ColumnVisibilityChangeHandler;
  136. import com.vaadin.client.widget.grid.events.FooterClickHandler;
  137. import com.vaadin.client.widget.grid.events.FooterDoubleClickHandler;
  138. import com.vaadin.client.widget.grid.events.FooterKeyDownHandler;
  139. import com.vaadin.client.widget.grid.events.FooterKeyPressHandler;
  140. import com.vaadin.client.widget.grid.events.FooterKeyUpHandler;
  141. import com.vaadin.client.widget.grid.events.GridClickEvent;
  142. import com.vaadin.client.widget.grid.events.GridDoubleClickEvent;
  143. import com.vaadin.client.widget.grid.events.GridEnabledEvent;
  144. import com.vaadin.client.widget.grid.events.GridEnabledHandler;
  145. import com.vaadin.client.widget.grid.events.GridKeyDownEvent;
  146. import com.vaadin.client.widget.grid.events.GridKeyPressEvent;
  147. import com.vaadin.client.widget.grid.events.GridKeyUpEvent;
  148. import com.vaadin.client.widget.grid.events.HeaderClickHandler;
  149. import com.vaadin.client.widget.grid.events.HeaderDoubleClickHandler;
  150. import com.vaadin.client.widget.grid.events.HeaderKeyDownHandler;
  151. import com.vaadin.client.widget.grid.events.HeaderKeyPressHandler;
  152. import com.vaadin.client.widget.grid.events.HeaderKeyUpHandler;
  153. import com.vaadin.client.widget.grid.events.ScrollEvent;
  154. import com.vaadin.client.widget.grid.events.ScrollHandler;
  155. import com.vaadin.client.widget.grid.events.SelectAllEvent;
  156. import com.vaadin.client.widget.grid.events.SelectAllHandler;
  157. import com.vaadin.client.widget.grid.selection.HasSelectionHandlers;
  158. import com.vaadin.client.widget.grid.selection.MultiSelectionRenderer;
  159. import com.vaadin.client.widget.grid.selection.SelectionEvent;
  160. import com.vaadin.client.widget.grid.selection.SelectionHandler;
  161. import com.vaadin.client.widget.grid.selection.SelectionModel;
  162. import com.vaadin.client.widget.grid.selection.SelectionModel.Multi;
  163. import com.vaadin.client.widget.grid.selection.SelectionModel.Single;
  164. import com.vaadin.client.widget.grid.selection.SelectionModelMulti;
  165. import com.vaadin.client.widget.grid.selection.SelectionModelNone;
  166. import com.vaadin.client.widget.grid.selection.SelectionModelSingle;
  167. import com.vaadin.client.widget.grid.sort.Sort;
  168. import com.vaadin.client.widget.grid.sort.SortEvent;
  169. import com.vaadin.client.widget.grid.sort.SortHandler;
  170. import com.vaadin.client.widget.grid.sort.SortOrder;
  171. import com.vaadin.client.widgets.Escalator.AbstractRowContainer;
  172. import com.vaadin.client.widgets.Escalator.SubPartArguments;
  173. import com.vaadin.client.widgets.Grid.Editor.State;
  174. import com.vaadin.client.widgets.Grid.StaticSection.StaticCell;
  175. import com.vaadin.client.widgets.Grid.StaticSection.StaticRow;
  176. import com.vaadin.shared.data.sort.SortDirection;
  177. import com.vaadin.shared.ui.grid.GridConstants;
  178. import com.vaadin.shared.ui.grid.GridConstants.Section;
  179. import com.vaadin.shared.ui.grid.GridStaticCellType;
  180. import com.vaadin.shared.ui.grid.HeightMode;
  181. import com.vaadin.shared.ui.grid.Range;
  182. import com.vaadin.shared.ui.grid.ScrollDestination;
  183. import com.vaadin.shared.util.SharedUtil;
  184. /**
  185. * A data grid view that supports columns and lazy loading of data rows from a
  186. * data source.
  187. *
  188. * <h1>Columns</h1>
  189. * <p>
  190. * Each column in Grid is represented by a {@link Column}. Each
  191. * {@code GridColumn} has a custom implementation for
  192. * {@link Column#getValue(Object)} that gets the row object as an argument, and
  193. * returns the value for that particular column, extracted from the row object.
  194. * <p>
  195. * Each column also has a Renderer. Its function is to take the value that is
  196. * given by the {@code GridColumn} and display it to the user. A simple column
  197. * might have a {@link com.vaadin.client.renderers.TextRenderer TextRenderer}
  198. * that simply takes in a {@code String} and displays it as the cell's content.
  199. * A more complex renderer might be
  200. * {@link com.vaadin.client.renderers.ProgressBarRenderer ProgressBarRenderer}
  201. * that takes in a floating point number, and displays a progress bar instead,
  202. * based on the given number.
  203. * <p>
  204. * <em>See:</em> {@link #addColumn(Column)}, {@link #addColumn(Column, int)} and
  205. * {@link #addColumns(Column...)}. <em>Also</em>
  206. * {@link Column#setRenderer(Renderer)}.
  207. *
  208. * <h1>Data Sources</h1>
  209. * <p>
  210. * Grid gets its data from a {@link DataSource}, providing row objects to Grid
  211. * from a user-defined endpoint. It can be either a local in-memory data source
  212. * (e.g. {@link com.vaadin.client.widget.grid.datasources.ListDataSource
  213. * ListDataSource}) or even a remote one, retrieving data from e.g. a REST API
  214. * (see {@link com.vaadin.client.data.AbstractRemoteDataSource
  215. * AbstractRemoteDataSource}).
  216. *
  217. *
  218. * @param <T>
  219. * The row type of the grid. The row type is the POJO type from where
  220. * the data is retrieved into the column cells.
  221. * @since 7.4
  222. * @author Vaadin Ltd
  223. */
  224. public class Grid<T> extends ResizeComposite implements HasSelectionHandlers<T>,
  225. SubPartAware, DeferredWorker, Focusable,
  226. com.google.gwt.user.client.ui.Focusable, HasWidgets, HasEnabled {
  227. private static final String STYLE_NAME = "v-grid";
  228. private static final String SELECT_ALL_CHECKBOX_CLASSNAME = "-select-all-checkbox";
  229. /**
  230. * Abstract base class for Grid header and footer sections.
  231. *
  232. * @since 7.5.0
  233. *
  234. * @param <ROWTYPE>
  235. * the type of the rows in the section
  236. */
  237. public abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>> {
  238. /**
  239. * A header or footer cell. Has a simple textual caption.
  240. *
  241. */
  242. public static class StaticCell {
  243. private Object content = null;
  244. private int colspan = 1;
  245. private StaticSection<?> section;
  246. private GridStaticCellType type = GridStaticCellType.TEXT;
  247. private String styleName = null;
  248. /**
  249. * Sets the text displayed in this cell.
  250. *
  251. * @param text
  252. * a plain text caption
  253. */
  254. public void setText(String text) {
  255. this.content = text;
  256. this.type = GridStaticCellType.TEXT;
  257. section.requestSectionRefresh();
  258. }
  259. /**
  260. * Returns the text displayed in this cell.
  261. *
  262. * @return the plain text caption
  263. */
  264. public String getText() {
  265. if (type != GridStaticCellType.TEXT) {
  266. throw new IllegalStateException(
  267. "Cannot fetch Text from a cell with type " + type);
  268. }
  269. return (String) content;
  270. }
  271. protected StaticSection<?> getSection() {
  272. assert section != null;
  273. return section;
  274. }
  275. protected void setSection(StaticSection<?> section) {
  276. this.section = section;
  277. }
  278. /**
  279. * Returns the amount of columns the cell spans. By default is 1.
  280. *
  281. * @return The amount of columns the cell spans.
  282. */
  283. public int getColspan() {
  284. return colspan;
  285. }
  286. /**
  287. * Sets the amount of columns the cell spans. Must be more or equal
  288. * to 1. By default is 1.
  289. *
  290. * @param colspan
  291. * the colspan to set
  292. */
  293. public void setColspan(int colspan) {
  294. if (colspan < 1) {
  295. throw new IllegalArgumentException(
  296. "Colspan cannot be less than 1");
  297. }
  298. this.colspan = colspan;
  299. section.requestSectionRefresh();
  300. }
  301. /**
  302. * Returns the html inside the cell.
  303. *
  304. * @throws IllegalStateException
  305. * if trying to retrive HTML from a cell with a type
  306. * other than {@link GridStaticCellType#HTML}.
  307. * @return the html content of the cell.
  308. */
  309. public String getHtml() {
  310. if (type != GridStaticCellType.HTML) {
  311. throw new IllegalStateException(
  312. "Cannot fetch HTML from a cell with type " + type);
  313. }
  314. return (String) content;
  315. }
  316. /**
  317. * Sets the content of the cell to the provided html. All previous
  318. * content is discarded and the cell type is set to
  319. * {@link GridStaticCellType#HTML}.
  320. *
  321. * @param html
  322. * The html content of the cell
  323. */
  324. public void setHtml(String html) {
  325. this.content = html;
  326. this.type = GridStaticCellType.HTML;
  327. section.requestSectionRefresh();
  328. }
  329. /**
  330. * Returns the widget in the cell.
  331. *
  332. * @throws IllegalStateException
  333. * if the cell is not {@link GridStaticCellType#WIDGET}
  334. *
  335. * @return the widget in the cell
  336. */
  337. public Widget getWidget() {
  338. if (type != GridStaticCellType.WIDGET) {
  339. throw new IllegalStateException(
  340. "Cannot fetch Widget from a cell with type "
  341. + type);
  342. }
  343. return (Widget) content;
  344. }
  345. /**
  346. * Set widget as the content of the cell. The type of the cell
  347. * becomes {@link GridStaticCellType#WIDGET}. All previous content
  348. * is discarded.
  349. *
  350. * @param widget
  351. * The widget to add to the cell. Should not be
  352. * previously attached anywhere (widget.getParent ==
  353. * null).
  354. */
  355. public void setWidget(Widget widget) {
  356. if (this.content == widget) {
  357. return;
  358. }
  359. if (this.content instanceof Widget) {
  360. // Old widget in the cell, detach it first
  361. section.getGrid().detachWidget((Widget) this.content);
  362. }
  363. this.content = widget;
  364. this.type = GridStaticCellType.WIDGET;
  365. section.requestSectionRefresh();
  366. }
  367. /**
  368. * Returns the type of the cell.
  369. *
  370. * @return the type of content the cell contains.
  371. */
  372. public GridStaticCellType getType() {
  373. return type;
  374. }
  375. /**
  376. * Returns the custom style name for this cell.
  377. *
  378. * @return the style name or null if no style name has been set
  379. */
  380. public String getStyleName() {
  381. return styleName;
  382. }
  383. /**
  384. * Sets a custom style name for this cell.
  385. *
  386. * @param styleName
  387. * the style name to set or null to not use any style
  388. * name
  389. */
  390. public void setStyleName(String styleName) {
  391. this.styleName = styleName;
  392. section.requestSectionRefresh();
  393. }
  394. /**
  395. * Called when the cell is detached from the row
  396. *
  397. * @since 7.6.3
  398. */
  399. void detach() {
  400. if (this.content instanceof Widget) {
  401. // Widget in the cell, detach it
  402. section.getGrid().detachWidget((Widget) this.content);
  403. }
  404. }
  405. }
  406. /**
  407. * Abstract base class for Grid header and footer rows.
  408. *
  409. * @param <CELLTYPE>
  410. * the type of the cells in the row
  411. */
  412. public abstract static class StaticRow<CELLTYPE extends StaticCell> {
  413. private Map<Column<?, ?>, CELLTYPE> cells = new HashMap<Column<?, ?>, CELLTYPE>();
  414. private StaticSection<?> section;
  415. /**
  416. * Map from set of spanned columns to cell meta data.
  417. */
  418. private Map<Set<Column<?, ?>>, CELLTYPE> cellGroups = new HashMap<Set<Column<?, ?>>, CELLTYPE>();
  419. /**
  420. * A custom style name for the row or null if none is set.
  421. */
  422. private String styleName = null;
  423. /**
  424. * Returns the cell on given GridColumn. If the column is merged
  425. * returned cell is the cell for the whole group.
  426. *
  427. * @param column
  428. * the column in grid
  429. * @return the cell on given column, merged cell for merged columns,
  430. * null if not found
  431. */
  432. public CELLTYPE getCell(Column<?, ?> column) {
  433. Set<Column<?, ?>> cellGroup = getCellGroupForColumn(column);
  434. if (cellGroup != null) {
  435. return cellGroups.get(cellGroup);
  436. }
  437. return cells.get(column);
  438. }
  439. /**
  440. * Returns <code>true</code> if this row contains spanned cells.
  441. *
  442. * @since 7.5.0
  443. * @return does this row contain spanned cells
  444. */
  445. public boolean hasSpannedCells() {
  446. return !cellGroups.isEmpty();
  447. }
  448. /**
  449. * Merges columns cells in a row
  450. *
  451. * @param columns
  452. * the columns which header should be merged
  453. * @return the remaining visible cell after the merge, or the cell
  454. * on first column if all are hidden
  455. */
  456. public CELLTYPE join(Column<?, ?>... columns) {
  457. if (columns.length <= 1) {
  458. throw new IllegalArgumentException(
  459. "You can't merge less than 2 columns together.");
  460. }
  461. HashSet<Column<?, ?>> columnGroup = new HashSet<Column<?, ?>>();
  462. // NOTE: this doesn't care about hidden columns, those are
  463. // filtered in calculateColspans()
  464. for (Column<?, ?> column : columns) {
  465. if (!cells.containsKey(column)) {
  466. throw new IllegalArgumentException(
  467. "Given column does not exists on row "
  468. + column);
  469. } else if (getCellGroupForColumn(column) != null) {
  470. throw new IllegalStateException(
  471. "Column is already in a group.");
  472. }
  473. columnGroup.add(column);
  474. }
  475. CELLTYPE joinedCell = createCell();
  476. cellGroups.put(columnGroup, joinedCell);
  477. joinedCell.setSection(getSection());
  478. calculateColspans();
  479. return joinedCell;
  480. }
  481. /**
  482. * Merges columns cells in a row
  483. *
  484. * @param cells
  485. * The cells to merge. Must be from the same row.
  486. * @return The remaining visible cell after the merge, or the first
  487. * cell if all columns are hidden
  488. */
  489. public CELLTYPE join(CELLTYPE... cells) {
  490. if (cells.length <= 1) {
  491. throw new IllegalArgumentException(
  492. "You can't merge less than 2 cells together.");
  493. }
  494. Column<?, ?>[] columns = new Column<?, ?>[cells.length];
  495. int j = 0;
  496. for (Column<?, ?> column : this.cells.keySet()) {
  497. CELLTYPE cell = this.cells.get(column);
  498. if (!this.cells.containsValue(cells[j])) {
  499. throw new IllegalArgumentException(
  500. "Given cell does not exists on row");
  501. } else if (cell.equals(cells[j])) {
  502. columns[j++] = column;
  503. if (j == cells.length) {
  504. break;
  505. }
  506. }
  507. }
  508. return join(columns);
  509. }
  510. private Set<Column<?, ?>> getCellGroupForColumn(
  511. Column<?, ?> column) {
  512. for (Set<Column<?, ?>> group : cellGroups.keySet()) {
  513. if (group.contains(column)) {
  514. return group;
  515. }
  516. }
  517. return null;
  518. }
  519. void calculateColspans() {
  520. // Reset all cells
  521. for (CELLTYPE cell : this.cells.values()) {
  522. cell.setColspan(1);
  523. }
  524. // Set colspan for grouped cells
  525. for (Set<Column<?, ?>> group : cellGroups.keySet()) {
  526. if (!checkMergedCellIsContinuous(group)) {
  527. // on error simply break the merged cell
  528. cellGroups.get(group).setColspan(1);
  529. } else {
  530. int colSpan = 0;
  531. for (Column<?, ?> column : group) {
  532. if (!column.isHidden()) {
  533. colSpan++;
  534. }
  535. }
  536. // colspan can't be 0
  537. cellGroups.get(group).setColspan(Math.max(1, colSpan));
  538. }
  539. }
  540. }
  541. private boolean checkMergedCellIsContinuous(
  542. Set<Column<?, ?>> mergedCell) {
  543. // no matter if hidden or not, just check for continuous order
  544. final List<Column<?, ?>> columnOrder = new ArrayList<Column<?, ?>>(
  545. section.grid.getColumns());
  546. if (!columnOrder.containsAll(mergedCell)) {
  547. return false;
  548. }
  549. for (int i = 0; i < columnOrder.size(); ++i) {
  550. if (!mergedCell.contains(columnOrder.get(i))) {
  551. continue;
  552. }
  553. for (int j = 1; j < mergedCell.size(); ++j) {
  554. if (!mergedCell.contains(columnOrder.get(i + j))) {
  555. return false;
  556. }
  557. }
  558. return true;
  559. }
  560. return false;
  561. }
  562. protected void addCell(Column<?, ?> column) {
  563. CELLTYPE cell = createCell();
  564. cell.setSection(getSection());
  565. cells.put(column, cell);
  566. }
  567. protected void removeCell(Column<?, ?> column) {
  568. cells.remove(column);
  569. }
  570. protected abstract CELLTYPE createCell();
  571. protected StaticSection<?> getSection() {
  572. return section;
  573. }
  574. protected void setSection(StaticSection<?> section) {
  575. this.section = section;
  576. }
  577. /**
  578. * Returns the custom style name for this row.
  579. *
  580. * @return the style name or null if no style name has been set
  581. */
  582. public String getStyleName() {
  583. return styleName;
  584. }
  585. /**
  586. * Sets a custom style name for this row.
  587. *
  588. * @param styleName
  589. * the style name to set or null to not use any style
  590. * name
  591. */
  592. public void setStyleName(String styleName) {
  593. this.styleName = styleName;
  594. section.requestSectionRefresh();
  595. }
  596. /**
  597. * Called when the row is detached from the grid
  598. *
  599. * @since 7.6.3
  600. */
  601. void detach() {
  602. // Avoid calling detach twice for a merged cell
  603. HashSet<CELLTYPE> cells = new HashSet<CELLTYPE>();
  604. for (Column<?, ?> column : getSection().grid.getColumns()) {
  605. cells.add(getCell(column));
  606. }
  607. for (CELLTYPE cell : cells) {
  608. cell.detach();
  609. }
  610. }
  611. }
  612. private Grid<?> grid;
  613. private List<ROWTYPE> rows = new ArrayList<ROWTYPE>();
  614. private boolean visible = true;
  615. /**
  616. * Creates and returns a new instance of the row type.
  617. *
  618. * @return the created row
  619. */
  620. protected abstract ROWTYPE createRow();
  621. /**
  622. * Informs the grid that this section should be re-rendered.
  623. * <p>
  624. * <b>Note</b> that re-render means calling update() on each cell,
  625. * preAttach()/postAttach()/preDetach()/postDetach() is not called as
  626. * the cells are not removed from the DOM.
  627. */
  628. protected abstract void requestSectionRefresh();
  629. /**
  630. * Sets the visibility of the whole section.
  631. *
  632. * @param visible
  633. * true to show this section, false to hide
  634. */
  635. public void setVisible(boolean visible) {
  636. this.visible = visible;
  637. requestSectionRefresh();
  638. }
  639. /**
  640. * Returns the visibility of this section.
  641. *
  642. * @return true if visible, false otherwise.
  643. */
  644. public boolean isVisible() {
  645. return visible;
  646. }
  647. /**
  648. * Inserts a new row at the given position. Shifts the row currently at
  649. * that position and any subsequent rows down (adds one to their
  650. * indices).
  651. *
  652. * @param index
  653. * the position at which to insert the row
  654. * @return the new row
  655. *
  656. * @throws IndexOutOfBoundsException
  657. * if the index is out of bounds
  658. * @see #appendRow()
  659. * @see #prependRow()
  660. * @see #removeRow(int)
  661. * @see #removeRow(StaticRow)
  662. */
  663. public ROWTYPE addRowAt(int index) {
  664. ROWTYPE row = createRow();
  665. row.setSection(this);
  666. for (int i = 0; i < getGrid().getColumnCount(); ++i) {
  667. row.addCell(grid.getColumn(i));
  668. }
  669. rows.add(index, row);
  670. requestSectionRefresh();
  671. return row;
  672. }
  673. /**
  674. * Adds a new row at the top of this section.
  675. *
  676. * @return the new row
  677. * @see #appendRow()
  678. * @see #addRowAt(int)
  679. * @see #removeRow(int)
  680. * @see #removeRow(StaticRow)
  681. */
  682. public ROWTYPE prependRow() {
  683. return addRowAt(0);
  684. }
  685. /**
  686. * Adds a new row at the bottom of this section.
  687. *
  688. * @return the new row
  689. * @see #prependRow()
  690. * @see #addRowAt(int)
  691. * @see #removeRow(int)
  692. * @see #removeRow(StaticRow)
  693. */
  694. public ROWTYPE appendRow() {
  695. return addRowAt(rows.size());
  696. }
  697. /**
  698. * Removes the row at the given position.
  699. *
  700. * @param index
  701. * the position of the row
  702. *
  703. * @throws IndexOutOfBoundsException
  704. * if the index is out of bounds
  705. * @see #addRowAt(int)
  706. * @see #appendRow()
  707. * @see #prependRow()
  708. * @see #removeRow(StaticRow)
  709. */
  710. public void removeRow(int index) {
  711. ROWTYPE row = rows.remove(index);
  712. row.detach();
  713. requestSectionRefresh();
  714. }
  715. /**
  716. * Removes the given row from the section.
  717. *
  718. * @param row
  719. * the row to be removed
  720. *
  721. * @throws IllegalArgumentException
  722. * if the row does not exist in this section
  723. * @see #addRowAt(int)
  724. * @see #appendRow()
  725. * @see #prependRow()
  726. * @see #removeRow(int)
  727. */
  728. public void removeRow(ROWTYPE row) {
  729. try {
  730. removeRow(rows.indexOf(row));
  731. } catch (IndexOutOfBoundsException e) {
  732. throw new IllegalArgumentException(
  733. "Section does not contain the given row");
  734. }
  735. }
  736. /**
  737. * Returns the row at the given position.
  738. *
  739. * @param index
  740. * the position of the row
  741. * @return the row with the given index
  742. *
  743. * @throws IndexOutOfBoundsException
  744. * if the index is out of bounds
  745. */
  746. public ROWTYPE getRow(int index) {
  747. try {
  748. return rows.get(index);
  749. } catch (IndexOutOfBoundsException e) {
  750. throw new IllegalArgumentException(
  751. "Row with index " + index + " does not exist");
  752. }
  753. }
  754. /**
  755. * Returns the number of rows in this section.
  756. *
  757. * @return the number of rows
  758. */
  759. public int getRowCount() {
  760. return rows.size();
  761. }
  762. protected List<ROWTYPE> getRows() {
  763. return rows;
  764. }
  765. protected int getVisibleRowCount() {
  766. return isVisible() ? getRowCount() : 0;
  767. }
  768. protected void addColumn(Column<?, ?> column) {
  769. for (ROWTYPE row : rows) {
  770. row.addCell(column);
  771. }
  772. }
  773. protected void removeColumn(Column<?, ?> column) {
  774. for (ROWTYPE row : rows) {
  775. row.removeCell(column);
  776. }
  777. }
  778. protected void setGrid(Grid<?> grid) {
  779. this.grid = grid;
  780. }
  781. protected Grid<?> getGrid() {
  782. assert grid != null;
  783. return grid;
  784. }
  785. protected void updateColSpans() {
  786. for (ROWTYPE row : rows) {
  787. if (row.hasSpannedCells()) {
  788. row.calculateColspans();
  789. }
  790. }
  791. }
  792. }
  793. /**
  794. * Represents the header section of a Grid. A header consists of a single
  795. * header row containing a header cell for each column. Each cell has a
  796. * simple textual caption.
  797. */
  798. protected static class Header extends StaticSection<HeaderRow> {
  799. private HeaderRow defaultRow;
  800. private boolean markAsDirty = false;
  801. @Override
  802. public void removeRow(int index) {
  803. HeaderRow removedRow = getRow(index);
  804. super.removeRow(index);
  805. if (removedRow == defaultRow) {
  806. setDefaultRow(null);
  807. }
  808. }
  809. /**
  810. * Sets the default row of this header. The default row is a special
  811. * header row providing a user interface for sorting columns.
  812. *
  813. * @param row
  814. * the new default row, or null for no default row
  815. *
  816. * @throws IllegalArgumentException
  817. * this header does not contain the row
  818. */
  819. public void setDefaultRow(HeaderRow row) {
  820. if (row == defaultRow) {
  821. return;
  822. }
  823. if (row != null && !getRows().contains(row)) {
  824. throw new IllegalArgumentException(
  825. "Cannot set a default row that does not exist in the container");
  826. }
  827. if (defaultRow != null) {
  828. defaultRow.setDefault(false);
  829. }
  830. if (row != null) {
  831. row.setDefault(true);
  832. }
  833. defaultRow = row;
  834. requestSectionRefresh();
  835. }
  836. /**
  837. * Returns the current default row of this header. The default row is a
  838. * special header row providing a user interface for sorting columns.
  839. *
  840. * @return the default row or null if no default row set
  841. */
  842. public HeaderRow getDefaultRow() {
  843. return defaultRow;
  844. }
  845. @Override
  846. protected HeaderRow createRow() {
  847. return new HeaderRow();
  848. }
  849. @Override
  850. protected void requestSectionRefresh() {
  851. markAsDirty = true;
  852. /*
  853. * Defer the refresh so if we multiple times call refreshSection()
  854. * (for example when updating cell values) we only get one actual
  855. * refresh in the end.
  856. */
  857. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  858. @Override
  859. public void execute() {
  860. if (markAsDirty) {
  861. markAsDirty = false;
  862. getGrid().refreshHeader();
  863. }
  864. }
  865. });
  866. }
  867. /**
  868. * Returns the events consumed by the header
  869. *
  870. * @return a collection of BrowserEvents
  871. */
  872. public Collection<String> getConsumedEvents() {
  873. return Arrays.asList(BrowserEvents.TOUCHSTART,
  874. BrowserEvents.TOUCHMOVE, BrowserEvents.TOUCHEND,
  875. BrowserEvents.TOUCHCANCEL, BrowserEvents.CLICK);
  876. }
  877. @Override
  878. protected void addColumn(Column<?, ?> column) {
  879. super.addColumn(column);
  880. // Add default content for new columns.
  881. if (defaultRow != null) {
  882. column.setDefaultHeaderContent(defaultRow.getCell(column));
  883. }
  884. }
  885. }
  886. /**
  887. * A single row in a grid header section.
  888. *
  889. */
  890. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  891. private boolean isDefault = false;
  892. protected void setDefault(boolean isDefault) {
  893. this.isDefault = isDefault;
  894. if (isDefault) {
  895. for (Column<?, ?> column : getSection().grid.getColumns()) {
  896. column.setDefaultHeaderContent(getCell(column));
  897. }
  898. }
  899. }
  900. public boolean isDefault() {
  901. return isDefault;
  902. }
  903. @Override
  904. protected HeaderCell createCell() {
  905. return new HeaderCell();
  906. }
  907. }
  908. /**
  909. * A single cell in a grid header row. Has a caption and, if it's in a
  910. * default row, a drag handle.
  911. */
  912. public static class HeaderCell extends StaticSection.StaticCell {
  913. }
  914. /**
  915. * Represents the footer section of a Grid. The footer is always empty.
  916. */
  917. protected static class Footer extends StaticSection<FooterRow> {
  918. private boolean markAsDirty = false;
  919. @Override
  920. protected FooterRow createRow() {
  921. return new FooterRow();
  922. }
  923. @Override
  924. protected void requestSectionRefresh() {
  925. markAsDirty = true;
  926. /*
  927. * Defer the refresh so if we multiple times call refreshSection()
  928. * (for example when updating cell values) we only get one actual
  929. * refresh in the end.
  930. */
  931. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  932. @Override
  933. public void execute() {
  934. if (markAsDirty) {
  935. markAsDirty = false;
  936. getGrid().refreshFooter();
  937. }
  938. }
  939. });
  940. }
  941. }
  942. /**
  943. * A single cell in a grid Footer row. Has a textual caption.
  944. *
  945. */
  946. public static class FooterCell extends StaticSection.StaticCell {
  947. }
  948. /**
  949. * A single row in a grid Footer section.
  950. *
  951. */
  952. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  953. @Override
  954. protected FooterCell createCell() {
  955. return new FooterCell();
  956. }
  957. }
  958. private static class EditorRequestImpl<T> implements EditorRequest<T> {
  959. /**
  960. * A callback interface used to notify the invoker of the editor handler
  961. * of completed editor requests.
  962. *
  963. * @param <T>
  964. * the row data type
  965. */
  966. public static interface RequestCallback<T> {
  967. /**
  968. * The method that must be called when the request has been
  969. * processed correctly.
  970. *
  971. * @param request
  972. * the original request object
  973. */
  974. public void onSuccess(EditorRequest<T> request);
  975. /**
  976. * The method that must be called when processing the request has
  977. * produced an aborting error.
  978. *
  979. * @param request
  980. * the original request object
  981. */
  982. public void onError(EditorRequest<T> request);
  983. }
  984. private Grid<T> grid;
  985. private final int rowIndex;
  986. private final int columnIndex;
  987. private RequestCallback<T> callback;
  988. private boolean completed = false;
  989. public EditorRequestImpl(Grid<T> grid, int rowIndex, int columnIndex,
  990. RequestCallback<T> callback) {
  991. this.grid = grid;
  992. this.rowIndex = rowIndex;
  993. this.columnIndex = columnIndex;
  994. this.callback = callback;
  995. }
  996. @Override
  997. public int getRowIndex() {
  998. return rowIndex;
  999. }
  1000. @Override
  1001. public int getColumnIndex() {
  1002. return columnIndex;
  1003. }
  1004. @Override
  1005. public T getRow() {
  1006. return grid.getDataSource().getRow(rowIndex);
  1007. }
  1008. @Override
  1009. public Grid<T> getGrid() {
  1010. return grid;
  1011. }
  1012. @Override
  1013. public Widget getWidget(Grid.Column<?, T> column) {
  1014. Widget w = grid.getEditorWidget(column);
  1015. assert w != null;
  1016. return w;
  1017. }
  1018. private void complete(String errorMessage,
  1019. Collection<Column<?, T>> errorColumns) {
  1020. if (completed) {
  1021. throw new IllegalStateException(
  1022. "An EditorRequest must be completed exactly once");
  1023. }
  1024. completed = true;
  1025. if (errorColumns == null) {
  1026. errorColumns = Collections.emptySet();
  1027. }
  1028. grid.getEditor().setEditorError(errorMessage, errorColumns);
  1029. }
  1030. @Override
  1031. public void success() {
  1032. complete(null, null);
  1033. if (callback != null) {
  1034. callback.onSuccess(this);
  1035. }
  1036. }
  1037. @Override
  1038. public void failure(String errorMessage,
  1039. Collection<Grid.Column<?, T>> errorColumns) {
  1040. complete(errorMessage, errorColumns);
  1041. if (callback != null) {
  1042. callback.onError(this);
  1043. }
  1044. }
  1045. @Override
  1046. public boolean isCompleted() {
  1047. return completed;
  1048. }
  1049. }
  1050. /**
  1051. * A wrapper for native DOM events originating from Grid. In addition to the
  1052. * native event, contains a {@link CellReference} instance specifying which
  1053. * cell the event originated from.
  1054. *
  1055. * @since 7.6
  1056. * @param <T>
  1057. * The row type of the grid
  1058. */
  1059. public static class GridEvent<T> {
  1060. private Event event;
  1061. private EventCellReference<T> cell;
  1062. protected GridEvent(Event event, EventCellReference<T> cell) {
  1063. this.event = event;
  1064. this.cell = cell;
  1065. }
  1066. /**
  1067. * Returns the wrapped DOM event.
  1068. *
  1069. * @return the DOM event
  1070. */
  1071. public Event getDomEvent() {
  1072. return event;
  1073. }
  1074. /**
  1075. * Returns the Grid cell this event originated from.
  1076. *
  1077. * @return the event cell
  1078. */
  1079. public EventCellReference<T> getCell() {
  1080. return cell;
  1081. }
  1082. /**
  1083. * Returns the Grid instance this event originated from.
  1084. *
  1085. * @return the grid
  1086. */
  1087. public Grid<T> getGrid() {
  1088. return cell.getGrid();
  1089. }
  1090. }
  1091. /**
  1092. * A wrapper for native DOM events related to the {@link Editor Grid editor}
  1093. * .
  1094. *
  1095. * @since 7.6
  1096. * @param <T>
  1097. * the row type of the grid
  1098. */
  1099. public static class EditorDomEvent<T> extends GridEvent<T> {
  1100. private final Widget editorWidget;
  1101. protected EditorDomEvent(Event event, EventCellReference<T> cell,
  1102. Widget editorWidget) {
  1103. super(event, cell);
  1104. this.editorWidget = editorWidget;
  1105. }
  1106. /**
  1107. * Returns the editor of the Grid this event originated from.
  1108. *
  1109. * @return the related editor instance
  1110. */
  1111. public Editor<T> getEditor() {
  1112. return getGrid().getEditor();
  1113. }
  1114. /**
  1115. * Returns the currently focused editor widget.
  1116. *
  1117. * @return the focused editor widget or {@code null} if not editable
  1118. */
  1119. public Widget getEditorWidget() {
  1120. return editorWidget;
  1121. }
  1122. /**
  1123. * Returns the row index the editor is open at. If the editor is not
  1124. * open, returns -1.
  1125. *
  1126. * @return the index of the edited row or -1 if editor is not open
  1127. */
  1128. public int getRowIndex() {
  1129. return getEditor().rowIndex;
  1130. }
  1131. /**
  1132. * Returns the column index the editor was opened at. If the editor is
  1133. * not open, returns -1.
  1134. *
  1135. * @return the column index or -1 if editor is not open
  1136. */
  1137. public int getFocusedColumnIndex() {
  1138. return getEditor().focusedColumnIndex;
  1139. }
  1140. }
  1141. /**
  1142. * An editor UI for Grid rows. A single Grid row at a time can be opened for
  1143. * editing.
  1144. *
  1145. * @since 7.6
  1146. * @param <T>
  1147. * the row type of the grid
  1148. */
  1149. public static class Editor<T> implements DeferredWorker {
  1150. public static final int KEYCODE_SHOW = KeyCodes.KEY_ENTER;
  1151. public static final int KEYCODE_HIDE = KeyCodes.KEY_ESCAPE;
  1152. private static final String ERROR_CLASS_NAME = "error";
  1153. private static final String NOT_EDITABLE_CLASS_NAME = "not-editable";
  1154. ScheduledCommand fieldFocusCommand = new ScheduledCommand() {
  1155. private int count = 0;
  1156. @Override
  1157. public void execute() {
  1158. Element focusedElement = WidgetUtil.getFocusedElement();
  1159. if (focusedElement == grid.getElement()
  1160. || focusedElement == Document.get().getBody()
  1161. || count > 2) {
  1162. focusColumn(focusedColumnIndex);
  1163. } else {
  1164. ++count;
  1165. Scheduler.get().scheduleDeferred(this);
  1166. }
  1167. }
  1168. };
  1169. /**
  1170. * A handler for events related to the Grid editor. Responsible for
  1171. * opening, moving or closing the editor based on the received event.
  1172. *
  1173. * @since 7.6
  1174. * @author Vaadin Ltd
  1175. * @param <T>
  1176. * the row type of the grid
  1177. */
  1178. public interface EventHandler<T> {
  1179. /**
  1180. * Handles editor-related events in an appropriate way. Opens,
  1181. * moves, or closes the editor based on the given event.
  1182. *
  1183. * @param event
  1184. * the received event
  1185. * @return true if the event was handled and nothing else should be
  1186. * done, false otherwise
  1187. */
  1188. boolean handleEvent(EditorDomEvent<T> event);
  1189. }
  1190. protected enum State {
  1191. INACTIVE, ACTIVATING, BINDING, ACTIVE, SAVING
  1192. }
  1193. private Grid<T> grid;
  1194. private EditorHandler<T> handler;
  1195. private EventHandler<T> eventHandler = GWT
  1196. .create(DefaultEditorEventHandler.class);
  1197. private DivElement editorOverlay = DivElement.as(DOM.createDiv());
  1198. private DivElement cellWrapper = DivElement.as(DOM.createDiv());
  1199. private DivElement frozenCellWrapper = DivElement.as(DOM.createDiv());
  1200. private DivElement messageAndButtonsWrapper = DivElement
  1201. .as(DOM.createDiv());
  1202. private DivElement messageWrapper = DivElement.as(DOM.createDiv());
  1203. private DivElement buttonsWrapper = DivElement.as(DOM.createDiv());
  1204. // Element which contains the error message for the editor
  1205. // Should only be added to the DOM when there's a message to show
  1206. private DivElement message = DivElement.as(DOM.createDiv());
  1207. private Map<Column<?, T>, Widget> columnToWidget = new HashMap<Column<?, T>, Widget>();
  1208. private List<HandlerRegistration> focusHandlers = new ArrayList<HandlerRegistration>();
  1209. private boolean enabled = false;
  1210. private State state = State.INACTIVE;
  1211. private int rowIndex = -1;
  1212. private int focusedColumnIndex = -1;
  1213. private String styleName = null;
  1214. private HandlerRegistration hScrollHandler;
  1215. private HandlerRegistration vScrollHandler;
  1216. private final Button saveButton;
  1217. private final Button cancelButton;
  1218. private static final int SAVE_TIMEOUT_MS = 5000;
  1219. private final Timer saveTimeout = new Timer() {
  1220. @Override
  1221. public void run() {
  1222. getLogger().warning(
  1223. "Editor save action is taking longer than expected ("
  1224. + SAVE_TIMEOUT_MS + "ms). Does your "
  1225. + EditorHandler.class.getSimpleName()
  1226. + " remember to call success() or fail()?");
  1227. }
  1228. };
  1229. private final EditorRequestImpl.RequestCallback<T> saveRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  1230. @Override
  1231. public void onSuccess(EditorRequest<T> request) {
  1232. if (state == State.SAVING) {
  1233. cleanup();
  1234. cancel();
  1235. grid.clearSortOrder();
  1236. }
  1237. }
  1238. @Override
  1239. public void onError(EditorRequest<T> request) {
  1240. if (state == State.SAVING) {
  1241. cleanup();
  1242. }
  1243. }
  1244. private void cleanup() {
  1245. state = State.ACTIVE;
  1246. setButtonsEnabled(true);
  1247. saveTimeout.cancel();
  1248. }
  1249. };
  1250. private static final int BIND_TIMEOUT_MS = 5000;
  1251. private final Timer bindTimeout = new Timer() {
  1252. @Override
  1253. public void run() {
  1254. getLogger().warning(
  1255. "Editor bind action is taking longer than expected ("
  1256. + BIND_TIMEOUT_MS + "ms). Does your "
  1257. + EditorHandler.class.getSimpleName()
  1258. + " remember to call success() or fail()?");
  1259. }
  1260. };
  1261. private final EditorRequestImpl.RequestCallback<T> bindRequestCallback = new EditorRequestImpl.RequestCallback<T>() {
  1262. @Override
  1263. public void onSuccess(EditorRequest<T> request) {
  1264. if (state == State.BINDING) {
  1265. state = State.ACTIVE;
  1266. bindTimeout.cancel();
  1267. rowIndex = request.getRowIndex();
  1268. focusedColumnIndex = request.getColumnIndex();
  1269. if (focusedColumnIndex >= 0) {
  1270. // Update internal focus of Grid
  1271. grid.focusCell(rowIndex, focusedColumnIndex);
  1272. }
  1273. showOverlay();
  1274. }
  1275. }
  1276. @Override
  1277. public void onError(EditorRequest<T> request) {
  1278. if (state == State.BINDING) {
  1279. if (rowIndex == -1) {
  1280. doCancel();
  1281. } else {
  1282. state = State.ACTIVE;
  1283. // TODO: Maybe restore focus?
  1284. }
  1285. bindTimeout.cancel();
  1286. }
  1287. }
  1288. };
  1289. /** A set of all the columns that display an error flag. */
  1290. private final Set<Column<?, T>> columnErrors = new HashSet<Grid.Column<?, T>>();
  1291. private boolean buffered = true;
  1292. /** Original position of editor */
  1293. private double originalTop;
  1294. /** Original scroll position of grid when editor was opened */
  1295. private double originalScrollTop;
  1296. private RowHandle<T> pinnedRowHandle;
  1297. public Editor() {
  1298. saveButton = new Button();
  1299. saveButton.setText(GridConstants.DEFAULT_SAVE_CAPTION);
  1300. saveButton.addClickHandler(new ClickHandler() {
  1301. @Override
  1302. public void onClick(ClickEvent event) {
  1303. save();
  1304. }
  1305. });
  1306. cancelButton = new Button();
  1307. cancelButton.setText(GridConstants.DEFAULT_CANCEL_CAPTION);
  1308. cancelButton.addClickHandler(new ClickHandler() {
  1309. @Override
  1310. public void onClick(ClickEvent event) {
  1311. cancel();
  1312. }
  1313. });
  1314. }
  1315. public void setEditorError(String errorMessage,
  1316. Collection<Column<?, T>> errorColumns) {
  1317. if (errorMessage == null) {
  1318. message.removeFromParent();
  1319. } else {
  1320. message.setInnerText(errorMessage);
  1321. if (message.getParentElement() == null) {
  1322. messageWrapper.appendChild(message);
  1323. }
  1324. }
  1325. // In unbuffered mode only show message wrapper if there is an error
  1326. if (!isBuffered()) {
  1327. setMessageAndButtonsWrapperVisible(errorMessage != null);
  1328. }
  1329. if (state == State.ACTIVE || state == State.SAVING) {
  1330. for (Column<?, T> c : grid.getColumns()) {
  1331. grid.getEditor().setEditorColumnError(c,
  1332. errorColumns.contains(c));
  1333. }
  1334. }
  1335. }
  1336. public int getRow() {
  1337. return rowIndex;
  1338. }
  1339. /**
  1340. * If a cell of this Grid had focus once this editRow call was
  1341. * triggered, the editor component at the previously focused column
  1342. * index will be focused.
  1343. *
  1344. * If a Grid cell was not focused prior to calling this method, it will
  1345. * be equivalent to {@code editRow(rowIndex, -1)}.
  1346. *
  1347. * @see #editRow(int, int)
  1348. */
  1349. public void editRow(int rowIndex) {
  1350. // Focus the last focused column in the editor iff grid or its child
  1351. // was focused before the edit request
  1352. Cell focusedCell = grid.cellFocusHandler.getFocusedCell();
  1353. Element focusedElement = WidgetUtil.getFocusedElement();
  1354. if (focusedCell != null && focusedElement != null
  1355. && grid.getElement().isOrHasChild(focusedElement)) {
  1356. editRow(rowIndex, focusedCell.getColumn());
  1357. } else {
  1358. editRow(rowIndex, -1);
  1359. }
  1360. }
  1361. /**
  1362. * Opens the editor over the row with the given index and attempts to
  1363. * focus the editor widget in the given column index. Does not move
  1364. * focus if the widget is not focusable or if the column index is -1.
  1365. *
  1366. * @param rowIndex
  1367. * the index of the row to be edited
  1368. * @param columnIndex
  1369. * the column index of the editor widget that should be
  1370. * initially focused or -1 to not set focus
  1371. *
  1372. * @throws IllegalStateException
  1373. * if this editor is not enabled
  1374. * @throws IllegalStateException
  1375. * if this editor is already in edit mode and in buffered
  1376. * mode
  1377. *
  1378. * @since 7.5
  1379. */
  1380. public void editRow(final int rowIndex, final int columnIndex) {
  1381. if (!enabled) {
  1382. throw new IllegalStateException(
  1383. "Cannot edit row: editor is not enabled");
  1384. }
  1385. if (isWorkPending()) {
  1386. // Request pending a response, don't move try to start another
  1387. // request.
  1388. return;
  1389. }
  1390. if (state != State.INACTIVE && this.rowIndex != rowIndex) {
  1391. if (isBuffered()) {
  1392. throw new IllegalStateException(
  1393. "Cannot edit row: editor already in edit mode");
  1394. } else if (!columnErrors.isEmpty()) {
  1395. // Don't move row if errors are present
  1396. // FIXME: Should attempt bind if error field values have
  1397. // changed.
  1398. return;
  1399. }
  1400. }
  1401. if (columnIndex >= grid.getVisibleColumns().size()) {
  1402. throw new IllegalArgumentException(
  1403. "Edited column index " + columnIndex
  1404. + " was bigger than visible column count.");
  1405. }
  1406. if (this.rowIndex == rowIndex
  1407. && focusedColumnIndex == columnIndex) {
  1408. // NO-OP
  1409. return;
  1410. }
  1411. if (this.rowIndex == rowIndex) {
  1412. if (focusedColumnIndex != columnIndex) {
  1413. if (columnIndex >= grid.getFrozenColumnCount()) {
  1414. // Scroll to new focused column.
  1415. grid.getEscalator().scrollToColumn(columnIndex,
  1416. ScrollDestination.ANY, 0);
  1417. }
  1418. focusedColumnIndex = columnIndex;
  1419. }
  1420. updateHorizontalScrollPosition();
  1421. // Update Grid internal focus and focus widget if possible
  1422. if (focusedColumnIndex >= 0) {
  1423. grid.focusCell(rowIndex, focusedColumnIndex);
  1424. focusColumn(focusedColumnIndex);
  1425. }
  1426. // No need to request anything from the editor handler.
  1427. return;
  1428. }
  1429. state = State.ACTIVATING;
  1430. final Escalator escalator = grid.getEscalator();
  1431. if (escalator.getVisibleRowRange().contains(rowIndex)) {
  1432. show(rowIndex, columnIndex);
  1433. } else {
  1434. vScrollHandler = grid.addScrollHandler(new ScrollHandler() {
  1435. @Override
  1436. public void onScroll(ScrollEvent event) {
  1437. if (escalator.getVisibleRowRange().contains(rowIndex)) {
  1438. show(rowIndex, columnIndex);
  1439. vScrollHandler.removeHandler();
  1440. }
  1441. }
  1442. });
  1443. grid.scrollToRow(rowIndex, isBuffered()
  1444. ? ScrollDestination.MIDDLE : ScrollDestination.ANY);
  1445. }
  1446. }
  1447. /**
  1448. * Cancels the currently active edit and hides the editor. Any changes
  1449. * that are not {@link #save() saved} are lost.
  1450. *
  1451. * @throws IllegalStateException
  1452. * if this editor is not enabled
  1453. * @throws IllegalStateException
  1454. * if this editor is not in edit mode
  1455. */
  1456. public void cancel() {
  1457. if (!enabled) {
  1458. throw new IllegalStateException(
  1459. "Cannot cancel edit: editor is not enabled");
  1460. }
  1461. if (state == State.INACTIVE) {
  1462. throw new IllegalStateException(
  1463. "Cannot cancel edit: editor is not in edit mode");
  1464. }
  1465. handler.cancel(new EditorRequestImpl<T>(grid, rowIndex,
  1466. focusedColumnIndex, null));
  1467. doCancel();
  1468. }
  1469. private void doCancel() {
  1470. hideOverlay();
  1471. state = State.INACTIVE;
  1472. rowIndex = -1;
  1473. focusedColumnIndex = -1;
  1474. grid.getEscalator().setScrollLocked(Direction.VERTICAL, false);
  1475. updateSelectionCheckboxesAsNeeded(true);
  1476. }
  1477. private void updateSelectionCheckboxesAsNeeded(boolean isEnabled) {
  1478. // FIXME: This is too much guessing. Define a better way to do this.
  1479. if (grid.selectionColumn != null && grid.selectionColumn
  1480. .getRenderer() instanceof MultiSelectionRenderer) {
  1481. grid.refreshBody();
  1482. CheckBox checkBox = (CheckBox) grid.getDefaultHeaderRow()
  1483. .getCell(grid.selectionColumn).getWidget();
  1484. checkBox.setEnabled(isEnabled);
  1485. }
  1486. }
  1487. /**
  1488. * Saves any unsaved changes to the data source and hides the editor.
  1489. *
  1490. * @throws IllegalStateException
  1491. * if this editor is not enabled
  1492. * @throws IllegalStateException
  1493. * if this editor is not in edit mode
  1494. */
  1495. public void save() {
  1496. if (!enabled) {
  1497. throw new IllegalStateException(
  1498. "Cannot save: editor is not enabled");
  1499. }
  1500. if (state != State.ACTIVE) {
  1501. throw new IllegalStateException(
  1502. "Cannot save: editor is not in edit mode");
  1503. }
  1504. state = State.SAVING;
  1505. setButtonsEnabled(false);
  1506. saveTimeout.schedule(SAVE_TIMEOUT_MS);
  1507. EditorRequest<T> request = new EditorRequestImpl<T>(grid, rowIndex,
  1508. focusedColumnIndex, saveRequestCallback);
  1509. handler.save(request);
  1510. updateSelectionCheckboxesAsNeeded(true);
  1511. }
  1512. /**
  1513. * Returns the handler responsible for binding data and editor widgets
  1514. * to this editor.
  1515. *
  1516. * @return the editor handler or null if not set
  1517. */
  1518. public EditorHandler<T> getHandler() {
  1519. return handler;
  1520. }
  1521. /**
  1522. * Sets the handler responsible for binding data and editor widgets to
  1523. * this editor.
  1524. *
  1525. * @param rowHandler
  1526. * the new editor handler
  1527. *
  1528. * @throws IllegalStateException
  1529. * if this editor is currently in edit mode
  1530. */
  1531. public void setHandler(EditorHandler<T> rowHandler) {
  1532. if (state != State.INACTIVE) {
  1533. throw new IllegalStateException(
  1534. "Cannot set EditorHandler: editor is currently in edit mode");
  1535. }
  1536. handler = rowHandler;
  1537. }
  1538. public boolean isEnabled() {
  1539. return enabled;
  1540. }
  1541. /**
  1542. * Sets the enabled state of this editor.
  1543. *
  1544. * @param enabled
  1545. * true if enabled, false otherwise
  1546. *
  1547. * @throws IllegalStateException
  1548. * if in edit mode and trying to disable
  1549. * @throws IllegalStateException
  1550. * if the editor handler is not set
  1551. */
  1552. public void setEnabled(boolean enabled) {
  1553. if (enabled == false && state != State.INACTIVE) {
  1554. throw new IllegalStateException(
  1555. "Cannot disable: editor is in edit mode");
  1556. } else if (enabled == true && getHandler() == null) {
  1557. throw new IllegalStateException(
  1558. "Cannot enable: EditorHandler not set");
  1559. }
  1560. this.enabled = enabled;
  1561. }
  1562. protected void show(int rowIndex, int columnIndex) {
  1563. if (state == State.ACTIVATING) {
  1564. state = State.BINDING;
  1565. bindTimeout.schedule(BIND_TIMEOUT_MS);
  1566. EditorRequest<T> request = new EditorRequestImpl<T>(grid,
  1567. rowIndex, columnIndex, bindRequestCallback);
  1568. handler.bind(request);
  1569. grid.getEscalator().setScrollLocked(Direction.VERTICAL,
  1570. isBuffered());
  1571. updateSelectionCheckboxesAsNeeded(false);
  1572. }
  1573. }
  1574. protected void setGrid(final Grid<T> grid) {
  1575. assert grid != null : "Grid cannot be null";
  1576. assert this.grid == null : "Can only attach editor to Grid once";
  1577. this.grid = grid;
  1578. }
  1579. protected State getState() {
  1580. return state;
  1581. }
  1582. protected void setState(State state) {
  1583. this.state = state;
  1584. }
  1585. /**
  1586. * Returns the editor widget associated with the given column. If the
  1587. * editor is not active or the column is not
  1588. * {@link Grid.Column#isEditable() editable}, returns null.
  1589. *
  1590. * @param column
  1591. * the column
  1592. * @return the widget if the editor is open and the column is editable,
  1593. * null otherwise
  1594. */
  1595. protected Widget getWidget(Column<?, T> column) {
  1596. return columnToWidget.get(column);
  1597. }
  1598. /**
  1599. * Equivalent to {@code showOverlay()}. The argument is ignored.
  1600. *
  1601. * @param unused
  1602. * ignored argument
  1603. *
  1604. * @deprecated As of 7.5, use {@link #showOverlay()} instead.
  1605. */
  1606. @Deprecated
  1607. protected void showOverlay(TableRowElement unused) {
  1608. showOverlay();
  1609. }
  1610. /**
  1611. * Opens the editor overlay over the table row indicated by
  1612. * {@link #getRow()}.
  1613. *
  1614. * @since 7.5
  1615. */
  1616. protected void showOverlay() {
  1617. // Ensure overlay is hidden initially
  1618. hideOverlay();
  1619. DivElement gridElement = DivElement.as(grid.getElement());
  1620. TableRowElement tr = grid.getEscalator().getBody()
  1621. .getRowElement(rowIndex);
  1622. hScrollHandler = grid.addScrollHandler(new ScrollHandler() {
  1623. @Override
  1624. public void onScroll(ScrollEvent event) {
  1625. updateHorizontalScrollPosition();
  1626. updateVerticalScrollPosition();
  1627. }
  1628. });
  1629. gridElement.appendChild(editorOverlay);
  1630. editorOverlay.appendChild(frozenCellWrapper);
  1631. editorOverlay.appendChild(cellWrapper);
  1632. editorOverlay.appendChild(messageAndButtonsWrapper);
  1633. updateBufferedStyleName();
  1634. int frozenColumns = grid.getVisibleFrozenColumnCount();
  1635. double frozenColumnsWidth = 0;
  1636. double cellHeight = 0;
  1637. for (int i = 0; i < tr.getCells().getLength(); i++) {
  1638. Element cell = createCell(tr.getCells().getItem(i));
  1639. cellHeight = Math.max(cellHeight,
  1640. WidgetUtil.getRequiredHeightBoundingClientRectDouble(
  1641. tr.getCells().getItem(i)));
  1642. Column<?, T> column = grid.getVisibleColumn(i);
  1643. if (i < frozenColumns) {
  1644. frozenCellWrapper.appendChild(cell);
  1645. frozenColumnsWidth += WidgetUtil
  1646. .getRequiredWidthBoundingClientRectDouble(
  1647. tr.getCells().getItem(i));
  1648. } else {
  1649. cellWrapper.appendChild(cell);
  1650. }
  1651. if (column.isEditable()) {
  1652. Widget editor = getHandler().getWidget(column);
  1653. if (editor != null) {
  1654. columnToWidget.put(column, editor);
  1655. grid.attachWidget(editor, cell);
  1656. }
  1657. if (i == focusedColumnIndex) {
  1658. if (BrowserInfo.get().isIE8()) {
  1659. Scheduler.get().scheduleDeferred(fieldFocusCommand);
  1660. } else {
  1661. focusColumn(focusedColumnIndex);
  1662. }
  1663. }
  1664. } else {
  1665. cell.addClassName(NOT_EDITABLE_CLASS_NAME);
  1666. cell.addClassName(tr.getCells().getItem(i).getClassName());
  1667. // If the focused or frozen stylename is present it should
  1668. // not be inherited by the editor cell as it is not useful
  1669. // in the editor and would look broken without additional
  1670. // style rules. This is a bit of a hack.
  1671. cell.removeClassName(grid.cellFocusStyleName);
  1672. cell.removeClassName("frozen");
  1673. if (column == grid.selectionColumn) {
  1674. // Duplicate selection column CheckBox
  1675. pinnedRowHandle = grid.getDataSource().getHandle(
  1676. grid.getDataSource().getRow(rowIndex));
  1677. pinnedRowHandle.pin();
  1678. // We need to duplicate the selection CheckBox for the
  1679. // editor overlay since the original one is hidden by
  1680. // the overlay
  1681. final CheckBox checkBox = GWT.create(CheckBox.class);
  1682. checkBox.setValue(
  1683. grid.isSelected(pinnedRowHandle.getRow()));
  1684. checkBox.sinkEvents(Event.ONCLICK);
  1685. checkBox.addClickHandler(new ClickHandler() {
  1686. @Override
  1687. public void onClick(ClickEvent event) {
  1688. T row = pinnedRowHandle.getRow();
  1689. if (grid.isSelected(row)) {
  1690. grid.deselect(row);
  1691. } else {
  1692. grid.select(row);
  1693. }
  1694. }
  1695. });
  1696. grid.attachWidget(checkBox, cell);
  1697. columnToWidget.put(column, checkBox);
  1698. // Only enable CheckBox in non-buffered mode
  1699. checkBox.setEnabled(!isBuffered());
  1700. } else if (!(column
  1701. .getRenderer() instanceof WidgetRenderer)) {
  1702. // Copy non-widget content directly
  1703. cell.setInnerHTML(
  1704. tr.getCells().getItem(i).getInnerHTML());
  1705. }
  1706. }
  1707. }
  1708. setBounds(frozenCellWrapper, 0, 0, frozenColumnsWidth, 0);
  1709. setBounds(cellWrapper, frozenColumnsWidth, 0,
  1710. tr.getOffsetWidth() - frozenColumnsWidth, cellHeight);
  1711. // Only add these elements once
  1712. if (!messageAndButtonsWrapper.isOrHasChild(messageWrapper)) {
  1713. messageAndButtonsWrapper.appendChild(messageWrapper);
  1714. messageAndButtonsWrapper.appendChild(buttonsWrapper);
  1715. }
  1716. if (isBuffered()) {
  1717. grid.attachWidget(saveButton, buttonsWrapper);
  1718. grid.attachWidget(cancelButton, buttonsWrapper);
  1719. }
  1720. setMessageAndButtonsWrapperVisible(isBuffered());
  1721. updateHorizontalScrollPosition();
  1722. AbstractRowContainer body = (AbstractRowContainer) grid
  1723. .getEscalator().getBody();
  1724. double rowTop = body.getRowTop(tr);
  1725. int bodyTop = body.getElement().getAbsoluteTop();
  1726. int gridTop = gridElement.getAbsoluteTop();
  1727. double overlayTop = rowTop + bodyTop - gridTop;
  1728. originalScrollTop = grid.getScrollTop();
  1729. if (!isBuffered() || buttonsShouldBeRenderedBelow(tr)) {
  1730. // Default case, editor buttons are below the edited row
  1731. editorOverlay.getStyle().setTop(overlayTop, Unit.PX);
  1732. originalTop = overlayTop;
  1733. editorOverlay.getStyle().clearBottom();
  1734. } else {
  1735. // Move message and buttons wrapper on top of cell wrapper if
  1736. // there is not enough space visible space under and fix the
  1737. // overlay from the bottom
  1738. editorOverlay.insertFirst(messageAndButtonsWrapper);
  1739. int gridHeight = grid.getElement().getOffsetHeight();
  1740. editorOverlay.getStyle().setBottom(
  1741. gridHeight - overlayTop - tr.getOffsetHeight(),
  1742. Unit.PX);
  1743. editorOverlay.getStyle().clearTop();
  1744. }
  1745. // Do not render over the vertical scrollbar
  1746. editorOverlay.getStyle().setWidth(grid.escalator.getInnerWidth(),
  1747. Unit.PX);
  1748. }
  1749. private void focusColumn(int colIndex) {
  1750. if (colIndex < 0 || colIndex >= grid.getVisibleColumns().size()) {
  1751. // NO-OP
  1752. return;
  1753. }
  1754. Widget editor = getWidget(grid.getVisibleColumn(colIndex));
  1755. if (editor instanceof Focusable) {
  1756. ((Focusable) editor).focus();
  1757. } else if (editor instanceof com.google.gwt.user.client.ui.Focusable) {
  1758. ((com.google.gwt.user.client.ui.Focusable) editor)
  1759. .setFocus(true);
  1760. } else {
  1761. grid.focus();
  1762. }
  1763. }
  1764. private boolean buttonsShouldBeRenderedBelow(TableRowElement tr) {
  1765. TableSectionElement tfoot = grid.escalator.getFooter().getElement();
  1766. double tfootPageTop = WidgetUtil.getBoundingClientRect(tfoot)
  1767. .getTop();
  1768. double trPageBottom = WidgetUtil.getBoundingClientRect(tr)
  1769. .getBottom();
  1770. int messageAndButtonsHeight = messageAndButtonsWrapper
  1771. .getOffsetHeight();
  1772. double bottomOfButtons = trPageBottom + messageAndButtonsHeight;
  1773. return bottomOfButtons < tfootPageTop;
  1774. }
  1775. protected void hideOverlay() {
  1776. if (editorOverlay.getParentElement() == null) {
  1777. return;
  1778. }
  1779. if (pinnedRowHandle != null) {
  1780. pinnedRowHandle.unpin();
  1781. pinnedRowHandle = null;
  1782. }
  1783. for (HandlerRegistration r : focusHandlers) {
  1784. r.removeHandler();
  1785. }
  1786. focusHandlers.clear();
  1787. for (Widget w : columnToWidget.values()) {
  1788. setParent(w, null);
  1789. }
  1790. columnToWidget.clear();
  1791. if (isBuffered()) {
  1792. grid.detachWidget(saveButton);
  1793. grid.detachWidget(cancelButton);
  1794. }
  1795. editorOverlay.removeAllChildren();
  1796. cellWrapper.removeAllChildren();
  1797. frozenCellWrapper.removeAllChildren();
  1798. editorOverlay.removeFromParent();
  1799. hScrollHandler.removeHandler();
  1800. clearEditorColumnErrors();
  1801. }
  1802. private void updateBufferedStyleName() {
  1803. if (isBuffered()) {
  1804. editorOverlay.removeClassName("unbuffered");
  1805. editorOverlay.addClassName("buffered");
  1806. } else {
  1807. editorOverlay.removeClassName("buffered");
  1808. editorOverlay.addClassName("unbuffered");
  1809. }
  1810. }
  1811. protected void setStylePrimaryName(String primaryName) {
  1812. if (styleName != null) {
  1813. editorOverlay.removeClassName(styleName);
  1814. cellWrapper.removeClassName(styleName + "-cells");
  1815. frozenCellWrapper.removeClassName(styleName + "-cells");
  1816. messageAndButtonsWrapper.removeClassName(styleName + "-footer");
  1817. messageWrapper.removeClassName(styleName + "-message");
  1818. buttonsWrapper.removeClassName(styleName + "-buttons");
  1819. saveButton.removeStyleName(styleName + "-save");
  1820. cancelButton.removeStyleName(styleName + "-cancel");
  1821. }
  1822. styleName = primaryName + "-editor";
  1823. editorOverlay.setClassName(styleName);
  1824. cellWrapper.setClassName(styleName + "-cells");
  1825. frozenCellWrapper.setClassName(styleName + "-cells frozen");
  1826. messageAndButtonsWrapper.setClassName(styleName + "-footer");
  1827. messageWrapper.setClassName(styleName + "-message");
  1828. buttonsWrapper.setClassName(styleName + "-buttons");
  1829. saveButton.setStyleName(styleName + "-save");
  1830. cancelButton.setStyleName(styleName + "-cancel");
  1831. }
  1832. /**
  1833. * Creates an editor cell corresponding to the given table cell. The
  1834. * returned element is empty and has the same dimensions and position as
  1835. * the table cell.
  1836. *
  1837. * @param td
  1838. * the table cell used as a reference
  1839. * @return an editor cell corresponding to the given cell
  1840. */
  1841. protected Element createCell(TableCellElement td) {
  1842. DivElement cell = DivElement.as(DOM.createDiv());
  1843. double width = WidgetUtil
  1844. .getRequiredWidthBoundingClientRectDouble(td);
  1845. double height = WidgetUtil
  1846. .getRequiredHeightBoundingClientRectDouble(td);
  1847. setBounds(cell, td.getOffsetLeft(), td.getOffsetTop(), width,
  1848. height);
  1849. return cell;
  1850. }
  1851. private static void setBounds(Element e, double left, double top,
  1852. double width, double height) {
  1853. Style style = e.getStyle();
  1854. style.setLeft(left, Unit.PX);
  1855. style.setTop(top, Unit.PX);
  1856. style.setWidth(width, Unit.PX);
  1857. style.setHeight(height, Unit.PX);
  1858. }
  1859. private void updateHorizontalScrollPosition() {
  1860. double scrollLeft = grid.getScrollLeft();
  1861. cellWrapper.getStyle().setLeft(
  1862. frozenCellWrapper.getOffsetWidth() - scrollLeft, Unit.PX);
  1863. }
  1864. /**
  1865. * Moves the editor overlay on scroll so that it stays on top of the
  1866. * edited row. This will also snap the editor to top or bottom of the
  1867. * row container if the edited row is scrolled out of the visible area.
  1868. */
  1869. private void updateVerticalScrollPosition() {
  1870. if (isBuffered()) {
  1871. return;
  1872. }
  1873. double newScrollTop = grid.getScrollTop();
  1874. int gridTop = grid.getElement().getAbsoluteTop();
  1875. int editorHeight = editorOverlay.getOffsetHeight();
  1876. Escalator escalator = grid.getEscalator();
  1877. TableSectionElement header = escalator.getHeader().getElement();
  1878. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  1879. int headerBottom = header.getAbsoluteBottom();
  1880. double newTop = originalTop - (newScrollTop - originalScrollTop);
  1881. if (newTop + gridTop < headerBottom) {
  1882. // Snap editor to top of the row container
  1883. newTop = header.getOffsetHeight();
  1884. } else if (newTop + gridTop > footerTop - editorHeight) {
  1885. // Snap editor to the bottom of the row container
  1886. newTop = footerTop - editorHeight - gridTop;
  1887. }
  1888. editorOverlay.getStyle().setTop(newTop, Unit.PX);
  1889. }
  1890. protected void setGridEnabled(boolean enabled) {
  1891. // TODO: This should be informed to handler as well so possible
  1892. // fields can be disabled.
  1893. setButtonsEnabled(enabled);
  1894. }
  1895. private void setButtonsEnabled(boolean enabled) {
  1896. saveButton.setEnabled(enabled);
  1897. cancelButton.setEnabled(enabled);
  1898. }
  1899. public void setSaveCaption(String saveCaption)
  1900. throws IllegalArgumentException {
  1901. if (saveCaption == null) {
  1902. throw new IllegalArgumentException(
  1903. "Save caption cannot be null");
  1904. }
  1905. saveButton.setText(saveCaption);
  1906. }
  1907. public String getSaveCaption() {
  1908. return saveButton.getText();
  1909. }
  1910. public void setCancelCaption(String cancelCaption)
  1911. throws IllegalArgumentException {
  1912. if (cancelCaption == null) {
  1913. throw new IllegalArgumentException(
  1914. "Cancel caption cannot be null");
  1915. }
  1916. cancelButton.setText(cancelCaption);
  1917. }
  1918. public String getCancelCaption() {
  1919. return cancelButton.getText();
  1920. }
  1921. public void setEditorColumnError(Column<?, T> column,
  1922. boolean hasError) {
  1923. if (state != State.ACTIVE && state != State.SAVING) {
  1924. throw new IllegalStateException("Cannot set cell error "
  1925. + "status: editor is neither active nor saving.");
  1926. }
  1927. if (isEditorColumnError(column) == hasError) {
  1928. return;
  1929. }
  1930. Element editorCell = getWidget(column).getElement()
  1931. .getParentElement();
  1932. if (hasError) {
  1933. editorCell.addClassName(ERROR_CLASS_NAME);
  1934. columnErrors.add(column);
  1935. } else {
  1936. editorCell.removeClassName(ERROR_CLASS_NAME);
  1937. columnErrors.remove(column);
  1938. }
  1939. }
  1940. public void clearEditorColumnErrors() {
  1941. /*
  1942. * editorOverlay has no children if it's not active, effectively
  1943. * making this loop a NOOP.
  1944. */
  1945. Element e = editorOverlay.getFirstChildElement();
  1946. while (e != null) {
  1947. e.removeClassName(ERROR_CLASS_NAME);
  1948. e = e.getNextSiblingElement();
  1949. }
  1950. columnErrors.clear();
  1951. }
  1952. public boolean isEditorColumnError(Column<?, T> column) {
  1953. return columnErrors.contains(column);
  1954. }
  1955. public void setBuffered(boolean buffered) {
  1956. this.buffered = buffered;
  1957. setMessageAndButtonsWrapperVisible(buffered);
  1958. }
  1959. public boolean isBuffered() {
  1960. return buffered;
  1961. }
  1962. private void setMessageAndButtonsWrapperVisible(boolean visible) {
  1963. if (visible) {
  1964. messageAndButtonsWrapper.getStyle().clearDisplay();
  1965. } else {
  1966. messageAndButtonsWrapper.getStyle().setDisplay(Display.NONE);
  1967. }
  1968. }
  1969. /**
  1970. * Sets the event handler for this Editor.
  1971. *
  1972. * @since 7.6
  1973. * @param handler
  1974. * the new event handler
  1975. */
  1976. public void setEventHandler(EventHandler<T> handler) {
  1977. eventHandler = handler;
  1978. }
  1979. /**
  1980. * Returns the event handler of this Editor.
  1981. *
  1982. * @since 7.6
  1983. * @return the current event handler
  1984. */
  1985. public EventHandler<T> getEventHandler() {
  1986. return eventHandler;
  1987. }
  1988. @Override
  1989. public boolean isWorkPending() {
  1990. return saveTimeout.isRunning() || bindTimeout.isRunning();
  1991. }
  1992. protected int getElementColumn(Element e) {
  1993. int frozenCells = frozenCellWrapper.getChildCount();
  1994. if (frozenCellWrapper.isOrHasChild(e)) {
  1995. for (int i = 0; i < frozenCells; ++i) {
  1996. if (frozenCellWrapper.getChild(i).isOrHasChild(e)) {
  1997. return i;
  1998. }
  1999. }
  2000. }
  2001. if (cellWrapper.isOrHasChild(e)) {
  2002. for (int i = 0; i < cellWrapper.getChildCount(); ++i) {
  2003. if (cellWrapper.getChild(i).isOrHasChild(e)) {
  2004. return i + frozenCells;
  2005. }
  2006. }
  2007. }
  2008. return -1;
  2009. }
  2010. }
  2011. public static abstract class AbstractGridKeyEvent<HANDLER extends AbstractGridKeyEventHandler>
  2012. extends KeyEvent<HANDLER> {
  2013. private Grid<?> grid;
  2014. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  2015. getBrowserEventType(), this);
  2016. private final CellReference<?> targetCell;
  2017. public AbstractGridKeyEvent(Grid<?> grid, CellReference<?> targetCell) {
  2018. this.grid = grid;
  2019. this.targetCell = targetCell;
  2020. }
  2021. protected abstract String getBrowserEventType();
  2022. /**
  2023. * Gets the Grid instance for this event.
  2024. *
  2025. * @return grid
  2026. */
  2027. public Grid<?> getGrid() {
  2028. return grid;
  2029. }
  2030. /**
  2031. * Gets the focused cell for this event.
  2032. *
  2033. * @return focused cell
  2034. */
  2035. public CellReference<?> getFocusedCell() {
  2036. return targetCell;
  2037. }
  2038. @Override
  2039. protected void dispatch(HANDLER handler) {
  2040. EventTarget target = getNativeEvent().getEventTarget();
  2041. if (Element.is(target)
  2042. && !grid.isElementInChildWidget(Element.as(target))) {
  2043. Section section = Section.FOOTER;
  2044. final RowContainer container = grid.cellFocusHandler.containerWithFocus;
  2045. if (container == grid.escalator.getHeader()) {
  2046. section = Section.HEADER;
  2047. } else if (container == grid.escalator.getBody()) {
  2048. section = Section.BODY;
  2049. }
  2050. doDispatch(handler, section);
  2051. }
  2052. }
  2053. protected abstract void doDispatch(HANDLER handler, Section section);
  2054. @Override
  2055. public Type<HANDLER> getAssociatedType() {
  2056. return associatedType;
  2057. }
  2058. }
  2059. public static abstract class AbstractGridMouseEvent<HANDLER extends AbstractGridMouseEventHandler>
  2060. extends MouseEvent<HANDLER> {
  2061. private Grid<?> grid;
  2062. private final CellReference<?> targetCell;
  2063. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  2064. getBrowserEventType(), this);
  2065. public AbstractGridMouseEvent(Grid<?> grid,
  2066. CellReference<?> targetCell) {
  2067. this.grid = grid;
  2068. this.targetCell = targetCell;
  2069. }
  2070. protected abstract String getBrowserEventType();
  2071. /**
  2072. * Gets the Grid instance for this event.
  2073. *
  2074. * @return grid
  2075. */
  2076. public Grid<?> getGrid() {
  2077. return grid;
  2078. }
  2079. /**
  2080. * Gets the reference of target cell for this event.
  2081. *
  2082. * @return target cell
  2083. */
  2084. public CellReference<?> getTargetCell() {
  2085. return targetCell;
  2086. }
  2087. @Override
  2088. protected void dispatch(HANDLER handler) {
  2089. EventTarget target = getNativeEvent().getEventTarget();
  2090. if (!Element.is(target)) {
  2091. // Target is not an element
  2092. return;
  2093. }
  2094. Element targetElement = Element.as(target);
  2095. if (grid.isElementInChildWidget(targetElement)) {
  2096. // Target is some widget inside of Grid
  2097. return;
  2098. }
  2099. final RowContainer container = grid.escalator
  2100. .findRowContainer(targetElement);
  2101. if (container == null) {
  2102. // No container for given element
  2103. return;
  2104. }
  2105. Section section = Section.FOOTER;
  2106. if (container == grid.escalator.getHeader()) {
  2107. section = Section.HEADER;
  2108. } else if (container == grid.escalator.getBody()) {
  2109. section = Section.BODY;
  2110. }
  2111. doDispatch(handler, section);
  2112. }
  2113. protected abstract void doDispatch(HANDLER handler, Section section);
  2114. @Override
  2115. public Type<HANDLER> getAssociatedType() {
  2116. return associatedType;
  2117. }
  2118. }
  2119. private static final String CUSTOM_STYLE_PROPERTY_NAME = "customStyle";
  2120. /**
  2121. * An initial height that is given to new details rows before rendering the
  2122. * appropriate widget that we then can be measure
  2123. *
  2124. * @see GridSpacerUpdater
  2125. */
  2126. private static final double DETAILS_ROW_INITIAL_HEIGHT = 50;
  2127. private EventCellReference<T> eventCell = new EventCellReference<T>(this);
  2128. private GridKeyDownEvent keyDown = new GridKeyDownEvent(this, eventCell);
  2129. private GridKeyUpEvent keyUp = new GridKeyUpEvent(this, eventCell);
  2130. private GridKeyPressEvent keyPress = new GridKeyPressEvent(this, eventCell);
  2131. private GridClickEvent clickEvent = new GridClickEvent(this, eventCell);
  2132. private GridDoubleClickEvent doubleClickEvent = new GridDoubleClickEvent(
  2133. this, eventCell);
  2134. private class CellFocusHandler {
  2135. private RowContainer containerWithFocus = escalator.getBody();
  2136. private int rowWithFocus = 0;
  2137. private Range cellFocusRange = Range.withLength(0, 1);
  2138. private int lastFocusedBodyRow = 0;
  2139. private int lastFocusedHeaderRow = 0;
  2140. private int lastFocusedFooterRow = 0;
  2141. private TableCellElement cellWithFocusStyle = null;
  2142. private TableRowElement rowWithFocusStyle = null;
  2143. public CellFocusHandler() {
  2144. sinkEvents(getNavigationEvents());
  2145. }
  2146. private Cell getFocusedCell() {
  2147. return new Cell(rowWithFocus, cellFocusRange.getStart(),
  2148. cellWithFocusStyle);
  2149. }
  2150. /**
  2151. * Sets style names for given cell when needed.
  2152. */
  2153. public void updateFocusedCellStyle(FlyweightCell cell,
  2154. RowContainer cellContainer) {
  2155. int cellRow = cell.getRow();
  2156. int cellColumn = cell.getColumn();
  2157. int colSpan = cell.getColSpan();
  2158. boolean columnHasFocus = Range.withLength(cellColumn, colSpan)
  2159. .intersects(cellFocusRange);
  2160. if (cellContainer == containerWithFocus) {
  2161. // Cell is in the current container
  2162. if (cellRow == rowWithFocus && columnHasFocus) {
  2163. if (cellWithFocusStyle != cell.getElement()) {
  2164. // Cell is correct but it does not have focused style
  2165. if (cellWithFocusStyle != null) {
  2166. // Remove old focus style
  2167. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2168. false);
  2169. }
  2170. cellWithFocusStyle = cell.getElement();
  2171. // Add focus style to correct cell.
  2172. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2173. true);
  2174. }
  2175. } else if (cellWithFocusStyle == cell.getElement()) {
  2176. // Due to escalator reusing cells, a new cell has the same
  2177. // element but is not the focused cell.
  2178. setStyleName(cellWithFocusStyle, cellFocusStyleName, false);
  2179. cellWithFocusStyle = null;
  2180. }
  2181. }
  2182. }
  2183. /**
  2184. * Sets focus style for the given row if needed.
  2185. *
  2186. * @param row
  2187. * a row object
  2188. */
  2189. public void updateFocusedRowStyle(Row row) {
  2190. if (rowWithFocus == row.getRow()
  2191. && containerWithFocus == escalator.getBody()) {
  2192. if (row.getElement() != rowWithFocusStyle) {
  2193. // Row should have focus style but does not have it.
  2194. if (rowWithFocusStyle != null) {
  2195. setStyleName(rowWithFocusStyle, rowFocusStyleName,
  2196. false);
  2197. }
  2198. rowWithFocusStyle = row.getElement();
  2199. setStyleName(rowWithFocusStyle, rowFocusStyleName, true);
  2200. }
  2201. } else if (rowWithFocusStyle == row.getElement()
  2202. || (containerWithFocus != escalator.getBody()
  2203. && rowWithFocusStyle != null)) {
  2204. // Remove focus style.
  2205. setStyleName(rowWithFocusStyle, rowFocusStyleName, false);
  2206. rowWithFocusStyle = null;
  2207. }
  2208. }
  2209. /**
  2210. * Sets the currently focused.
  2211. * <p>
  2212. * <em>NOTE:</em> the column index is the index in DOM, not the logical
  2213. * column index which includes hidden columns.
  2214. *
  2215. * @param rowIndex
  2216. * the index of the row having focus
  2217. * @param columnIndexDOM
  2218. * the index of the cell having focus
  2219. * @param container
  2220. * the row container having focus
  2221. */
  2222. private void setCellFocus(int rowIndex, int columnIndexDOM,
  2223. RowContainer container) {
  2224. if (container == null || rowIndex == rowWithFocus
  2225. && cellFocusRange.contains(columnIndexDOM)
  2226. && container == this.containerWithFocus) {
  2227. return;
  2228. }
  2229. int oldRow = rowWithFocus;
  2230. rowWithFocus = rowIndex;
  2231. Range oldRange = cellFocusRange;
  2232. if (container == escalator.getBody()) {
  2233. scrollToRow(rowWithFocus);
  2234. cellFocusRange = Range.withLength(columnIndexDOM, 1);
  2235. } else {
  2236. int i = 0;
  2237. Element cell = container.getRowElement(rowWithFocus)
  2238. .getFirstChildElement();
  2239. do {
  2240. int colSpan = cell
  2241. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  2242. Range cellRange = Range.withLength(i, colSpan);
  2243. if (cellRange.contains(columnIndexDOM)) {
  2244. cellFocusRange = cellRange;
  2245. break;
  2246. }
  2247. cell = cell.getNextSiblingElement();
  2248. ++i;
  2249. } while (cell != null);
  2250. }
  2251. int columnIndex = getColumns()
  2252. .indexOf(getVisibleColumn(columnIndexDOM));
  2253. if (columnIndex >= escalator.getColumnConfiguration()
  2254. .getFrozenColumnCount()) {
  2255. escalator.scrollToColumn(columnIndexDOM, ScrollDestination.ANY,
  2256. 10);
  2257. }
  2258. if (this.containerWithFocus == container) {
  2259. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  2260. refreshRow(oldRow);
  2261. } else {
  2262. refreshHeader();
  2263. refreshFooter();
  2264. }
  2265. } else {
  2266. RowContainer oldContainer = this.containerWithFocus;
  2267. this.containerWithFocus = container;
  2268. if (oldContainer == escalator.getBody()) {
  2269. lastFocusedBodyRow = oldRow;
  2270. } else if (oldContainer == escalator.getHeader()) {
  2271. lastFocusedHeaderRow = oldRow;
  2272. } else {
  2273. lastFocusedFooterRow = oldRow;
  2274. }
  2275. if (!oldRange.equals(cellFocusRange)) {
  2276. refreshHeader();
  2277. refreshFooter();
  2278. if (oldContainer == escalator.getBody()) {
  2279. oldContainer.refreshRows(oldRow, 1);
  2280. }
  2281. } else {
  2282. oldContainer.refreshRows(oldRow, 1);
  2283. }
  2284. }
  2285. refreshRow(rowWithFocus);
  2286. }
  2287. /**
  2288. * Sets focus on a cell.
  2289. *
  2290. * <p>
  2291. * <em>Note</em>: cell focus is not the same as JavaScript's
  2292. * {@code document.activeElement}.
  2293. *
  2294. * @param cell
  2295. * a cell object
  2296. */
  2297. public void setCellFocus(CellReference<T> cell) {
  2298. setCellFocus(cell.getRowIndex(), cell.getColumnIndexDOM(),
  2299. escalator.findRowContainer(cell.getElement()));
  2300. }
  2301. /**
  2302. * Gets list of events that can be used for cell focusing.
  2303. *
  2304. * @return list of navigation related event types
  2305. */
  2306. public Collection<String> getNavigationEvents() {
  2307. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  2308. }
  2309. /**
  2310. * Handle events that can move the cell focus.
  2311. */
  2312. public void handleNavigationEvent(Event event, CellReference<T> cell) {
  2313. if (event.getType().equals(BrowserEvents.CLICK)) {
  2314. setCellFocus(cell);
  2315. // Grid should have focus when clicked.
  2316. getElement().focus();
  2317. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  2318. int newRow = rowWithFocus;
  2319. RowContainer newContainer = containerWithFocus;
  2320. int newColumn = cellFocusRange.getStart();
  2321. switch (event.getKeyCode()) {
  2322. case KeyCodes.KEY_DOWN:
  2323. ++newRow;
  2324. break;
  2325. case KeyCodes.KEY_UP:
  2326. --newRow;
  2327. break;
  2328. case KeyCodes.KEY_RIGHT:
  2329. if (cellFocusRange.getEnd() >= getVisibleColumns().size()) {
  2330. return;
  2331. }
  2332. newColumn = cellFocusRange.getEnd();
  2333. break;
  2334. case KeyCodes.KEY_LEFT:
  2335. if (newColumn == 0) {
  2336. return;
  2337. }
  2338. --newColumn;
  2339. break;
  2340. case KeyCodes.KEY_TAB:
  2341. if (event.getShiftKey()) {
  2342. newContainer = getPreviousContainer(containerWithFocus);
  2343. } else {
  2344. newContainer = getNextContainer(containerWithFocus);
  2345. }
  2346. if (newContainer == containerWithFocus) {
  2347. return;
  2348. }
  2349. break;
  2350. case KeyCodes.KEY_HOME:
  2351. if (newContainer.getRowCount() > 0) {
  2352. newRow = 0;
  2353. }
  2354. break;
  2355. case KeyCodes.KEY_END:
  2356. if (newContainer.getRowCount() > 0) {
  2357. newRow = newContainer.getRowCount() - 1;
  2358. }
  2359. break;
  2360. case KeyCodes.KEY_PAGEDOWN:
  2361. case KeyCodes.KEY_PAGEUP:
  2362. if (newContainer.getRowCount() > 0) {
  2363. boolean down = event
  2364. .getKeyCode() == KeyCodes.KEY_PAGEDOWN;
  2365. // If there is a visible focused cell, scroll by one
  2366. // page from its position. Otherwise, use the first or
  2367. // the last visible row as the scroll start position.
  2368. // This avoids jumping when using both keyboard and the
  2369. // scroll bar for scrolling.
  2370. int firstVisible = getFirstVisibleRowIndex();
  2371. int lastVisible = getLastVisibleRowIndex();
  2372. if (newRow < firstVisible || newRow > lastVisible) {
  2373. newRow = down ? lastVisible : firstVisible;
  2374. }
  2375. // Scroll by a little less than the visible area to
  2376. // account for the possibility that the top and the
  2377. // bottom row are only partially visible.
  2378. int moveFocusBy = Math.max(1,
  2379. lastVisible - firstVisible - 1);
  2380. moveFocusBy *= down ? 1 : -1;
  2381. newRow += moveFocusBy;
  2382. newRow = Math.max(0, Math
  2383. .min(newContainer.getRowCount() - 1, newRow));
  2384. }
  2385. break;
  2386. default:
  2387. return;
  2388. }
  2389. if (newContainer != containerWithFocus) {
  2390. if (newContainer == escalator.getBody()) {
  2391. newRow = lastFocusedBodyRow;
  2392. } else if (newContainer == escalator.getHeader()) {
  2393. newRow = lastFocusedHeaderRow;
  2394. } else {
  2395. newRow = lastFocusedFooterRow;
  2396. }
  2397. } else if (newRow < 0) {
  2398. newContainer = getPreviousContainer(newContainer);
  2399. if (newContainer == containerWithFocus) {
  2400. newRow = 0;
  2401. } else if (newContainer == escalator.getBody()) {
  2402. newRow = getLastVisibleRowIndex();
  2403. } else {
  2404. newRow = newContainer.getRowCount() - 1;
  2405. }
  2406. } else if (newRow >= containerWithFocus.getRowCount()) {
  2407. newContainer = getNextContainer(newContainer);
  2408. if (newContainer == containerWithFocus) {
  2409. newRow = containerWithFocus.getRowCount() - 1;
  2410. } else if (newContainer == escalator.getBody()) {
  2411. newRow = getFirstVisibleRowIndex();
  2412. } else {
  2413. newRow = 0;
  2414. }
  2415. }
  2416. if (newContainer.getRowCount() == 0) {
  2417. /*
  2418. * There are no rows in the container. Can't change the
  2419. * focused cell.
  2420. */
  2421. return;
  2422. }
  2423. event.preventDefault();
  2424. event.stopPropagation();
  2425. setCellFocus(newRow, newColumn, newContainer);
  2426. }
  2427. }
  2428. private RowContainer getPreviousContainer(RowContainer current) {
  2429. if (current == escalator.getFooter()) {
  2430. current = escalator.getBody();
  2431. } else if (current == escalator.getBody()) {
  2432. current = escalator.getHeader();
  2433. } else {
  2434. return current;
  2435. }
  2436. if (current.getRowCount() == 0) {
  2437. return getPreviousContainer(current);
  2438. }
  2439. return current;
  2440. }
  2441. private RowContainer getNextContainer(RowContainer current) {
  2442. if (current == escalator.getHeader()) {
  2443. current = escalator.getBody();
  2444. } else if (current == escalator.getBody()) {
  2445. current = escalator.getFooter();
  2446. } else {
  2447. return current;
  2448. }
  2449. if (current.getRowCount() == 0) {
  2450. return getNextContainer(current);
  2451. }
  2452. return current;
  2453. }
  2454. private void refreshRow(int row) {
  2455. containerWithFocus.refreshRows(row, 1);
  2456. }
  2457. /**
  2458. * Offsets the focused cell's range.
  2459. *
  2460. * @param offset
  2461. * offset for fixing focused cell's range
  2462. */
  2463. public void offsetRangeBy(int offset) {
  2464. cellFocusRange = cellFocusRange.offsetBy(offset);
  2465. }
  2466. /**
  2467. * Informs {@link CellFocusHandler} that certain range of rows has been
  2468. * added to the Grid body. {@link CellFocusHandler} will fix indices
  2469. * accordingly.
  2470. *
  2471. * @param added
  2472. * a range of added rows
  2473. */
  2474. public void rowsAddedToBody(Range added) {
  2475. boolean bodyHasFocus = (containerWithFocus == escalator.getBody());
  2476. boolean insertionIsAboveFocusedCell = (added
  2477. .getStart() <= rowWithFocus);
  2478. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  2479. rowWithFocus += added.length();
  2480. rowWithFocus = Math.min(rowWithFocus,
  2481. escalator.getBody().getRowCount() - 1);
  2482. refreshRow(rowWithFocus);
  2483. }
  2484. }
  2485. /**
  2486. * Informs {@link CellFocusHandler} that certain range of rows has been
  2487. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  2488. * accordingly.
  2489. *
  2490. * @param removed
  2491. * a range of removed rows
  2492. */
  2493. public void rowsRemovedFromBody(Range removed) {
  2494. if (containerWithFocus != escalator.getBody()) {
  2495. return;
  2496. } else if (!removed.contains(rowWithFocus)) {
  2497. if (removed.getStart() > rowWithFocus) {
  2498. return;
  2499. }
  2500. rowWithFocus = rowWithFocus - removed.length();
  2501. } else {
  2502. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  2503. rowWithFocus = removed.getStart();
  2504. } else if (removed.getStart() > 0) {
  2505. rowWithFocus = removed.getStart() - 1;
  2506. } else {
  2507. if (escalator.getHeader().getRowCount() > 0) {
  2508. rowWithFocus = Math.min(lastFocusedHeaderRow,
  2509. escalator.getHeader().getRowCount() - 1);
  2510. containerWithFocus = escalator.getHeader();
  2511. } else if (escalator.getFooter().getRowCount() > 0) {
  2512. rowWithFocus = Math.min(lastFocusedFooterRow,
  2513. escalator.getFooter().getRowCount() - 1);
  2514. containerWithFocus = escalator.getFooter();
  2515. }
  2516. }
  2517. }
  2518. refreshRow(rowWithFocus);
  2519. }
  2520. }
  2521. public final class SelectionColumn extends Column<Boolean, T>
  2522. implements GridEnabledHandler {
  2523. private boolean initDone = false;
  2524. private boolean selected = false;
  2525. private CheckBox selectAllCheckBox;
  2526. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  2527. super(selectColumnRenderer);
  2528. addEnabledHandler(this);
  2529. }
  2530. void initDone() {
  2531. setWidth(-1);
  2532. setEditable(false);
  2533. setResizable(false);
  2534. initDone = true;
  2535. }
  2536. @Override
  2537. protected void setDefaultHeaderContent(HeaderCell selectionCell) {
  2538. /*
  2539. * TODO: Currently the select all check box is shown when multi
  2540. * selection is in use. This might result in malfunctions if no
  2541. * SelectAllHandlers are present.
  2542. *
  2543. * Later on this could be fixed so that it check such handlers
  2544. * exist.
  2545. */
  2546. final SelectionModel.Multi<T> model = (Multi<T>) getSelectionModel();
  2547. if (selectAllCheckBox == null) {
  2548. selectAllCheckBox = GWT.create(CheckBox.class);
  2549. selectAllCheckBox.setStylePrimaryName(
  2550. getStylePrimaryName() + SELECT_ALL_CHECKBOX_CLASSNAME);
  2551. selectAllCheckBox.addValueChangeHandler(
  2552. new ValueChangeHandler<Boolean>() {
  2553. @Override
  2554. public void onValueChange(
  2555. ValueChangeEvent<Boolean> event) {
  2556. if (event.getValue()) {
  2557. fireEvent(new SelectAllEvent<T>(model));
  2558. selected = true;
  2559. } else {
  2560. model.deselectAll();
  2561. selected = false;
  2562. }
  2563. }
  2564. });
  2565. selectAllCheckBox.setValue(selected);
  2566. addHeaderClickHandler(new HeaderClickHandler() {
  2567. @Override
  2568. public void onClick(GridClickEvent event) {
  2569. CellReference<?> targetCell = event.getTargetCell();
  2570. int defaultRowIndex = getHeader().getRows()
  2571. .indexOf(getDefaultHeaderRow());
  2572. if (targetCell.getColumnIndex() == 0 && targetCell
  2573. .getRowIndex() == defaultRowIndex) {
  2574. selectAllCheckBox.setValue(
  2575. !selectAllCheckBox.getValue(), true);
  2576. }
  2577. }
  2578. });
  2579. // Select all with space when "select all" cell is active
  2580. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  2581. @Override
  2582. public void onKeyUp(GridKeyUpEvent event) {
  2583. if (event.getNativeKeyCode() != KeyCodes.KEY_SPACE) {
  2584. return;
  2585. }
  2586. HeaderRow targetHeaderRow = getHeader()
  2587. .getRow(event.getFocusedCell().getRowIndex());
  2588. if (!targetHeaderRow.isDefault()) {
  2589. return;
  2590. }
  2591. if (event.getFocusedCell()
  2592. .getColumn() == SelectionColumn.this) {
  2593. // Send events to ensure state is updated
  2594. selectAllCheckBox.setValue(
  2595. !selectAllCheckBox.getValue(), true);
  2596. }
  2597. }
  2598. });
  2599. } else {
  2600. for (HeaderRow row : header.getRows()) {
  2601. if (row.getCell(this)
  2602. .getType() == GridStaticCellType.WIDGET) {
  2603. // Detach from old header.
  2604. row.getCell(this).setText("");
  2605. }
  2606. }
  2607. }
  2608. selectionCell.setWidget(selectAllCheckBox);
  2609. }
  2610. @Override
  2611. public Column<Boolean, T> setWidth(double pixels) {
  2612. if (pixels != getWidth() && initDone) {
  2613. throw new UnsupportedOperationException("The selection "
  2614. + "column cannot be modified after init");
  2615. } else {
  2616. super.setWidth(pixels);
  2617. }
  2618. return this;
  2619. }
  2620. @Override
  2621. public Boolean getValue(T row) {
  2622. return Boolean.valueOf(isSelected(row));
  2623. }
  2624. @Override
  2625. public Column<Boolean, T> setExpandRatio(int ratio) {
  2626. throw new UnsupportedOperationException(
  2627. "can't change the expand ratio of the selection column");
  2628. }
  2629. @Override
  2630. public int getExpandRatio() {
  2631. return 0;
  2632. }
  2633. @Override
  2634. public Column<Boolean, T> setMaximumWidth(double pixels) {
  2635. throw new UnsupportedOperationException(
  2636. "can't change the maximum width of the selection column");
  2637. }
  2638. @Override
  2639. public double getMaximumWidth() {
  2640. return -1;
  2641. }
  2642. @Override
  2643. public Column<Boolean, T> setMinimumWidth(double pixels) {
  2644. throw new UnsupportedOperationException(
  2645. "can't change the minimum width of the selection column");
  2646. }
  2647. @Override
  2648. public double getMinimumWidth() {
  2649. return -1;
  2650. }
  2651. @Override
  2652. public Column<Boolean, T> setEditable(boolean editable) {
  2653. if (initDone) {
  2654. throw new UnsupportedOperationException(
  2655. "can't set the selection column editable");
  2656. }
  2657. super.setEditable(editable);
  2658. return this;
  2659. }
  2660. /**
  2661. * Sets whether the selection column is enabled.
  2662. *
  2663. * @since 7.7
  2664. * @param enabled
  2665. * <code>true</code> to enable the column, <code>false</code>
  2666. * to disable it.
  2667. */
  2668. public void setEnabled(boolean enabled) {
  2669. if (selectAllCheckBox != null) {
  2670. selectAllCheckBox.setEnabled(enabled);
  2671. }
  2672. }
  2673. @Override
  2674. public void onEnabled(boolean enabled) {
  2675. setEnabled(enabled);
  2676. }
  2677. }
  2678. /**
  2679. * Helper class for performing sorting through the user interface. Controls
  2680. * the sort() method, reporting USER as the event originator. This is a
  2681. * completely internal class, and is, as such, safe to re-name should a more
  2682. * descriptive name come to mind.
  2683. */
  2684. private final class UserSorter {
  2685. private final Timer timer;
  2686. private boolean scheduledMultisort;
  2687. private Column<?, T> column;
  2688. private UserSorter() {
  2689. timer = new Timer() {
  2690. @Override
  2691. public void run() {
  2692. UserSorter.this.sort(column, scheduledMultisort);
  2693. }
  2694. };
  2695. }
  2696. /**
  2697. * Toggle sorting for a cell. If the multisort parameter is set to true,
  2698. * the cell's sort order is modified as a natural part of a multi-sort
  2699. * chain. If false, the sorting order is set to ASCENDING for that
  2700. * cell's column. If that column was already the only sorted column in
  2701. * the Grid, the sort direction is flipped.
  2702. *
  2703. * @param cell
  2704. * a valid cell reference
  2705. * @param multisort
  2706. * whether the sort command should act as a multi-sort stack
  2707. * or not
  2708. */
  2709. public void sort(Column<?, ?> column, boolean multisort) {
  2710. if (!columns.contains(column)) {
  2711. throw new IllegalArgumentException(
  2712. "Given column is not a column in this grid. "
  2713. + column.toString());
  2714. }
  2715. if (!column.isSortable()) {
  2716. return;
  2717. }
  2718. final SortOrder so = getSortOrder(column);
  2719. if (multisort) {
  2720. // If the sort order exists, replace existing value with its
  2721. // opposite
  2722. if (so != null) {
  2723. final int idx = sortOrder.indexOf(so);
  2724. sortOrder.set(idx, so.getOpposite());
  2725. } else {
  2726. // If it doesn't, just add a new sort order to the end of
  2727. // the list
  2728. sortOrder.add(new SortOrder(column));
  2729. }
  2730. } else {
  2731. // Since we're doing single column sorting, first clear the
  2732. // list. Then, if the sort order existed, add its opposite,
  2733. // otherwise just add a new sort value
  2734. int items = sortOrder.size();
  2735. sortOrder.clear();
  2736. if (so != null && items == 1) {
  2737. sortOrder.add(so.getOpposite());
  2738. } else {
  2739. sortOrder.add(new SortOrder(column));
  2740. }
  2741. }
  2742. // sortOrder has been changed; tell the Grid to re-sort itself by
  2743. // user request.
  2744. Grid.this.sort(true);
  2745. }
  2746. /**
  2747. * Perform a sort after a delay.
  2748. *
  2749. * @param delay
  2750. * delay, in milliseconds
  2751. */
  2752. public void sortAfterDelay(int delay, boolean multisort) {
  2753. column = eventCell.getColumn();
  2754. scheduledMultisort = multisort;
  2755. timer.schedule(delay);
  2756. }
  2757. /**
  2758. * Check if a delayed sort command has been issued but not yet carried
  2759. * out.
  2760. *
  2761. * @return a boolean value
  2762. */
  2763. public boolean isDelayedSortScheduled() {
  2764. return timer.isRunning();
  2765. }
  2766. /**
  2767. * Cancel a scheduled sort.
  2768. */
  2769. public void cancelDelayedSort() {
  2770. timer.cancel();
  2771. }
  2772. }
  2773. /**
  2774. * @see Grid#autoColumnWidthsRecalculator
  2775. */
  2776. private class AutoColumnWidthsRecalculator {
  2777. private double lastCalculatedInnerWidth = -1;
  2778. private final ScheduledCommand calculateCommand = new ScheduledCommand() {
  2779. @Override
  2780. public void execute() {
  2781. if (!isScheduled) {
  2782. // something cancelled running this.
  2783. return;
  2784. }
  2785. if (header.markAsDirty || footer.markAsDirty) {
  2786. if (rescheduleCount < 10) {
  2787. /*
  2788. * Headers and footers are rendered as finally, this way
  2789. * we re-schedule this loop as finally, at the end of
  2790. * the queue, so that the headers have a chance to
  2791. * render themselves.
  2792. */
  2793. Scheduler.get().scheduleFinally(this);
  2794. rescheduleCount++;
  2795. } else {
  2796. /*
  2797. * We've tried too many times reschedule finally. Seems
  2798. * like something is being deferred. Let the queue
  2799. * execute and retry again.
  2800. */
  2801. rescheduleCount = 0;
  2802. Scheduler.get().scheduleDeferred(this);
  2803. }
  2804. } else if (currentDataAvailable.isEmpty()
  2805. && dataIsBeingFetched) {
  2806. // No data available yet but something is incoming soon
  2807. Scheduler.get().scheduleDeferred(this);
  2808. } else {
  2809. calculate();
  2810. }
  2811. }
  2812. };
  2813. private int rescheduleCount = 0;
  2814. private boolean isScheduled;
  2815. /**
  2816. * Calculates and applies column widths, taking into account fixed
  2817. * widths and column expand rules
  2818. *
  2819. * @param immediately
  2820. * <code>true</code> if the widths should be executed
  2821. * immediately (ignoring lazy loading completely), or
  2822. * <code>false</code> if the command should be run after a
  2823. * while (duplicate non-immediately invocations are ignored).
  2824. * @see Column#setWidth(double)
  2825. * @see Column#setExpandRatio(int)
  2826. * @see Column#setMinimumWidth(double)
  2827. * @see Column#setMaximumWidth(double)
  2828. */
  2829. public void schedule() {
  2830. if (!isScheduled && isAttached()) {
  2831. isScheduled = true;
  2832. Scheduler.get().scheduleFinally(calculateCommand);
  2833. }
  2834. }
  2835. private void calculate() {
  2836. isScheduled = false;
  2837. rescheduleCount = 0;
  2838. assert !(currentDataAvailable.isEmpty()
  2839. && dataIsBeingFetched) : "Trying to calculate column widths without data while data is still being fetched.";
  2840. if (columnsAreGuaranteedToBeWiderThanGrid()) {
  2841. applyColumnWidths();
  2842. } else {
  2843. applyColumnWidthsWithExpansion();
  2844. }
  2845. // Update latest width to prevent recalculate on height change.
  2846. lastCalculatedInnerWidth = escalator.getInnerWidth();
  2847. }
  2848. private boolean columnsAreGuaranteedToBeWiderThanGrid() {
  2849. double freeSpace = escalator.getInnerWidth();
  2850. for (Column<?, ?> column : getVisibleColumns()) {
  2851. if (column.getWidth() >= 0) {
  2852. freeSpace -= column.getWidth();
  2853. } else if (column.getMinimumWidth() >= 0) {
  2854. freeSpace -= column.getMinimumWidth();
  2855. }
  2856. }
  2857. return freeSpace < 0;
  2858. }
  2859. @SuppressWarnings("boxing")
  2860. private void applyColumnWidths() {
  2861. /* Step 1: Apply all column widths as they are. */
  2862. Map<Integer, Double> selfWidths = new LinkedHashMap<Integer, Double>();
  2863. List<Column<?, T>> columns = getVisibleColumns();
  2864. for (int index = 0; index < columns.size(); index++) {
  2865. selfWidths.put(index, columns.get(index).getWidth());
  2866. }
  2867. Grid.this.escalator.getColumnConfiguration()
  2868. .setColumnWidths(selfWidths);
  2869. /*
  2870. * Step 2: Make sure that each column ends up obeying their min/max
  2871. * width constraints if defined as autowidth. If constraints are
  2872. * violated, fix it.
  2873. */
  2874. Map<Integer, Double> constrainedWidths = new LinkedHashMap<Integer, Double>();
  2875. for (int index = 0; index < columns.size(); index++) {
  2876. Column<?, T> column = columns.get(index);
  2877. boolean hasAutoWidth = column.getWidth() < 0;
  2878. if (!hasAutoWidth) {
  2879. continue;
  2880. }
  2881. // TODO: bug: these don't honor the CSS max/min. :(
  2882. double actualWidth = column.getWidthActual();
  2883. if (actualWidth < getMinWidth(column)) {
  2884. constrainedWidths.put(index, column.getMinimumWidth());
  2885. } else if (actualWidth > getMaxWidth(column)) {
  2886. constrainedWidths.put(index, column.getMaximumWidth());
  2887. }
  2888. }
  2889. Grid.this.escalator.getColumnConfiguration()
  2890. .setColumnWidths(constrainedWidths);
  2891. }
  2892. private void applyColumnWidthsWithExpansion() {
  2893. boolean defaultExpandRatios = true;
  2894. int totalRatios = 0;
  2895. double reservedPixels = 0;
  2896. final Set<Column<?, T>> columnsToExpand = new HashSet<Column<?, T>>();
  2897. List<Column<?, T>> nonFixedColumns = new ArrayList<Column<?, T>>();
  2898. Map<Integer, Double> columnSizes = new HashMap<Integer, Double>();
  2899. final List<Column<?, T>> visibleColumns = getVisibleColumns();
  2900. /*
  2901. * Set all fixed widths and also calculate the size-to-fit widths
  2902. * for the autocalculated columns.
  2903. *
  2904. * This way we know with how many pixels we have left to expand the
  2905. * rest.
  2906. */
  2907. for (Column<?, T> column : visibleColumns) {
  2908. final double widthAsIs = column.getWidth();
  2909. final boolean isFixedWidth = widthAsIs >= 0;
  2910. // Check for max width just to be sure we don't break the limits
  2911. final double widthFixed = Math.max(
  2912. Math.min(getMaxWidth(column), widthAsIs),
  2913. column.getMinimumWidth());
  2914. defaultExpandRatios = defaultExpandRatios
  2915. && (column.getExpandRatio() == -1
  2916. || column == selectionColumn);
  2917. if (isFixedWidth) {
  2918. columnSizes.put(visibleColumns.indexOf(column), widthFixed);
  2919. reservedPixels += widthFixed;
  2920. } else {
  2921. nonFixedColumns.add(column);
  2922. columnSizes.put(visibleColumns.indexOf(column), -1.0d);
  2923. }
  2924. }
  2925. setColumnSizes(columnSizes);
  2926. for (Column<?, T> column : nonFixedColumns) {
  2927. final int expandRatio = (defaultExpandRatios ? 1
  2928. : column.getExpandRatio());
  2929. final double maxWidth = getMaxWidth(column);
  2930. final double newWidth = Math.min(maxWidth,
  2931. column.getWidthActual());
  2932. boolean shouldExpand = newWidth < maxWidth && expandRatio > 0
  2933. && column != selectionColumn;
  2934. if (shouldExpand) {
  2935. totalRatios += expandRatio;
  2936. columnsToExpand.add(column);
  2937. }
  2938. reservedPixels += newWidth;
  2939. columnSizes.put(visibleColumns.indexOf(column), newWidth);
  2940. }
  2941. /*
  2942. * Now that we know how many pixels we need at the very least, we
  2943. * can distribute the remaining pixels to all columns according to
  2944. * their expand ratios.
  2945. */
  2946. double pixelsToDistribute = escalator.getInnerWidth()
  2947. - reservedPixels;
  2948. if (pixelsToDistribute <= 0 || totalRatios <= 0) {
  2949. if (pixelsToDistribute <= 0) {
  2950. // Set column sizes for expanding columns
  2951. setColumnSizes(columnSizes);
  2952. }
  2953. return;
  2954. }
  2955. /*
  2956. * Check for columns that hit their max width. Adjust
  2957. * pixelsToDistribute and totalRatios accordingly. Recheck. Stop
  2958. * when no new columns hit their max width
  2959. */
  2960. boolean aColumnHasMaxedOut;
  2961. do {
  2962. aColumnHasMaxedOut = false;
  2963. final double widthPerRatio = pixelsToDistribute / totalRatios;
  2964. final Iterator<Column<?, T>> i = columnsToExpand.iterator();
  2965. while (i.hasNext()) {
  2966. final Column<?, T> column = i.next();
  2967. final int expandRatio = getExpandRatio(column,
  2968. defaultExpandRatios);
  2969. final int columnIndex = visibleColumns.indexOf(column);
  2970. final double autoWidth = columnSizes.get(columnIndex);
  2971. final double maxWidth = getMaxWidth(column);
  2972. double expandedWidth = autoWidth
  2973. + widthPerRatio * expandRatio;
  2974. if (maxWidth <= expandedWidth) {
  2975. i.remove();
  2976. totalRatios -= expandRatio;
  2977. aColumnHasMaxedOut = true;
  2978. pixelsToDistribute -= maxWidth - autoWidth;
  2979. columnSizes.put(columnIndex, maxWidth);
  2980. }
  2981. }
  2982. } while (aColumnHasMaxedOut);
  2983. if (totalRatios <= 0 && columnsToExpand.isEmpty()) {
  2984. setColumnSizes(columnSizes);
  2985. return;
  2986. }
  2987. assert pixelsToDistribute > 0 : "We've run out of pixels to distribute ("
  2988. + pixelsToDistribute + "px to " + totalRatios
  2989. + " ratios between " + columnsToExpand.size() + " columns)";
  2990. assert totalRatios > 0 && !columnsToExpand
  2991. .isEmpty() : "Bookkeeping out of sync. Ratios: "
  2992. + totalRatios + " Columns: "
  2993. + columnsToExpand.size();
  2994. /*
  2995. * If we still have anything left, distribute the remaining pixels
  2996. * to the remaining columns.
  2997. */
  2998. final double widthPerRatio;
  2999. int leftOver = 0;
  3000. if (BrowserInfo.get().isIE8() || BrowserInfo.get().isIE9()
  3001. || BrowserInfo.getBrowserString().contains("PhantomJS")) {
  3002. // These browsers report subpixels as integers. this usually
  3003. // results into issues..
  3004. widthPerRatio = (int) (pixelsToDistribute / totalRatios);
  3005. leftOver = (int) (pixelsToDistribute
  3006. - widthPerRatio * totalRatios);
  3007. } else {
  3008. widthPerRatio = pixelsToDistribute / totalRatios;
  3009. }
  3010. for (Column<?, T> column : columnsToExpand) {
  3011. final int expandRatio = getExpandRatio(column,
  3012. defaultExpandRatios);
  3013. final int columnIndex = visibleColumns.indexOf(column);
  3014. final double autoWidth = columnSizes.get(columnIndex);
  3015. double totalWidth = autoWidth + widthPerRatio * expandRatio;
  3016. if (leftOver > 0) {
  3017. totalWidth += 1;
  3018. leftOver--;
  3019. }
  3020. columnSizes.put(columnIndex, totalWidth);
  3021. totalRatios -= expandRatio;
  3022. }
  3023. assert totalRatios == 0 : "Bookkeeping error: there were still some ratios left undistributed: "
  3024. + totalRatios;
  3025. /*
  3026. * Check the guarantees for minimum width and scoot back the columns
  3027. * that don't care.
  3028. */
  3029. boolean minWidthsCausedReflows;
  3030. do {
  3031. minWidthsCausedReflows = false;
  3032. /*
  3033. * First, let's check which columns were too cramped, and expand
  3034. * them. Also keep track on how many pixels we grew - we need to
  3035. * remove those pixels from other columns
  3036. */
  3037. double pixelsToRemoveFromOtherColumns = 0;
  3038. for (Column<?, T> column : visibleColumns) {
  3039. /*
  3040. * We can't iterate over columnsToExpand, even though that
  3041. * would be convenient. This is because some column without
  3042. * an expand ratio might still have a min width - those
  3043. * wouldn't show up in that set.
  3044. */
  3045. double minWidth = getMinWidth(column);
  3046. final int columnIndex = visibleColumns.indexOf(column);
  3047. double currentWidth = columnSizes.get(columnIndex);
  3048. boolean hasAutoWidth = column.getWidth() < 0;
  3049. if (hasAutoWidth && currentWidth < minWidth) {
  3050. columnSizes.put(columnIndex, minWidth);
  3051. pixelsToRemoveFromOtherColumns += (minWidth
  3052. - currentWidth);
  3053. minWidthsCausedReflows = true;
  3054. /*
  3055. * Remove this column form the set if it exists. This
  3056. * way we make sure that it doesn't get shrunk in the
  3057. * next step.
  3058. */
  3059. columnsToExpand.remove(column);
  3060. }
  3061. }
  3062. /*
  3063. * Now we need to shrink the remaining columns according to
  3064. * their ratios. Recalculate the sum of remaining ratios.
  3065. */
  3066. totalRatios = 0;
  3067. for (Column<?, ?> column : columnsToExpand) {
  3068. totalRatios += getExpandRatio(column, defaultExpandRatios);
  3069. }
  3070. final double pixelsToRemovePerRatio = pixelsToRemoveFromOtherColumns
  3071. / totalRatios;
  3072. for (Column<?, T> column : columnsToExpand) {
  3073. final double pixelsToRemove = pixelsToRemovePerRatio
  3074. * getExpandRatio(column, defaultExpandRatios);
  3075. int colIndex = visibleColumns.indexOf(column);
  3076. columnSizes.put(colIndex,
  3077. columnSizes.get(colIndex) - pixelsToRemove);
  3078. }
  3079. } while (minWidthsCausedReflows);
  3080. // Finally set all the column sizes.
  3081. setColumnSizes(columnSizes);
  3082. }
  3083. private void setColumnSizes(Map<Integer, Double> columnSizes) {
  3084. // Set all widths at once
  3085. escalator.getColumnConfiguration().setColumnWidths(columnSizes);
  3086. }
  3087. private int getExpandRatio(Column<?, ?> column,
  3088. boolean defaultExpandRatios) {
  3089. int expandRatio = column.getExpandRatio();
  3090. if (expandRatio > 0) {
  3091. return expandRatio;
  3092. } else if (expandRatio < 0) {
  3093. assert defaultExpandRatios : "No columns should've expanded";
  3094. return 1;
  3095. } else {
  3096. assert false : "this method should've not been called at all if expandRatio is 0";
  3097. return 0;
  3098. }
  3099. }
  3100. /**
  3101. * Returns the maximum width of the column, or {@link Double#MAX_VALUE}
  3102. * if defined as negative.
  3103. */
  3104. private double getMaxWidth(Column<?, ?> column) {
  3105. double maxWidth = column.getMaximumWidth();
  3106. if (maxWidth >= 0) {
  3107. return maxWidth;
  3108. } else {
  3109. return Double.MAX_VALUE;
  3110. }
  3111. }
  3112. /**
  3113. * Returns the minimum width of the column, or {@link Double#MIN_VALUE}
  3114. * if defined as negative.
  3115. */
  3116. private double getMinWidth(Column<?, ?> column) {
  3117. double minWidth = column.getMinimumWidth();
  3118. if (minWidth >= 0) {
  3119. return minWidth;
  3120. } else {
  3121. return Double.MIN_VALUE;
  3122. }
  3123. }
  3124. /**
  3125. * Check whether the auto width calculation is currently scheduled.
  3126. *
  3127. * @return <code>true</code> if auto width calculation is currently
  3128. * scheduled
  3129. */
  3130. public boolean isScheduled() {
  3131. return isScheduled;
  3132. }
  3133. }
  3134. private class GridSpacerUpdater implements SpacerUpdater {
  3135. private static final String STRIPE_CLASSNAME = "stripe";
  3136. private final Map<Element, Widget> elementToWidgetMap = new HashMap<Element, Widget>();
  3137. @Override
  3138. public void init(Spacer spacer) {
  3139. initTheming(spacer);
  3140. int rowIndex = spacer.getRow();
  3141. Widget detailsWidget = null;
  3142. try {
  3143. detailsWidget = detailsGenerator.getDetails(rowIndex);
  3144. } catch (Throwable e) {
  3145. getLogger().log(Level.SEVERE,
  3146. "Exception while generating details for row "
  3147. + rowIndex,
  3148. e);
  3149. }
  3150. final double spacerHeight;
  3151. Element spacerElement = spacer.getElement();
  3152. if (detailsWidget == null) {
  3153. spacerElement.removeAllChildren();
  3154. spacerHeight = DETAILS_ROW_INITIAL_HEIGHT;
  3155. } else {
  3156. Element element = detailsWidget.getElement();
  3157. spacerElement.appendChild(element);
  3158. setParent(detailsWidget, Grid.this);
  3159. Widget previousWidget = elementToWidgetMap.put(element,
  3160. detailsWidget);
  3161. assert previousWidget == null : "Overwrote a pre-existing widget on row "
  3162. + rowIndex + " without proper removal first.";
  3163. /*
  3164. * Once we have the content properly inside the DOM, we should
  3165. * re-measure it to make sure that it's the correct height.
  3166. *
  3167. * This is rather tricky, since the row (tr) will get the
  3168. * height, but the spacer cell (td) has the borders, which
  3169. * should go on top of the previous row and next row.
  3170. */
  3171. double contentHeight;
  3172. if (detailsGenerator instanceof HeightAwareDetailsGenerator) {
  3173. HeightAwareDetailsGenerator sadg = (HeightAwareDetailsGenerator) detailsGenerator;
  3174. contentHeight = sadg.getDetailsHeight(rowIndex);
  3175. } else {
  3176. contentHeight = WidgetUtil
  3177. .getRequiredHeightBoundingClientRectDouble(element);
  3178. }
  3179. double borderTopAndBottomHeight = WidgetUtil
  3180. .getBorderTopAndBottomThickness(spacerElement);
  3181. double measuredHeight = contentHeight
  3182. + borderTopAndBottomHeight;
  3183. assert getElement().isOrHasChild(
  3184. spacerElement) : "The spacer element wasn't in the DOM during measurement, but was assumed to be.";
  3185. spacerHeight = measuredHeight;
  3186. }
  3187. escalator.getBody().setSpacer(rowIndex, spacerHeight);
  3188. if (getHeightMode() == HeightMode.UNDEFINED) {
  3189. setHeightByRows(getEscalator().getBody().getRowCount());
  3190. }
  3191. }
  3192. @Override
  3193. public void destroy(Spacer spacer) {
  3194. Element spacerElement = spacer.getElement();
  3195. assert getElement().isOrHasChild(spacerElement) : "Trying "
  3196. + "to destroy a spacer that is not connected to this "
  3197. + "Grid's DOM. (row: " + spacer.getRow() + ", element: "
  3198. + spacerElement + ")";
  3199. Widget detailsWidget = elementToWidgetMap
  3200. .remove(spacerElement.getFirstChildElement());
  3201. if (detailsWidget != null) {
  3202. /*
  3203. * The widget may be null here if the previous generator
  3204. * returned a null widget.
  3205. */
  3206. assert spacerElement.getFirstChild() != null : "The "
  3207. + "details row to destroy did not contain a widget - "
  3208. + "probably removed by something else without "
  3209. + "permission? (row: " + spacer.getRow() + ", element: "
  3210. + spacerElement + ")";
  3211. setParent(detailsWidget, null);
  3212. spacerElement.removeAllChildren();
  3213. if (getHeightMode() == HeightMode.UNDEFINED) {
  3214. // update spacer height
  3215. escalator.getBody().setSpacer(spacer.getRow(), 0);
  3216. setHeightByRows(getEscalator().getBody().getRowCount());
  3217. }
  3218. }
  3219. }
  3220. private void initTheming(Spacer spacer) {
  3221. Element spacerRoot = spacer.getElement();
  3222. if (spacer.getRow() % 2 == 1) {
  3223. spacerRoot.getParentElement().addClassName(STRIPE_CLASSNAME);
  3224. } else {
  3225. spacerRoot.getParentElement().removeClassName(STRIPE_CLASSNAME);
  3226. }
  3227. }
  3228. }
  3229. /**
  3230. * Sidebar displaying toggles for hidable columns and custom widgets
  3231. * provided by the application.
  3232. * <p>
  3233. * The button for opening the sidebar is automatically visible inside the
  3234. * grid, if it contains any column hiding options or custom widgets. The
  3235. * column hiding toggles and custom widgets become visible once the sidebar
  3236. * has been opened.
  3237. *
  3238. * @since 7.5.0
  3239. */
  3240. private static class Sidebar extends Composite implements HasEnabled {
  3241. private final ClickHandler openCloseButtonHandler = new ClickHandler() {
  3242. @Override
  3243. public void onClick(ClickEvent event) {
  3244. if (!isOpen()) {
  3245. open();
  3246. } else {
  3247. close();
  3248. }
  3249. }
  3250. };
  3251. private final FlowPanel rootContainer;
  3252. private final FlowPanel content;
  3253. private final MenuBar menuBar;
  3254. private final Button openCloseButton;
  3255. private final Grid<?> grid;
  3256. private Overlay overlay;
  3257. private Sidebar(Grid<?> grid) {
  3258. this.grid = grid;
  3259. rootContainer = new FlowPanel();
  3260. initWidget(rootContainer);
  3261. openCloseButton = new Button();
  3262. openCloseButton.addClickHandler(openCloseButtonHandler);
  3263. rootContainer.add(openCloseButton);
  3264. content = new FlowPanel() {
  3265. @Override
  3266. public boolean remove(Widget w) {
  3267. // Check here to catch child.removeFromParent() calls
  3268. boolean removed = super.remove(w);
  3269. if (removed) {
  3270. updateVisibility();
  3271. }
  3272. return removed;
  3273. }
  3274. };
  3275. createOverlay();
  3276. menuBar = new MenuBar(true) {
  3277. @Override
  3278. public MenuItem insertItem(MenuItem item, int beforeIndex)
  3279. throws IndexOutOfBoundsException {
  3280. if (getParent() == null) {
  3281. content.insert(this, 0);
  3282. updateVisibility();
  3283. }
  3284. return super.insertItem(item, beforeIndex);
  3285. }
  3286. @Override
  3287. public void removeItem(MenuItem item) {
  3288. super.removeItem(item);
  3289. if (getItems().isEmpty()) {
  3290. menuBar.removeFromParent();
  3291. }
  3292. }
  3293. @Override
  3294. public void onBrowserEvent(Event event) {
  3295. // selecting a item with enter will lose the focus and
  3296. // selected item, which means that further keyboard
  3297. // selection won't work unless we do this:
  3298. if (event.getTypeInt() == Event.ONKEYDOWN
  3299. && event.getKeyCode() == KeyCodes.KEY_ENTER) {
  3300. final MenuItem item = getSelectedItem();
  3301. super.onBrowserEvent(event);
  3302. Scheduler.get()
  3303. .scheduleDeferred(new ScheduledCommand() {
  3304. @Override
  3305. public void execute() {
  3306. selectItem(item);
  3307. focus();
  3308. }
  3309. });
  3310. } else {
  3311. super.onBrowserEvent(event);
  3312. }
  3313. }
  3314. };
  3315. KeyDownHandler keyDownHandler = new KeyDownHandler() {
  3316. @Override
  3317. public void onKeyDown(KeyDownEvent event) {
  3318. if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
  3319. close();
  3320. }
  3321. }
  3322. };
  3323. openCloseButton.addDomHandler(keyDownHandler,
  3324. KeyDownEvent.getType());
  3325. menuBar.addDomHandler(keyDownHandler, KeyDownEvent.getType());
  3326. }
  3327. /**
  3328. * Creates and initializes the overlay.
  3329. */
  3330. private void createOverlay() {
  3331. overlay = GWT.create(Overlay.class);
  3332. overlay.setOwner(grid);
  3333. overlay.setAutoHideEnabled(true);
  3334. overlay.addStyleDependentName("popup");
  3335. overlay.add(content);
  3336. overlay.addAutoHidePartner(rootContainer.getElement());
  3337. overlay.addCloseHandler(new CloseHandler<PopupPanel>() {
  3338. @Override
  3339. public void onClose(CloseEvent<PopupPanel> event) {
  3340. removeStyleName("open");
  3341. addStyleName("closed");
  3342. }
  3343. });
  3344. overlay.setFitInWindow(true);
  3345. }
  3346. /**
  3347. * Opens the sidebar if not yet opened. Opening the sidebar has no
  3348. * effect if it is empty.
  3349. */
  3350. public void open() {
  3351. if (!isOpen() && isInDOM()) {
  3352. addStyleName("open");
  3353. removeStyleName("closed");
  3354. overlay.showRelativeTo(rootContainer);
  3355. }
  3356. }
  3357. /**
  3358. * Closes the sidebar if not yet closed.
  3359. */
  3360. public void close() {
  3361. overlay.hide();
  3362. }
  3363. /**
  3364. * Returns whether the sidebar is open or not.
  3365. *
  3366. * @return <code>true</code> if open, <code>false</code> if not
  3367. */
  3368. public boolean isOpen() {
  3369. return overlay != null && overlay.isShowing();
  3370. }
  3371. @Override
  3372. public void setStylePrimaryName(String styleName) {
  3373. super.setStylePrimaryName(styleName);
  3374. overlay.setStylePrimaryName(styleName);
  3375. content.setStylePrimaryName(styleName + "-content");
  3376. openCloseButton.setStylePrimaryName(styleName + "-button");
  3377. if (isOpen()) {
  3378. addStyleName("open");
  3379. removeStyleName("closed");
  3380. } else {
  3381. removeStyleName("open");
  3382. addStyleName("closed");
  3383. }
  3384. }
  3385. @Override
  3386. public void addStyleName(String style) {
  3387. super.addStyleName(style);
  3388. overlay.addStyleName(style);
  3389. }
  3390. @Override
  3391. public void removeStyleName(String style) {
  3392. super.removeStyleName(style);
  3393. overlay.removeStyleName(style);
  3394. }
  3395. private void setHeightToHeaderCellHeight() {
  3396. RowContainer header = grid.escalator.getHeader();
  3397. if (header.getRowCount() == 0
  3398. || !header.getRowElement(0).hasChildNodes()) {
  3399. getLogger().info(
  3400. "No header cell available when calculating sidebar button height");
  3401. openCloseButton.setHeight(header.getDefaultRowHeight() + "px");
  3402. return;
  3403. }
  3404. Element firstHeaderCell = header.getRowElement(0)
  3405. .getFirstChildElement();
  3406. double height = WidgetUtil
  3407. .getRequiredHeightBoundingClientRectDouble(firstHeaderCell)
  3408. - (WidgetUtil.measureVerticalBorder(getElement()) / 2);
  3409. openCloseButton.setHeight(height + "px");
  3410. }
  3411. private void updateVisibility() {
  3412. final boolean hasWidgets = content.getWidgetCount() > 0;
  3413. final boolean isVisible = isInDOM();
  3414. if (isVisible && !hasWidgets) {
  3415. Grid.setParent(this, null);
  3416. getElement().removeFromParent();
  3417. } else if (!isVisible && hasWidgets) {
  3418. close();
  3419. grid.getElement().appendChild(getElement());
  3420. Grid.setParent(this, grid);
  3421. // border calculation won't work until attached
  3422. setHeightToHeaderCellHeight();
  3423. }
  3424. }
  3425. private boolean isInDOM() {
  3426. return getParent() != null;
  3427. }
  3428. @Override
  3429. protected void onAttach() {
  3430. super.onAttach();
  3431. // make sure the button will get correct height if the button should
  3432. // be visible when the grid is rendered the first time.
  3433. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  3434. @Override
  3435. public void execute() {
  3436. setHeightToHeaderCellHeight();
  3437. }
  3438. });
  3439. }
  3440. @Override
  3441. public boolean isEnabled() {
  3442. return openCloseButton.isEnabled();
  3443. }
  3444. @Override
  3445. public void setEnabled(boolean enabled) {
  3446. if (!enabled && isOpen()) {
  3447. close();
  3448. }
  3449. openCloseButton.setEnabled(enabled);
  3450. }
  3451. }
  3452. /**
  3453. * UI and functionality related to hiding columns with toggles in the
  3454. * sidebar.
  3455. */
  3456. private final class ColumnHider {
  3457. /** Map from columns to their hiding toggles, component might change */
  3458. private HashMap<Column<?, T>, MenuItem> columnToHidingToggleMap = new HashMap<Grid.Column<?, T>, MenuItem>();
  3459. /**
  3460. * When column is being hidden with a toggle, do not refresh toggles for
  3461. * no reason. Also helps for keeping the keyboard navigation working.
  3462. */
  3463. private boolean hidingColumn;
  3464. private void updateColumnHidable(final Column<?, T> column) {
  3465. if (column.isHidable()) {
  3466. MenuItem toggle = columnToHidingToggleMap.get(column);
  3467. if (toggle == null) {
  3468. toggle = createToggle(column);
  3469. }
  3470. toggle.setStyleName("hidden", column.isHidden());
  3471. } else if (columnToHidingToggleMap.containsKey(column)) {
  3472. sidebar.menuBar
  3473. .removeItem((columnToHidingToggleMap.remove(column)));
  3474. }
  3475. updateTogglesOrder();
  3476. }
  3477. private MenuItem createToggle(final Column<?, T> column) {
  3478. MenuItem toggle = new MenuItem(createHTML(column), true,
  3479. new ScheduledCommand() {
  3480. @Override
  3481. public void execute() {
  3482. hidingColumn = true;
  3483. column.setHidden(!column.isHidden(), true);
  3484. hidingColumn = false;
  3485. }
  3486. });
  3487. toggle.addStyleName("column-hiding-toggle");
  3488. columnToHidingToggleMap.put(column, toggle);
  3489. return toggle;
  3490. }
  3491. private String createHTML(Column<?, T> column) {
  3492. final StringBuffer buf = new StringBuffer();
  3493. buf.append("<span class=\"");
  3494. if (column.isHidden()) {
  3495. buf.append("v-off");
  3496. } else {
  3497. buf.append("v-on");
  3498. }
  3499. buf.append("\"><div>");
  3500. String caption = column.getHidingToggleCaption();
  3501. if (caption == null) {
  3502. caption = column.headerCaption;
  3503. }
  3504. buf.append(caption);
  3505. buf.append("</div></span>");
  3506. return buf.toString();
  3507. }
  3508. private void updateTogglesOrder() {
  3509. if (!hidingColumn) {
  3510. int lastIndex = 0;
  3511. for (Column<?, T> column : getColumns()) {
  3512. if (column.isHidable()) {
  3513. final MenuItem menuItem = columnToHidingToggleMap
  3514. .get(column);
  3515. sidebar.menuBar.removeItem(menuItem);
  3516. sidebar.menuBar.insertItem(menuItem, lastIndex++);
  3517. }
  3518. }
  3519. }
  3520. }
  3521. private void updateHidingToggle(Column<?, T> column) {
  3522. if (column.isHidable()) {
  3523. MenuItem toggle = columnToHidingToggleMap.get(column);
  3524. toggle.setHTML(createHTML(column));
  3525. toggle.setStyleName("hidden", column.isHidden());
  3526. } // else we can just ignore
  3527. }
  3528. private void removeColumnHidingToggle(Column<?, T> column) {
  3529. sidebar.menuBar.removeItem(columnToHidingToggleMap.get(column));
  3530. }
  3531. }
  3532. /**
  3533. * Escalator used internally by grid to render the rows
  3534. */
  3535. private Escalator escalator = GWT.create(Escalator.class);
  3536. private final Header header = GWT.create(Header.class);
  3537. private final Footer footer = GWT.create(Footer.class);
  3538. private final Sidebar sidebar = new Sidebar(this);
  3539. /**
  3540. * List of columns in the grid. Order defines the visible order.
  3541. */
  3542. private List<Column<?, T>> columns = new ArrayList<Column<?, T>>();
  3543. /**
  3544. * The datasource currently in use. <em>Note:</em> it is <code>null</code>
  3545. * on initialization, but not after that.
  3546. */
  3547. private DataSource<T> dataSource;
  3548. /**
  3549. * Currently available row range in DataSource.
  3550. */
  3551. private Range currentDataAvailable = Range.withLength(0, 0);
  3552. /**
  3553. * The number of frozen columns, 0 freezes the selection column if
  3554. * displayed, -1 also prevents selection col from freezing.
  3555. */
  3556. private int frozenColumnCount = 0;
  3557. /**
  3558. * Current sort order. The (private) sort() method reads this list to
  3559. * determine the order in which to present rows.
  3560. */
  3561. private List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  3562. private Renderer<Boolean> selectColumnRenderer = null;
  3563. private SelectionColumn selectionColumn;
  3564. private String rowStripeStyleName;
  3565. private String rowHasDataStyleName;
  3566. private String rowSelectedStyleName;
  3567. private String cellFocusStyleName;
  3568. private String rowFocusStyleName;
  3569. /**
  3570. * Current selection model.
  3571. */
  3572. private SelectionModel<T> selectionModel;
  3573. protected final CellFocusHandler cellFocusHandler;
  3574. private final UserSorter sorter = new UserSorter();
  3575. private final Editor<T> editor = GWT.create(Editor.class);
  3576. private boolean dataIsBeingFetched = false;
  3577. /**
  3578. * The cell a click event originated from
  3579. * <p>
  3580. * This is a workaround to make Chrome work like Firefox. In Chrome,
  3581. * normally if you start a drag on one cell and release on:
  3582. * <ul>
  3583. * <li>that same cell, the click event is that <code>&lt;td></code>.
  3584. * <li>a cell on that same row, the click event is the parent
  3585. * <code>&lt;tr></code>.
  3586. * <li>a cell on another row, the click event is the table section ancestor
  3587. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  3588. * </ul>
  3589. *
  3590. * @see #onBrowserEvent(Event)
  3591. */
  3592. private Cell cellOnPrevMouseDown;
  3593. /**
  3594. * A scheduled command to re-evaluate the widths of <em>all columns</em>
  3595. * that have calculated widths. Most probably called because
  3596. * minwidth/maxwidth/expandratio has changed.
  3597. */
  3598. private final AutoColumnWidthsRecalculator autoColumnWidthsRecalculator = new AutoColumnWidthsRecalculator();
  3599. private boolean enabled = true;
  3600. private DetailsGenerator detailsGenerator = DetailsGenerator.NULL;
  3601. private GridSpacerUpdater gridSpacerUpdater = new GridSpacerUpdater();
  3602. /** A set keeping track of the indices of all currently open details */
  3603. private Set<Integer> visibleDetails = new HashSet<Integer>();
  3604. private boolean columnReorderingAllowed;
  3605. private ColumnHider columnHider = new ColumnHider();
  3606. private DragAndDropHandler dndHandler = new DragAndDropHandler();
  3607. private AutoScroller autoScroller = new AutoScroller(this);
  3608. private DragAndDropHandler.DragAndDropCallback headerCellDndCallback = new DragAndDropCallback() {
  3609. private final AutoScrollerCallback autoScrollerCallback = new AutoScrollerCallback() {
  3610. @Override
  3611. public void onAutoScroll(int scrollDiff) {
  3612. autoScrollX = scrollDiff;
  3613. onDragUpdate(null);
  3614. }
  3615. @Override
  3616. public void onAutoScrollReachedMin() {
  3617. // make sure the drop marker is visible on the left
  3618. autoScrollX = 0;
  3619. updateDragDropMarker(clientX);
  3620. }
  3621. @Override
  3622. public void onAutoScrollReachedMax() {
  3623. // make sure the drop marker is visible on the right
  3624. autoScrollX = 0;
  3625. updateDragDropMarker(clientX);
  3626. }
  3627. };
  3628. /**
  3629. * Elements for displaying the dragged column(s) and drop marker
  3630. * properly
  3631. */
  3632. private Element table;
  3633. private Element tableHeader;
  3634. /** Marks the column drop location */
  3635. private Element dropMarker;
  3636. /** A copy of the dragged column(s), moves with cursor. */
  3637. private Element dragElement;
  3638. /** Tracks index of the column whose left side the drop would occur */
  3639. private int latestColumnDropIndex;
  3640. /**
  3641. * Map of possible drop positions for the column and the corresponding
  3642. * column index.
  3643. */
  3644. private final TreeMap<Double, Integer> possibleDropPositions = new TreeMap<Double, Integer>();
  3645. /**
  3646. * Makes sure that drag cancel doesn't cause anything unwanted like sort
  3647. */
  3648. private HandlerRegistration columnSortPreventRegistration;
  3649. private int clientX;
  3650. /** How much the grid is being auto scrolled while dragging. */
  3651. private int autoScrollX;
  3652. /** Captures the value of the focused column before reordering */
  3653. private int focusedColumnIndex;
  3654. /** Offset caused by the drag and drop marker width */
  3655. private double dropMarkerWidthOffset;
  3656. private void initHeaderDragElementDOM() {
  3657. if (table == null) {
  3658. tableHeader = DOM.createTHead();
  3659. dropMarker = DOM.createDiv();
  3660. tableHeader.appendChild(dropMarker);
  3661. table = DOM.createTable();
  3662. table.appendChild(tableHeader);
  3663. table.setClassName("header-drag-table");
  3664. }
  3665. // update the style names on each run in case primary name has been
  3666. // modified
  3667. tableHeader.setClassName(
  3668. escalator.getHeader().getElement().getClassName());
  3669. dropMarker.setClassName(getStylePrimaryName() + "-drop-marker");
  3670. int topOffset = 0;
  3671. for (int i = 0; i < eventCell.getRowIndex(); i++) {
  3672. topOffset += escalator.getHeader().getRowElement(i)
  3673. .getFirstChildElement().getOffsetHeight();
  3674. }
  3675. tableHeader.getStyle().setTop(topOffset, Unit.PX);
  3676. getElement().appendChild(table);
  3677. dropMarkerWidthOffset = WidgetUtil
  3678. .getRequiredWidthBoundingClientRectDouble(dropMarker) / 2;
  3679. }
  3680. @Override
  3681. public void onDragUpdate(Event e) {
  3682. if (e != null) {
  3683. clientX = WidgetUtil.getTouchOrMouseClientX(e);
  3684. autoScrollX = 0;
  3685. }
  3686. resolveDragElementHorizontalPosition(clientX);
  3687. updateDragDropMarker(clientX);
  3688. }
  3689. private void updateDragDropMarker(final int clientX) {
  3690. final double scrollLeft = getScrollLeft();
  3691. final double cursorXCoordinate = clientX
  3692. - escalator.getHeader().getElement().getAbsoluteLeft();
  3693. final Entry<Double, Integer> cellEdgeOnRight = possibleDropPositions
  3694. .ceilingEntry(cursorXCoordinate);
  3695. final Entry<Double, Integer> cellEdgeOnLeft = possibleDropPositions
  3696. .floorEntry(cursorXCoordinate);
  3697. final double diffToRightEdge = cellEdgeOnRight == null
  3698. ? Double.MAX_VALUE
  3699. : cellEdgeOnRight.getKey() - cursorXCoordinate;
  3700. final double diffToLeftEdge = cellEdgeOnLeft == null
  3701. ? Double.MAX_VALUE
  3702. : cursorXCoordinate - cellEdgeOnLeft.getKey();
  3703. double dropMarkerLeft = 0 - scrollLeft;
  3704. if (diffToRightEdge > diffToLeftEdge) {
  3705. latestColumnDropIndex = cellEdgeOnLeft.getValue();
  3706. dropMarkerLeft += cellEdgeOnLeft.getKey();
  3707. } else {
  3708. latestColumnDropIndex = cellEdgeOnRight.getValue();
  3709. dropMarkerLeft += cellEdgeOnRight.getKey();
  3710. }
  3711. dropMarkerLeft += autoScrollX;
  3712. final double frozenColumnsWidth = autoScroller
  3713. .getFrozenColumnsWidth();
  3714. final double rightBoundaryForDrag = getSidebarBoundaryComparedTo(
  3715. dropMarkerLeft);
  3716. final int visibleColumns = getVisibleColumns().size();
  3717. // First check if the drop marker should move left because of the
  3718. // sidebar opening button. this only the case if the grid is
  3719. // scrolled to the right
  3720. if (latestColumnDropIndex == visibleColumns
  3721. && rightBoundaryForDrag < dropMarkerLeft
  3722. && dropMarkerLeft <= escalator.getInnerWidth()) {
  3723. dropMarkerLeft = rightBoundaryForDrag - dropMarkerWidthOffset;
  3724. }
  3725. // Check if the drop marker shouldn't be shown at all
  3726. else if (dropMarkerLeft < frozenColumnsWidth
  3727. || dropMarkerLeft > Math.min(rightBoundaryForDrag,
  3728. escalator.getInnerWidth())
  3729. || dropMarkerLeft < 0) {
  3730. dropMarkerLeft = -10000000;
  3731. }
  3732. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  3733. }
  3734. private void resolveDragElementHorizontalPosition(final int clientX) {
  3735. double left = clientX - table.getAbsoluteLeft();
  3736. // Do not show the drag element beyond a spanned header cell
  3737. // limitation
  3738. final Double leftBound = possibleDropPositions.firstKey();
  3739. final Double rightBound = possibleDropPositions.lastKey();
  3740. final double scrollLeft = getScrollLeft();
  3741. if (left + scrollLeft < leftBound) {
  3742. left = leftBound - scrollLeft + autoScrollX;
  3743. } else if (left + scrollLeft > rightBound) {
  3744. left = rightBound - scrollLeft + autoScrollX;
  3745. }
  3746. // Do not show the drag element beyond the grid
  3747. final double sidebarBoundary = getSidebarBoundaryComparedTo(left);
  3748. final double gridBoundary = escalator.getInnerWidth();
  3749. final double rightBoundary = Math.min(sidebarBoundary,
  3750. gridBoundary);
  3751. // Do not show on left of the frozen columns (even if scrolled)
  3752. final int frozenColumnsWidth = (int) autoScroller
  3753. .getFrozenColumnsWidth();
  3754. left = Math.max(frozenColumnsWidth, Math.min(left, rightBoundary));
  3755. left -= dragElement.getClientWidth() / 2;
  3756. dragElement.getStyle().setLeft(left, Unit.PX);
  3757. }
  3758. private boolean isSidebarOnDraggedRow() {
  3759. return eventCell.getRowIndex() == 0 && sidebar.isInDOM()
  3760. && !sidebar.isOpen();
  3761. }
  3762. /**
  3763. * Returns the sidebar left coordinate, in relation to the grid. Or
  3764. * Double.MAX_VALUE if it doesn't cause a boundary.
  3765. */
  3766. private double getSidebarBoundaryComparedTo(double left) {
  3767. if (isSidebarOnDraggedRow()) {
  3768. double absoluteLeft = left + getElement().getAbsoluteLeft();
  3769. double sidebarLeft = sidebar.getElement().getAbsoluteLeft();
  3770. double diff = absoluteLeft - sidebarLeft;
  3771. if (diff > 0) {
  3772. return left - diff;
  3773. }
  3774. }
  3775. return Double.MAX_VALUE;
  3776. }
  3777. @Override
  3778. public boolean onDragStart(Event e) {
  3779. calculatePossibleDropPositions();
  3780. if (possibleDropPositions.isEmpty()) {
  3781. return false;
  3782. }
  3783. initHeaderDragElementDOM();
  3784. // needs to clone focus and sorting indicators too (UX)
  3785. dragElement = DOM.clone(eventCell.getElement(), true);
  3786. dragElement.getStyle().clearWidth();
  3787. dropMarker.getStyle().setProperty("height",
  3788. dragElement.getStyle().getHeight());
  3789. tableHeader.appendChild(dragElement);
  3790. // mark the column being dragged for styling
  3791. eventCell.getElement().addClassName("dragged");
  3792. // mark the floating cell, for styling & testing
  3793. dragElement.addClassName("dragged-column-header");
  3794. // start the auto scroll handler
  3795. autoScroller.setScrollArea(60);
  3796. autoScroller.start(e, ScrollAxis.HORIZONTAL, autoScrollerCallback);
  3797. return true;
  3798. }
  3799. @Override
  3800. public void onDragEnd() {
  3801. table.removeFromParent();
  3802. dragElement.removeFromParent();
  3803. eventCell.getElement().removeClassName("dragged");
  3804. }
  3805. @Override
  3806. public void onDrop() {
  3807. final int draggedColumnIndex = eventCell.getColumnIndex();
  3808. final int colspan = header.getRow(eventCell.getRowIndex())
  3809. .getCell(eventCell.getColumn()).getColspan();
  3810. if (latestColumnDropIndex != draggedColumnIndex
  3811. && latestColumnDropIndex != (draggedColumnIndex
  3812. + colspan)) {
  3813. List<Column<?, T>> columns = getColumns();
  3814. List<Column<?, T>> reordered = new ArrayList<Column<?, T>>();
  3815. if (draggedColumnIndex < latestColumnDropIndex) {
  3816. reordered.addAll(columns.subList(0, draggedColumnIndex));
  3817. reordered.addAll(
  3818. columns.subList(draggedColumnIndex + colspan,
  3819. latestColumnDropIndex));
  3820. reordered.addAll(columns.subList(draggedColumnIndex,
  3821. draggedColumnIndex + colspan));
  3822. reordered.addAll(columns.subList(latestColumnDropIndex,
  3823. columns.size()));
  3824. } else {
  3825. reordered.addAll(columns.subList(0, latestColumnDropIndex));
  3826. reordered.addAll(columns.subList(draggedColumnIndex,
  3827. draggedColumnIndex + colspan));
  3828. reordered.addAll(columns.subList(latestColumnDropIndex,
  3829. draggedColumnIndex));
  3830. reordered.addAll(columns.subList(
  3831. draggedColumnIndex + colspan, columns.size()));
  3832. }
  3833. reordered.remove(selectionColumn); // since setColumnOrder will
  3834. // add it anyway!
  3835. // capture focused cell column before reorder
  3836. Cell focusedCell = cellFocusHandler.getFocusedCell();
  3837. if (focusedCell != null) {
  3838. // take hidden columns into account
  3839. focusedColumnIndex = getColumns()
  3840. .indexOf(getVisibleColumn(focusedCell.getColumn()));
  3841. }
  3842. Column<?, T>[] array = reordered
  3843. .toArray(new Column[reordered.size()]);
  3844. setColumnOrder(array);
  3845. transferCellFocusOnDrop();
  3846. } // else no reordering
  3847. }
  3848. private void transferCellFocusOnDrop() {
  3849. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  3850. if (focusedCell != null) {
  3851. final int focusedColumnIndexDOM = focusedCell.getColumn();
  3852. final int focusedRowIndex = focusedCell.getRow();
  3853. final int draggedColumnIndex = eventCell.getColumnIndex();
  3854. // transfer focus if it was effected by the new column order
  3855. final RowContainer rowContainer = escalator
  3856. .findRowContainer(focusedCell.getElement());
  3857. if (focusedColumnIndex == draggedColumnIndex) {
  3858. // move with the dragged column
  3859. int adjustedDropIndex = latestColumnDropIndex > draggedColumnIndex
  3860. ? latestColumnDropIndex - 1 : latestColumnDropIndex;
  3861. // remove hidden columns from indexing
  3862. adjustedDropIndex = getVisibleColumns()
  3863. .indexOf(getColumn(adjustedDropIndex));
  3864. cellFocusHandler.setCellFocus(focusedRowIndex,
  3865. adjustedDropIndex, rowContainer);
  3866. } else if (latestColumnDropIndex <= focusedColumnIndex
  3867. && draggedColumnIndex > focusedColumnIndex) {
  3868. cellFocusHandler.setCellFocus(focusedRowIndex,
  3869. focusedColumnIndexDOM + 1, rowContainer);
  3870. } else if (latestColumnDropIndex > focusedColumnIndex
  3871. && draggedColumnIndex < focusedColumnIndex) {
  3872. cellFocusHandler.setCellFocus(focusedRowIndex,
  3873. focusedColumnIndexDOM - 1, rowContainer);
  3874. }
  3875. }
  3876. }
  3877. @Override
  3878. public void onDragCancel() {
  3879. // cancel next click so that we may prevent column sorting if
  3880. // mouse was released on top of the dragged cell
  3881. if (columnSortPreventRegistration == null) {
  3882. columnSortPreventRegistration = Event
  3883. .addNativePreviewHandler(new NativePreviewHandler() {
  3884. @Override
  3885. public void onPreviewNativeEvent(
  3886. NativePreviewEvent event) {
  3887. if (event.getTypeInt() == Event.ONCLICK) {
  3888. event.cancel();
  3889. event.getNativeEvent().preventDefault();
  3890. columnSortPreventRegistration
  3891. .removeHandler();
  3892. columnSortPreventRegistration = null;
  3893. }
  3894. }
  3895. });
  3896. }
  3897. autoScroller.stop();
  3898. }
  3899. /**
  3900. * Returns the amount of frozen columns. The selection column is always
  3901. * considered frozen, since it can't be moved.
  3902. */
  3903. private int getSelectionAndFrozenColumnCount() {
  3904. // no matter if selection column is frozen or not, it is considered
  3905. // frozen for column dnd reorder
  3906. if (getSelectionModel().getSelectionColumnRenderer() != null) {
  3907. return Math.max(0, getFrozenColumnCount()) + 1;
  3908. } else {
  3909. return Math.max(0, getFrozenColumnCount());
  3910. }
  3911. }
  3912. @SuppressWarnings("boxing")
  3913. private void calculatePossibleDropPositions() {
  3914. possibleDropPositions.clear();
  3915. final int draggedColumnIndex = eventCell.getColumnIndex();
  3916. final StaticRow<?> draggedCellRow = header
  3917. .getRow(eventCell.getRowIndex());
  3918. final int draggedColumnRightIndex = draggedColumnIndex
  3919. + draggedCellRow.getCell(eventCell.getColumn())
  3920. .getColspan();
  3921. final int frozenColumns = getSelectionAndFrozenColumnCount();
  3922. final Range draggedCellRange = Range.between(draggedColumnIndex,
  3923. draggedColumnRightIndex);
  3924. /*
  3925. * If the dragged cell intersects with a spanned cell in any other
  3926. * header or footer row, then the drag is limited inside that
  3927. * spanned cell. The same rules apply: the cell can't be dropped
  3928. * inside another spanned cell. The left and right bounds keep track
  3929. * of the edges of the most limiting spanned cell.
  3930. */
  3931. int leftBound = -1;
  3932. int rightBound = getColumnCount() + 1;
  3933. final HashSet<Integer> unavailableColumnDropIndices = new HashSet<Integer>();
  3934. final List<StaticRow<?>> rows = new ArrayList<StaticRow<?>>();
  3935. rows.addAll(header.getRows());
  3936. rows.addAll(footer.getRows());
  3937. for (StaticRow<?> row : rows) {
  3938. if (!row.hasSpannedCells()) {
  3939. continue;
  3940. }
  3941. final boolean isDraggedCellRow = row.equals(draggedCellRow);
  3942. for (int cellColumnIndex = frozenColumns; cellColumnIndex < getColumnCount(); cellColumnIndex++) {
  3943. StaticCell cell = row.getCell(getColumn(cellColumnIndex));
  3944. int colspan = cell.getColspan();
  3945. if (colspan <= 1) {
  3946. continue;
  3947. }
  3948. final int cellColumnRightIndex = cellColumnIndex + colspan;
  3949. final Range cellRange = Range.between(cellColumnIndex,
  3950. cellColumnRightIndex);
  3951. final boolean intersects = draggedCellRange
  3952. .intersects(cellRange);
  3953. if (intersects && !isDraggedCellRow) {
  3954. // if the currently iterated cell is inside or same as
  3955. // the dragged cell, then it doesn't restrict the drag
  3956. if (cellRange.isSubsetOf(draggedCellRange)) {
  3957. cellColumnIndex = cellColumnRightIndex - 1;
  3958. continue;
  3959. }
  3960. /*
  3961. * if the dragged cell is a spanned cell and it crosses
  3962. * with the currently iterated cell without sharing
  3963. * either start or end then not possible to drag the
  3964. * cell.
  3965. */
  3966. if (!draggedCellRange.isSubsetOf(cellRange)) {
  3967. return;
  3968. }
  3969. // the spanned cell overlaps the dragged cell (but is
  3970. // not the dragged cell)
  3971. if (cellColumnIndex <= draggedColumnIndex
  3972. && cellColumnIndex > leftBound) {
  3973. leftBound = cellColumnIndex;
  3974. }
  3975. if (cellColumnRightIndex < rightBound) {
  3976. rightBound = cellColumnRightIndex;
  3977. }
  3978. cellColumnIndex = cellColumnRightIndex - 1;
  3979. }
  3980. else { // can't drop inside a spanned cell, or this is the
  3981. // dragged cell
  3982. while (colspan > 1) {
  3983. cellColumnIndex++;
  3984. colspan--;
  3985. unavailableColumnDropIndices.add(cellColumnIndex);
  3986. }
  3987. }
  3988. }
  3989. }
  3990. if (leftBound == (rightBound - 1)) {
  3991. return;
  3992. }
  3993. double position = autoScroller.getFrozenColumnsWidth();
  3994. // iterate column indices and add possible drop positions
  3995. for (int i = frozenColumns; i < getColumnCount(); i++) {
  3996. Column<?, T> column = getColumn(i);
  3997. if (!unavailableColumnDropIndices.contains(i)
  3998. && !column.isHidden()) {
  3999. if (leftBound != -1) {
  4000. if (i >= leftBound && i <= rightBound) {
  4001. possibleDropPositions.put(position, i);
  4002. }
  4003. } else {
  4004. possibleDropPositions.put(position, i);
  4005. }
  4006. }
  4007. position += column.getWidthActual();
  4008. }
  4009. if (leftBound == -1) {
  4010. // add the right side of the last column as columns.size()
  4011. possibleDropPositions.put(position, getColumnCount());
  4012. }
  4013. }
  4014. };
  4015. /**
  4016. * Enumeration for easy setting of selection mode.
  4017. */
  4018. public enum SelectionMode {
  4019. /**
  4020. * Shortcut for {@link SelectionModelSingle}.
  4021. */
  4022. SINGLE {
  4023. @Override
  4024. protected <T> SelectionModel<T> createModel() {
  4025. return GWT.create(SelectionModelSingle.class);
  4026. }
  4027. },
  4028. /**
  4029. * Shortcut for {@link SelectionModelMulti}.
  4030. */
  4031. MULTI {
  4032. @Override
  4033. protected <T> SelectionModel<T> createModel() {
  4034. return GWT.create(SelectionModelMulti.class);
  4035. }
  4036. },
  4037. /**
  4038. * Shortcut for {@link SelectionModelNone}.
  4039. */
  4040. NONE {
  4041. @Override
  4042. protected <T> SelectionModel<T> createModel() {
  4043. return GWT.create(SelectionModelNone.class);
  4044. }
  4045. };
  4046. protected abstract <T> SelectionModel<T> createModel();
  4047. }
  4048. /**
  4049. * Base class for grid columns internally used by the Grid. The user should
  4050. * use {@link Column} when creating new columns.
  4051. *
  4052. * @param <C>
  4053. * the column type
  4054. *
  4055. * @param <T>
  4056. * the row type
  4057. */
  4058. public static abstract class Column<C, T> {
  4059. /**
  4060. * Default renderer for GridColumns. Renders everything into text
  4061. * through {@link Object#toString()}.
  4062. */
  4063. private final class DefaultTextRenderer implements Renderer<Object> {
  4064. boolean warned = false;
  4065. private final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  4066. + "A more suitable renderer should be set using the setRenderer() method.";
  4067. @Override
  4068. public void render(RendererCellReference cell, Object data) {
  4069. if (!warned && !(data instanceof String)) {
  4070. getLogger().warning(Column.this.toString() + ": "
  4071. + DEFAULT_RENDERER_WARNING);
  4072. warned = true;
  4073. }
  4074. final String text;
  4075. if (data == null) {
  4076. text = "";
  4077. } else {
  4078. text = data.toString();
  4079. }
  4080. cell.getElement().setInnerText(text);
  4081. }
  4082. }
  4083. /**
  4084. * the column is associated with
  4085. */
  4086. private Grid<T> grid;
  4087. /**
  4088. * Width of column in pixels as {@link #setWidth(double)} has been
  4089. * called
  4090. */
  4091. private double widthUser = GridConstants.DEFAULT_COLUMN_WIDTH_PX;
  4092. /**
  4093. * Renderer for rendering a value into the cell
  4094. */
  4095. private Renderer<? super C> bodyRenderer;
  4096. private boolean sortable = false;
  4097. private boolean editable = true;
  4098. private boolean resizable = true;
  4099. private boolean hidden = false;
  4100. private boolean hidable = false;
  4101. private String headerCaption = "";
  4102. private String hidingToggleCaption = null;
  4103. private double minimumWidthPx = GridConstants.DEFAULT_MIN_WIDTH;
  4104. private double maximumWidthPx = GridConstants.DEFAULT_MAX_WIDTH;
  4105. private int expandRatio = GridConstants.DEFAULT_EXPAND_RATIO;
  4106. /**
  4107. * Constructs a new column with a simple TextRenderer.
  4108. */
  4109. public Column() {
  4110. setRenderer(new DefaultTextRenderer());
  4111. }
  4112. /**
  4113. * Constructs a new column with a simple TextRenderer.
  4114. *
  4115. * @param caption
  4116. * The header caption for this column
  4117. *
  4118. * @throws IllegalArgumentException
  4119. * if given header caption is null
  4120. */
  4121. public Column(String caption) throws IllegalArgumentException {
  4122. this();
  4123. setHeaderCaption(caption);
  4124. }
  4125. /**
  4126. * Constructs a new column with a custom renderer.
  4127. *
  4128. * @param renderer
  4129. * The renderer to use for rendering the cells
  4130. *
  4131. * @throws IllegalArgumentException
  4132. * if given Renderer is null
  4133. */
  4134. public Column(Renderer<? super C> renderer)
  4135. throws IllegalArgumentException {
  4136. setRenderer(renderer);
  4137. }
  4138. /**
  4139. * Constructs a new column with a custom renderer.
  4140. *
  4141. * @param renderer
  4142. * The renderer to use for rendering the cells
  4143. * @param caption
  4144. * The header caption for this column
  4145. *
  4146. * @throws IllegalArgumentException
  4147. * if given Renderer or header caption is null
  4148. */
  4149. public Column(String caption, Renderer<? super C> renderer)
  4150. throws IllegalArgumentException {
  4151. this(renderer);
  4152. setHeaderCaption(caption);
  4153. }
  4154. /**
  4155. * Internally used by the grid to set itself
  4156. *
  4157. * @param grid
  4158. */
  4159. private void setGrid(Grid<T> grid) {
  4160. if (this.grid != null && grid != null) {
  4161. // Trying to replace grid
  4162. throw new IllegalStateException("Column already is attached "
  4163. + "to a grid. Remove the column first from the grid "
  4164. + "and then add it. (in: " + toString() + ")");
  4165. }
  4166. if (this.grid != null) {
  4167. this.grid.recalculateColumnWidths();
  4168. }
  4169. this.grid = grid;
  4170. if (this.grid != null) {
  4171. this.grid.recalculateColumnWidths();
  4172. }
  4173. }
  4174. /**
  4175. * Sets a header caption for this column.
  4176. *
  4177. * @param caption
  4178. * The header caption for this column
  4179. * @return the column itself
  4180. *
  4181. */
  4182. public Column<C, T> setHeaderCaption(String caption) {
  4183. if (caption == null) {
  4184. caption = "";
  4185. }
  4186. if (!this.headerCaption.equals(caption)) {
  4187. this.headerCaption = caption;
  4188. if (grid != null) {
  4189. updateHeader();
  4190. }
  4191. }
  4192. return this;
  4193. }
  4194. /**
  4195. * Returns the current header caption for this column
  4196. *
  4197. * @since 7.6
  4198. * @return the header caption string
  4199. */
  4200. public String getHeaderCaption() {
  4201. return headerCaption;
  4202. }
  4203. private void updateHeader() {
  4204. HeaderRow row = grid.getHeader().getDefaultRow();
  4205. if (row != null) {
  4206. row.getCell(this).setText(headerCaption);
  4207. if (isHidable()) {
  4208. grid.columnHider.updateHidingToggle(this);
  4209. }
  4210. }
  4211. }
  4212. /**
  4213. * Returns the data that should be rendered into the cell. By default
  4214. * returning Strings and Widgets are supported. If the return type is a
  4215. * String then it will be treated as preformatted text.
  4216. * <p>
  4217. * To support other types you will need to pass a custom renderer to the
  4218. * column via the column constructor.
  4219. *
  4220. * @param row
  4221. * The row object that provides the cell content.
  4222. *
  4223. * @return The cell content
  4224. */
  4225. public abstract C getValue(T row);
  4226. /**
  4227. * The renderer to render the cell with. By default renders the data as
  4228. * a String or adds the widget into the cell if the column type is of
  4229. * widget type.
  4230. *
  4231. * @return The renderer to render the cell content with
  4232. */
  4233. public Renderer<? super C> getRenderer() {
  4234. return bodyRenderer;
  4235. }
  4236. /**
  4237. * Sets a custom {@link Renderer} for this column.
  4238. *
  4239. * @param renderer
  4240. * The renderer to use for rendering the cells
  4241. * @return the column itself
  4242. *
  4243. * @throws IllegalArgumentException
  4244. * if given Renderer is null
  4245. */
  4246. public Column<C, T> setRenderer(Renderer<? super C> renderer)
  4247. throws IllegalArgumentException {
  4248. if (renderer == null) {
  4249. throw new IllegalArgumentException("Renderer cannot be null.");
  4250. }
  4251. if (renderer != bodyRenderer) {
  4252. // Variables used to restore removed column.
  4253. boolean columnRemoved = false;
  4254. double widthInConfiguration = 0.0d;
  4255. ColumnConfiguration conf = null;
  4256. int index = 0;
  4257. if (grid != null && (bodyRenderer instanceof WidgetRenderer
  4258. || renderer instanceof WidgetRenderer)) {
  4259. // Column needs to be recreated.
  4260. index = grid.getColumns().indexOf(this);
  4261. conf = grid.escalator.getColumnConfiguration();
  4262. widthInConfiguration = conf.getColumnWidth(index);
  4263. conf.removeColumns(index, 1);
  4264. columnRemoved = true;
  4265. }
  4266. // Complex renderers need to be destroyed.
  4267. if (bodyRenderer instanceof ComplexRenderer) {
  4268. ((ComplexRenderer) bodyRenderer).destroy();
  4269. }
  4270. bodyRenderer = renderer;
  4271. if (columnRemoved) {
  4272. // Restore the column.
  4273. conf.insertColumns(index, 1);
  4274. conf.setColumnWidth(index, widthInConfiguration);
  4275. }
  4276. if (grid != null) {
  4277. grid.refreshBody();
  4278. }
  4279. }
  4280. return this;
  4281. }
  4282. /**
  4283. * Sets the pixel width of the column. Use a negative value for the grid
  4284. * to autosize column based on content and available space.
  4285. * <p>
  4286. * This action is done "finally", once the current execution loop
  4287. * returns. This is done to reduce overhead of unintentionally always
  4288. * recalculate all columns, when modifying several columns at once.
  4289. * <p>
  4290. * If the column is currently {@link #isHidden() hidden}, then this set
  4291. * width has effect only once the column has been made visible again.
  4292. *
  4293. * @param pixels
  4294. * the width in pixels or negative for auto sizing
  4295. */
  4296. public Column<C, T> setWidth(double pixels) {
  4297. if (!WidgetUtil.pixelValuesEqual(widthUser, pixels)) {
  4298. widthUser = pixels;
  4299. if (!isHidden()) {
  4300. scheduleColumnWidthRecalculator();
  4301. }
  4302. }
  4303. return this;
  4304. }
  4305. void doSetWidth(double pixels) {
  4306. assert !isHidden() : "applying width for a hidden column";
  4307. if (grid != null) {
  4308. int index = grid.getVisibleColumns().indexOf(this);
  4309. ColumnConfiguration conf = grid.escalator
  4310. .getColumnConfiguration();
  4311. conf.setColumnWidth(index, pixels);
  4312. }
  4313. }
  4314. /**
  4315. * Returns the pixel width of the column as given by the user.
  4316. * <p>
  4317. * <em>Note:</em> If a negative value was given to
  4318. * {@link #setWidth(double)}, that same negative value is returned here.
  4319. * <p>
  4320. * <em>Note:</em> Returns the value, even if the column is currently
  4321. * {@link #isHidden() hidden}.
  4322. *
  4323. * @return pixel width of the column, or a negative number if the column
  4324. * width has been automatically calculated.
  4325. * @see #setWidth(double)
  4326. * @see #getWidthActual()
  4327. */
  4328. public double getWidth() {
  4329. return widthUser;
  4330. }
  4331. /**
  4332. * Returns the effective pixel width of the column.
  4333. * <p>
  4334. * This differs from {@link #getWidth()} only when the column has been
  4335. * automatically resized, or when the column is currently
  4336. * {@link #isHidden() hidden}, when the value is 0.
  4337. *
  4338. * @return pixel width of the column.
  4339. */
  4340. public double getWidthActual() {
  4341. if (isHidden()) {
  4342. return 0;
  4343. }
  4344. return grid.escalator.getColumnConfiguration().getColumnWidthActual(
  4345. grid.getVisibleColumns().indexOf(this));
  4346. }
  4347. void reapplyWidth() {
  4348. scheduleColumnWidthRecalculator();
  4349. }
  4350. /**
  4351. * Sets whether the column should be sortable by the user. The grid can
  4352. * be sorted by a sortable column by clicking or tapping the column's
  4353. * default header. Programmatic sorting using the Grid#sort methods is
  4354. * not affected by this setting.
  4355. *
  4356. * @param sortable
  4357. * {@code true} if the user should be able to sort the
  4358. * column, {@code false} otherwise
  4359. * @return the column itself
  4360. */
  4361. public Column<C, T> setSortable(boolean sortable) {
  4362. if (this.sortable != sortable) {
  4363. this.sortable = sortable;
  4364. if (grid != null) {
  4365. grid.refreshHeader();
  4366. }
  4367. }
  4368. return this;
  4369. }
  4370. /**
  4371. * Returns whether the user can sort the grid by this column.
  4372. * <p>
  4373. * <em>Note:</em> it is possible to sort by this column programmatically
  4374. * using the Grid#sort methods regardless of the returned value.
  4375. *
  4376. * @return {@code true} if the column is sortable by the user,
  4377. * {@code false} otherwise
  4378. */
  4379. public boolean isSortable() {
  4380. return sortable;
  4381. }
  4382. /**
  4383. * Sets whether this column can be resized by the user.
  4384. *
  4385. * @since 7.6
  4386. *
  4387. * @param resizable
  4388. * {@code true} if this column should be resizable,
  4389. * {@code false} otherwise
  4390. */
  4391. public Column<C, T> setResizable(boolean resizable) {
  4392. if (this.resizable != resizable) {
  4393. this.resizable = resizable;
  4394. if (grid != null) {
  4395. grid.refreshHeader();
  4396. }
  4397. }
  4398. return this;
  4399. }
  4400. /**
  4401. * Returns whether this column can be resized by the user. Default is
  4402. * {@code true}.
  4403. * <p>
  4404. * <em>Note:</em> the column can be programmatically resized using
  4405. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  4406. * of the returned value.
  4407. *
  4408. * @since 7.6
  4409. *
  4410. * @return {@code true} if this column is resizable, {@code false}
  4411. * otherwise
  4412. */
  4413. public boolean isResizable() {
  4414. return resizable;
  4415. }
  4416. /**
  4417. * Hides or shows the column. By default columns are visible before
  4418. * explicitly hiding them.
  4419. *
  4420. * @since 7.5.0
  4421. * @param hidden
  4422. * <code>true</code> to hide the column, <code>false</code>
  4423. * to show
  4424. */
  4425. public Column<C, T> setHidden(boolean hidden) {
  4426. setHidden(hidden, false);
  4427. return this;
  4428. }
  4429. private void setHidden(boolean hidden, boolean userOriginated) {
  4430. if (this.hidden != hidden) {
  4431. if (hidden) {
  4432. grid.escalator.getColumnConfiguration().removeColumns(
  4433. grid.getVisibleColumns().indexOf(this), 1);
  4434. this.hidden = hidden;
  4435. } else {
  4436. this.hidden = hidden;
  4437. final int columnIndex = grid.getVisibleColumns()
  4438. .indexOf(this);
  4439. grid.escalator.getColumnConfiguration()
  4440. .insertColumns(columnIndex, 1);
  4441. // make sure column is set to frozen if it needs to be,
  4442. // escalator doesn't handle situation where the added column
  4443. // would be the last frozen column
  4444. int gridFrozenColumns = grid.getFrozenColumnCount();
  4445. int escalatorFrozenColumns = grid.escalator
  4446. .getColumnConfiguration().getFrozenColumnCount();
  4447. if (gridFrozenColumns > escalatorFrozenColumns
  4448. && escalatorFrozenColumns == columnIndex) {
  4449. grid.escalator.getColumnConfiguration()
  4450. .setFrozenColumnCount(++escalatorFrozenColumns);
  4451. }
  4452. }
  4453. grid.columnHider.updateHidingToggle(this);
  4454. grid.header.updateColSpans();
  4455. grid.footer.updateColSpans();
  4456. scheduleColumnWidthRecalculator();
  4457. this.grid.fireEvent(new ColumnVisibilityChangeEvent<T>(this,
  4458. hidden, userOriginated));
  4459. }
  4460. }
  4461. /**
  4462. * Returns whether this column is hidden. Default is {@code false}.
  4463. *
  4464. * @since 7.5.0
  4465. * @return {@code true} if the column is currently hidden, {@code false}
  4466. * otherwise
  4467. */
  4468. public boolean isHidden() {
  4469. return hidden;
  4470. }
  4471. /**
  4472. * Set whether it is possible for the user to hide this column or not.
  4473. * Default is {@code false}.
  4474. * <p>
  4475. * <em>Note:</em> it is still possible to hide the column
  4476. * programmatically using {@link #setHidden(boolean)}.
  4477. *
  4478. * @since 7.5.0
  4479. * @param hidable
  4480. * {@code true} the user can hide this column, {@code false}
  4481. * otherwise
  4482. */
  4483. public Column<C, T> setHidable(boolean hidable) {
  4484. if (this.hidable != hidable) {
  4485. this.hidable = hidable;
  4486. grid.columnHider.updateColumnHidable(this);
  4487. }
  4488. return this;
  4489. }
  4490. /**
  4491. * Is it possible for the the user to hide this column. Default is
  4492. * {@code false}.
  4493. * <p>
  4494. * <em>Note:</em> the column can be programmatically hidden using
  4495. * {@link #setHidden(boolean)} regardless of the returned value.
  4496. *
  4497. * @since 7.5.0
  4498. * @return <code>true</code> if the user can hide the column,
  4499. * <code>false</code> if not
  4500. */
  4501. public boolean isHidable() {
  4502. return hidable;
  4503. }
  4504. /**
  4505. * Sets the hiding toggle's caption for this column. Shown in the toggle
  4506. * for this column in the grid's sidebar when the column is
  4507. * {@link #isHidable() hidable}.
  4508. * <p>
  4509. * The default value is <code>null</code>. In this case the header
  4510. * caption is used, see {@link #setHeaderCaption(String)}.
  4511. *
  4512. * @since 7.5.0
  4513. * @param hidingToggleCaption
  4514. * the caption for the hiding toggle for this column
  4515. */
  4516. public Column<C, T> setHidingToggleCaption(String hidingToggleCaption) {
  4517. this.hidingToggleCaption = hidingToggleCaption;
  4518. if (isHidable()) {
  4519. grid.columnHider.updateHidingToggle(this);
  4520. }
  4521. return this;
  4522. }
  4523. /**
  4524. * Gets the hiding toggle caption for this column.
  4525. *
  4526. * @since 7.5.0
  4527. * @see #setHidingToggleCaption(String)
  4528. * @return the hiding toggle's caption for this column
  4529. */
  4530. public String getHidingToggleCaption() {
  4531. return hidingToggleCaption;
  4532. }
  4533. @Override
  4534. public String toString() {
  4535. String details = "";
  4536. if (headerCaption != null && !headerCaption.isEmpty()) {
  4537. details += "header:\"" + headerCaption + "\" ";
  4538. } else {
  4539. details += "header:empty ";
  4540. }
  4541. if (grid != null) {
  4542. int index = grid.getColumns().indexOf(this);
  4543. if (index != -1) {
  4544. details += "attached:#" + index + " ";
  4545. } else {
  4546. details += "attached:unindexed ";
  4547. }
  4548. } else {
  4549. details += "detached ";
  4550. }
  4551. details += "sortable:" + sortable + " ";
  4552. return getClass().getSimpleName() + "[" + details.trim() + "]";
  4553. }
  4554. /**
  4555. * Sets the minimum width for this column.
  4556. * <p>
  4557. * This defines the minimum guaranteed pixel width of the column
  4558. * <em>when it is set to expand</em>.
  4559. * <p>
  4560. * This action is done "finally", once the current execution loop
  4561. * returns. This is done to reduce overhead of unintentionally always
  4562. * recalculate all columns, when modifying several columns at once.
  4563. *
  4564. * @param pixels
  4565. * the minimum width
  4566. * @return this column
  4567. */
  4568. public Column<C, T> setMinimumWidth(double pixels) {
  4569. final double maxwidth = getMaximumWidth();
  4570. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  4571. throw new IllegalArgumentException("New minimum width ("
  4572. + pixels + ") was greater than maximum width ("
  4573. + maxwidth + ")");
  4574. }
  4575. if (minimumWidthPx != pixels) {
  4576. minimumWidthPx = pixels;
  4577. scheduleColumnWidthRecalculator();
  4578. }
  4579. return this;
  4580. }
  4581. /**
  4582. * Sets the maximum width for this column.
  4583. * <p>
  4584. * This defines the maximum allowed pixel width of the column <em>when
  4585. * it is set to expand</em>.
  4586. * <p>
  4587. * This action is done "finally", once the current execution loop
  4588. * returns. This is done to reduce overhead of unintentionally always
  4589. * recalculate all columns, when modifying several columns at once.
  4590. *
  4591. * @param pixels
  4592. * the maximum width
  4593. * @param immediately
  4594. * <code>true</code> if the widths should be executed
  4595. * immediately (ignoring lazy loading completely), or
  4596. * <code>false</code> if the command should be run after a
  4597. * while (duplicate non-immediately invocations are ignored).
  4598. * @return this column
  4599. */
  4600. public Column<C, T> setMaximumWidth(double pixels) {
  4601. final double minwidth = getMinimumWidth();
  4602. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  4603. throw new IllegalArgumentException("New maximum width ("
  4604. + pixels + ") was less than minimum width (" + minwidth
  4605. + ")");
  4606. }
  4607. if (maximumWidthPx != pixels) {
  4608. maximumWidthPx = pixels;
  4609. scheduleColumnWidthRecalculator();
  4610. }
  4611. return this;
  4612. }
  4613. /**
  4614. * Sets the ratio with which the column expands.
  4615. * <p>
  4616. * By default, all columns expand equally (treated as if all of them had
  4617. * an expand ratio of 1). Once at least one column gets a defined expand
  4618. * ratio, the implicit expand ratio is removed, and only the defined
  4619. * expand ratios are taken into account.
  4620. * <p>
  4621. * If a column has a defined width ({@link #setWidth(double)}), it
  4622. * overrides this method's effects.
  4623. * <p>
  4624. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  4625. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  4626. * as wide as its contents requires</strong>. The column with a ratio of
  4627. * 1 is as wide as it needs, <strong>plus a third of any excess
  4628. * space</strong>, bceause we have 3 parts total, and this column
  4629. * reservs only one of those. The column with a ratio of 2, is as wide
  4630. * as it needs to be, <strong>plus two thirds</strong> of the excess
  4631. * width.
  4632. * <p>
  4633. * This action is done "finally", once the current execution loop
  4634. * returns. This is done to reduce overhead of unintentionally always
  4635. * recalculate all columns, when modifying several columns at once.
  4636. *
  4637. * @param expandRatio
  4638. * the expand ratio of this column. {@code 0} to not have it
  4639. * expand at all. A negative number to clear the expand
  4640. * value.
  4641. * @return this column
  4642. */
  4643. public Column<C, T> setExpandRatio(int ratio) {
  4644. if (expandRatio != ratio) {
  4645. expandRatio = ratio;
  4646. scheduleColumnWidthRecalculator();
  4647. }
  4648. return this;
  4649. }
  4650. /**
  4651. * Clears the column's expand ratio.
  4652. * <p>
  4653. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  4654. *
  4655. * @return this column
  4656. */
  4657. public Column<C, T> clearExpandRatio() {
  4658. return setExpandRatio(-1);
  4659. }
  4660. /**
  4661. * Gets the minimum width for this column.
  4662. *
  4663. * @return the minimum width for this column
  4664. * @see #setMinimumWidth(double)
  4665. */
  4666. public double getMinimumWidth() {
  4667. return minimumWidthPx;
  4668. }
  4669. /**
  4670. * Gets the maximum width for this column.
  4671. *
  4672. * @return the maximum width for this column
  4673. * @see #setMaximumWidth(double)
  4674. */
  4675. public double getMaximumWidth() {
  4676. return maximumWidthPx;
  4677. }
  4678. /**
  4679. * Gets the expand ratio for this column.
  4680. *
  4681. * @return the expand ratio for this column
  4682. * @see #setExpandRatio(int)
  4683. */
  4684. public int getExpandRatio() {
  4685. return expandRatio;
  4686. }
  4687. /**
  4688. * Sets whether the values in this column should be editable by the user
  4689. * when the row editor is active. By default columns are editable.
  4690. *
  4691. * @param editable
  4692. * {@code true} to set this column editable, {@code false}
  4693. * otherwise
  4694. * @return this column
  4695. *
  4696. * @throws IllegalStateException
  4697. * if the editor is currently active
  4698. *
  4699. * @see Grid#editRow(int)
  4700. * @see Grid#isEditorActive()
  4701. */
  4702. public Column<C, T> setEditable(boolean editable) {
  4703. if (editable != this.editable && grid.isEditorActive()) {
  4704. throw new IllegalStateException(
  4705. "Cannot change column editable status while the editor is active");
  4706. }
  4707. this.editable = editable;
  4708. return this;
  4709. }
  4710. /**
  4711. * Returns whether the values in this column are editable by the user
  4712. * when the row editor is active.
  4713. *
  4714. * @return {@code true} if this column is editable, {@code false}
  4715. * otherwise
  4716. *
  4717. * @see #setEditable(boolean)
  4718. */
  4719. public boolean isEditable() {
  4720. return editable;
  4721. }
  4722. private void scheduleColumnWidthRecalculator() {
  4723. if (grid != null) {
  4724. grid.recalculateColumnWidths();
  4725. } else {
  4726. /*
  4727. * NOOP
  4728. *
  4729. * Since setGrid() will call reapplyWidths as the colum is
  4730. * attached to a grid, it will call setWidth, which, in turn,
  4731. * will call this method again. Therefore, it's guaranteed that
  4732. * the recalculation is scheduled eventually, once the column is
  4733. * attached to a grid.
  4734. */
  4735. }
  4736. }
  4737. /**
  4738. * Resets the default header cell contents to column header captions.
  4739. *
  4740. * @since 7.5.1
  4741. * @param cell
  4742. * default header cell for this column
  4743. */
  4744. protected void setDefaultHeaderContent(HeaderCell cell) {
  4745. cell.setText(headerCaption);
  4746. }
  4747. }
  4748. protected class BodyUpdater implements EscalatorUpdater {
  4749. @Override
  4750. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  4751. int rowIndex = row.getRow();
  4752. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  4753. row.getElement());
  4754. for (FlyweightCell cell : cellsToAttach) {
  4755. Renderer<?> renderer = findRenderer(cell);
  4756. if (renderer instanceof ComplexRenderer) {
  4757. try {
  4758. Column<?, T> column = getVisibleColumn(
  4759. cell.getColumn());
  4760. rendererCellReference.set(cell,
  4761. getColumns().indexOf(column), column);
  4762. ((ComplexRenderer<?>) renderer)
  4763. .init(rendererCellReference);
  4764. } catch (RuntimeException e) {
  4765. getLogger().log(Level.SEVERE,
  4766. "Error initing cell in column "
  4767. + cell.getColumn(),
  4768. e);
  4769. }
  4770. }
  4771. }
  4772. }
  4773. @Override
  4774. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  4775. for (FlyweightCell cell : attachedCells) {
  4776. Renderer<?> renderer = findRenderer(cell);
  4777. if (renderer instanceof WidgetRenderer) {
  4778. try {
  4779. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  4780. Widget widget = widgetRenderer.createWidget();
  4781. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  4782. assert widget
  4783. .getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  4784. assert cell.getElement()
  4785. .getChildCount() == 0 : "Cell content should be empty when adding Widget";
  4786. // Physical attach
  4787. cell.getElement().appendChild(widget.getElement());
  4788. // Logical attach
  4789. setParent(widget, Grid.this);
  4790. } catch (RuntimeException e) {
  4791. getLogger().log(Level.SEVERE,
  4792. "Error attaching child widget in column "
  4793. + cell.getColumn(),
  4794. e);
  4795. }
  4796. }
  4797. }
  4798. }
  4799. @Override
  4800. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4801. int rowIndex = row.getRow();
  4802. TableRowElement rowElement = row.getElement();
  4803. T rowData = dataSource.getRow(rowIndex);
  4804. boolean hasData = rowData != null;
  4805. /*
  4806. * TODO could be more efficient to build a list of all styles that
  4807. * should be used and update the element only once instead of
  4808. * attempting to update only the ones that have changed.
  4809. */
  4810. // Assign stylename for rows with data
  4811. boolean usedToHaveData = rowElement
  4812. .hasClassName(rowHasDataStyleName);
  4813. if (usedToHaveData != hasData) {
  4814. setStyleName(rowElement, rowHasDataStyleName, hasData);
  4815. }
  4816. boolean isEvenIndex = (row.getRow() % 2 == 0);
  4817. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  4818. rowReference.set(rowIndex, rowData, rowElement);
  4819. if (hasData) {
  4820. setStyleName(rowElement, rowSelectedStyleName,
  4821. isSelected(rowData));
  4822. if (rowStyleGenerator != null) {
  4823. try {
  4824. String rowStylename = rowStyleGenerator
  4825. .getStyle(rowReference);
  4826. setCustomStyleName(rowElement, rowStylename);
  4827. } catch (RuntimeException e) {
  4828. getLogger().log(Level.SEVERE,
  4829. "Error generating styles for row "
  4830. + row.getRow(),
  4831. e);
  4832. }
  4833. } else {
  4834. // Remove in case there was a generator previously
  4835. setCustomStyleName(rowElement, null);
  4836. }
  4837. } else if (usedToHaveData) {
  4838. setStyleName(rowElement, rowSelectedStyleName, false);
  4839. setCustomStyleName(rowElement, null);
  4840. }
  4841. cellFocusHandler.updateFocusedRowStyle(row);
  4842. for (FlyweightCell cell : cellsToUpdate) {
  4843. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4844. final int columnIndex = getColumns().indexOf(column);
  4845. assert column != null : "Column was not found from cell ("
  4846. + cell.getColumn() + "," + cell.getRow() + ")";
  4847. cellFocusHandler.updateFocusedCellStyle(cell,
  4848. escalator.getBody());
  4849. if (hasData && cellStyleGenerator != null) {
  4850. try {
  4851. cellReference.set(cell.getColumn(), columnIndex,
  4852. column);
  4853. String generatedStyle = cellStyleGenerator
  4854. .getStyle(cellReference);
  4855. setCustomStyleName(cell.getElement(), generatedStyle);
  4856. } catch (RuntimeException e) {
  4857. getLogger().log(Level.SEVERE,
  4858. "Error generating style for cell in column "
  4859. + cell.getColumn(),
  4860. e);
  4861. }
  4862. } else if (hasData || usedToHaveData) {
  4863. setCustomStyleName(cell.getElement(), null);
  4864. }
  4865. Renderer renderer = column.getRenderer();
  4866. try {
  4867. rendererCellReference.set(cell, columnIndex, column);
  4868. if (renderer instanceof ComplexRenderer) {
  4869. // Hide cell content if needed
  4870. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  4871. if (hasData) {
  4872. if (!usedToHaveData) {
  4873. // Prepare cell for rendering
  4874. clxRenderer.setContentVisible(
  4875. rendererCellReference, true);
  4876. }
  4877. Object value = column.getValue(rowData);
  4878. clxRenderer.render(rendererCellReference, value);
  4879. } else {
  4880. // Prepare cell for no data
  4881. clxRenderer.setContentVisible(rendererCellReference,
  4882. false);
  4883. }
  4884. } else if (hasData) {
  4885. // Simple renderers just render
  4886. Object value = column.getValue(rowData);
  4887. renderer.render(rendererCellReference, value);
  4888. } else {
  4889. // Clear cell if there is no data
  4890. cell.getElement().removeAllChildren();
  4891. }
  4892. } catch (RuntimeException e) {
  4893. getLogger().log(Level.SEVERE,
  4894. "Error rendering cell in column "
  4895. + cell.getColumn(),
  4896. e);
  4897. }
  4898. }
  4899. }
  4900. @Override
  4901. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  4902. for (FlyweightCell cell : cellsToDetach) {
  4903. Renderer<?> renderer = findRenderer(cell);
  4904. if (renderer instanceof WidgetRenderer) {
  4905. try {
  4906. Widget w = WidgetUtil.findWidget(
  4907. cell.getElement().getFirstChildElement(), null);
  4908. if (w != null) {
  4909. // Logical detach
  4910. setParent(w, null);
  4911. // Physical detach
  4912. cell.getElement().removeChild(w.getElement());
  4913. }
  4914. } catch (RuntimeException e) {
  4915. getLogger().log(Level.SEVERE,
  4916. "Error detaching widget in column "
  4917. + cell.getColumn(),
  4918. e);
  4919. }
  4920. }
  4921. }
  4922. }
  4923. @Override
  4924. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  4925. int rowIndex = row.getRow();
  4926. // Passing null row data since it might not exist in the data source
  4927. // any more
  4928. rowReference.set(rowIndex, null, row.getElement());
  4929. for (FlyweightCell cell : detachedCells) {
  4930. Renderer<?> renderer = findRenderer(cell);
  4931. if (renderer instanceof ComplexRenderer) {
  4932. try {
  4933. Column<?, T> column = getVisibleColumn(
  4934. cell.getColumn());
  4935. rendererCellReference.set(cell,
  4936. getColumns().indexOf(column), column);
  4937. ((ComplexRenderer) renderer)
  4938. .destroy(rendererCellReference);
  4939. } catch (RuntimeException e) {
  4940. getLogger().log(Level.SEVERE,
  4941. "Error destroying cell in column "
  4942. + cell.getColumn(),
  4943. e);
  4944. }
  4945. }
  4946. }
  4947. }
  4948. }
  4949. protected class StaticSectionUpdater implements EscalatorUpdater {
  4950. private StaticSection<?> section;
  4951. private RowContainer container;
  4952. public StaticSectionUpdater(StaticSection<?> section,
  4953. RowContainer container) {
  4954. super();
  4955. this.section = section;
  4956. this.container = container;
  4957. }
  4958. @Override
  4959. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4960. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  4961. final List<Column<?, T>> columns = getVisibleColumns();
  4962. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  4963. for (FlyweightCell cell : cellsToUpdate) {
  4964. final StaticSection.StaticCell metadata = staticRow
  4965. .getCell(columns.get(cell.getColumn()));
  4966. // Decorate default row with sorting indicators
  4967. if (staticRow instanceof HeaderRow) {
  4968. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow,
  4969. cell);
  4970. }
  4971. // Assign colspan to cell before rendering
  4972. cell.setColSpan(metadata.getColspan());
  4973. Element td = cell.getElement();
  4974. td.removeAllChildren();
  4975. setCustomStyleName(td, metadata.getStyleName());
  4976. Element content;
  4977. // Wrap text or html content in default header to isolate
  4978. // the content from the possible column resize drag handle
  4979. // next to it
  4980. if (metadata.getType() != GridStaticCellType.WIDGET) {
  4981. content = DOM.createDiv();
  4982. if (staticRow instanceof HeaderRow) {
  4983. content.setClassName(getStylePrimaryName()
  4984. + "-column-header-content");
  4985. if (((HeaderRow) staticRow).isDefault()) {
  4986. content.setClassName(content.getClassName() + " "
  4987. + getStylePrimaryName()
  4988. + "-column-default-header-content");
  4989. }
  4990. } else if (staticRow instanceof FooterRow) {
  4991. content.setClassName(getStylePrimaryName()
  4992. + "-column-footer-content");
  4993. } else {
  4994. getLogger().severe("Unhandled static row type "
  4995. + staticRow.getClass().getCanonicalName());
  4996. }
  4997. td.appendChild(content);
  4998. } else {
  4999. content = td;
  5000. }
  5001. switch (metadata.getType()) {
  5002. case TEXT:
  5003. content.setInnerText(metadata.getText());
  5004. break;
  5005. case HTML:
  5006. content.setInnerHTML(metadata.getHtml());
  5007. break;
  5008. case WIDGET:
  5009. preDetach(row, Arrays.asList(cell));
  5010. content.setInnerHTML("");
  5011. postAttach(row, Arrays.asList(cell));
  5012. break;
  5013. }
  5014. // XXX: Should add only once in preAttach/postAttach or when
  5015. // resizable status changes
  5016. // Only add resize handles to default header row for now
  5017. if (columns.get(cell.getColumn()).isResizable()
  5018. && staticRow instanceof HeaderRow
  5019. && ((HeaderRow) staticRow).isDefault()) {
  5020. final int column = cell.getColumn();
  5021. DragHandle dragger = new DragHandle(
  5022. getStylePrimaryName() + "-column-resize-handle",
  5023. new DragHandleCallback() {
  5024. private Column<?, T> col = getVisibleColumn(
  5025. column);
  5026. private double initialWidth = 0;
  5027. private double minCellWidth;
  5028. @Override
  5029. public void onUpdate(double deltaX,
  5030. double deltaY) {
  5031. col.setWidth(Math.max(minCellWidth,
  5032. initialWidth + deltaX));
  5033. }
  5034. @Override
  5035. public void onStart() {
  5036. initialWidth = col.getWidthActual();
  5037. minCellWidth = escalator.getMinCellWidth(
  5038. getVisibleColumns().indexOf(col));
  5039. for (Column<?, T> c : getVisibleColumns()) {
  5040. if (selectionColumn == c) {
  5041. // Don't modify selection column.
  5042. continue;
  5043. }
  5044. if (c.getWidth() < 0) {
  5045. c.setWidth(c.getWidthActual());
  5046. fireEvent(new ColumnResizeEvent<T>(
  5047. c));
  5048. }
  5049. }
  5050. WidgetUtil.setTextSelectionEnabled(
  5051. getElement(), false);
  5052. }
  5053. @Override
  5054. public void onComplete() {
  5055. fireEvent(new ColumnResizeEvent<T>(col));
  5056. WidgetUtil.setTextSelectionEnabled(
  5057. getElement(), true);
  5058. }
  5059. @Override
  5060. public void onCancel() {
  5061. col.setWidth(initialWidth);
  5062. WidgetUtil.setTextSelectionEnabled(
  5063. getElement(), true);
  5064. }
  5065. });
  5066. dragger.addTo(td);
  5067. }
  5068. cellFocusHandler.updateFocusedCellStyle(cell, container);
  5069. }
  5070. }
  5071. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  5072. FlyweightCell cell) {
  5073. Element cellElement = cell.getElement();
  5074. boolean sortedBefore = cellElement.hasClassName("sort-asc")
  5075. || cellElement.hasClassName("sort-desc");
  5076. cleanup(cell);
  5077. if (!headerRow.isDefault()) {
  5078. // Nothing more to do if not in the default row
  5079. return;
  5080. }
  5081. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5082. SortOrder sortingOrder = getSortOrder(column);
  5083. boolean sortable = column.isSortable();
  5084. if (sortable) {
  5085. cellElement.addClassName("sortable");
  5086. }
  5087. if (!sortable || sortingOrder == null) {
  5088. // Only apply sorting indicators to sortable header columns
  5089. return;
  5090. }
  5091. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  5092. cellElement.addClassName("sort-asc");
  5093. } else {
  5094. cellElement.addClassName("sort-desc");
  5095. }
  5096. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  5097. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  5098. // Show sort order indicator if column is
  5099. // sorted and other sorted columns also exists.
  5100. cellElement.setAttribute("sort-order",
  5101. String.valueOf(sortIndex + 1));
  5102. }
  5103. if (!sortedBefore) {
  5104. verifyColumnWidth(column);
  5105. }
  5106. }
  5107. /**
  5108. * Sort indicator requires a bit more space from the cell than normally.
  5109. * This method check that the now sorted column has enough width.
  5110. *
  5111. * @param column
  5112. * sorted column
  5113. */
  5114. private void verifyColumnWidth(Column<?, T> column) {
  5115. int colIndex = getColumns().indexOf(column);
  5116. double minWidth = escalator.getMinCellWidth(colIndex);
  5117. if (column.getWidthActual() < minWidth) {
  5118. // Fix column size
  5119. escalator.getColumnConfiguration().setColumnWidth(colIndex,
  5120. minWidth);
  5121. fireEvent(new ColumnResizeEvent<T>(column));
  5122. }
  5123. }
  5124. /**
  5125. * Finds the sort order for this column
  5126. */
  5127. private SortOrder getSortOrder(Column<?, ?> column) {
  5128. for (SortOrder order : Grid.this.getSortOrder()) {
  5129. if (order.getColumn() == column) {
  5130. return order;
  5131. }
  5132. }
  5133. return null;
  5134. }
  5135. private void cleanup(FlyweightCell cell) {
  5136. Element cellElement = cell.getElement();
  5137. cellElement.removeAttribute("sort-order");
  5138. cellElement.removeClassName("sort-desc");
  5139. cellElement.removeClassName("sort-asc");
  5140. cellElement.removeClassName("sortable");
  5141. }
  5142. @Override
  5143. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5144. }
  5145. @Override
  5146. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5147. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  5148. List<Column<?, T>> columns = getVisibleColumns();
  5149. for (FlyweightCell cell : attachedCells) {
  5150. StaticSection.StaticCell metadata = gridRow
  5151. .getCell(columns.get(cell.getColumn()));
  5152. /*
  5153. * If the cell contains widgets that are not currently attached
  5154. * then attach them now.
  5155. */
  5156. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  5157. final Widget widget = metadata.getWidget();
  5158. if (widget != null && !widget.isAttached()) {
  5159. getGrid().attachWidget(metadata.getWidget(),
  5160. cell.getElement());
  5161. }
  5162. }
  5163. }
  5164. }
  5165. @Override
  5166. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5167. if (section.getRowCount() > row.getRow()) {
  5168. StaticSection.StaticRow<?> gridRow = section
  5169. .getRow(row.getRow());
  5170. List<Column<?, T>> columns = getVisibleColumns();
  5171. for (FlyweightCell cell : cellsToDetach) {
  5172. StaticSection.StaticCell metadata = gridRow
  5173. .getCell(columns.get(cell.getColumn()));
  5174. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  5175. && metadata.getWidget() != null
  5176. && metadata.getWidget().isAttached()) {
  5177. getGrid().detachWidget(metadata.getWidget());
  5178. }
  5179. }
  5180. }
  5181. }
  5182. protected Grid getGrid() {
  5183. return section.grid;
  5184. }
  5185. @Override
  5186. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5187. }
  5188. };
  5189. /**
  5190. * Creates a new instance.
  5191. */
  5192. public Grid() {
  5193. initWidget(escalator);
  5194. getElement().setTabIndex(0);
  5195. cellFocusHandler = new CellFocusHandler();
  5196. setStylePrimaryName(STYLE_NAME);
  5197. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  5198. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  5199. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  5200. header.setGrid(this);
  5201. HeaderRow defaultRow = header.appendRow();
  5202. header.setDefaultRow(defaultRow);
  5203. footer.setGrid(this);
  5204. editor.setGrid(this);
  5205. setSelectionMode(SelectionMode.SINGLE);
  5206. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  5207. escalator.addScrollHandler(new ScrollHandler() {
  5208. @Override
  5209. public void onScroll(ScrollEvent event) {
  5210. fireEvent(new ScrollEvent());
  5211. }
  5212. });
  5213. escalator.addRowVisibilityChangeHandler(
  5214. new RowVisibilityChangeHandler() {
  5215. @Override
  5216. public void onRowVisibilityChange(
  5217. RowVisibilityChangeEvent event) {
  5218. if (dataSource != null && dataSource.size() != 0) {
  5219. dataIsBeingFetched = true;
  5220. dataSource.ensureAvailability(
  5221. event.getFirstVisibleRow(),
  5222. event.getVisibleRowCount());
  5223. }
  5224. }
  5225. });
  5226. // Default action on SelectionEvents. Refresh the body so changed
  5227. // become visible.
  5228. addSelectionHandler(new SelectionHandler<T>() {
  5229. @Override
  5230. public void onSelect(SelectionEvent<T> event) {
  5231. refreshBody();
  5232. }
  5233. });
  5234. // Sink header events and key events
  5235. sinkEvents(getHeader().getConsumedEvents());
  5236. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  5237. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  5238. BrowserEvents.MOUSEDOWN, BrowserEvents.CLICK));
  5239. // Make ENTER and SHIFT+ENTER in the header perform sorting
  5240. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  5241. @Override
  5242. public void onKeyUp(GridKeyUpEvent event) {
  5243. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  5244. return;
  5245. }
  5246. if (getHeader().getRow(event.getFocusedCell().getRowIndex())
  5247. .isDefault()) {
  5248. // Only sort for enter on the default header
  5249. sorter.sort(event.getFocusedCell().getColumn(),
  5250. event.isShiftKeyDown());
  5251. }
  5252. }
  5253. });
  5254. addDataAvailableHandler(new DataAvailableHandler() {
  5255. @Override
  5256. public void onDataAvailable(DataAvailableEvent event) {
  5257. dataIsBeingFetched = false;
  5258. }
  5259. });
  5260. }
  5261. @Override
  5262. public boolean isEnabled() {
  5263. return enabled;
  5264. }
  5265. @Override
  5266. public void setEnabled(boolean enabled) {
  5267. if (enabled == this.enabled) {
  5268. return;
  5269. }
  5270. this.enabled = enabled;
  5271. getElement().setTabIndex(enabled ? 0 : -1);
  5272. // Editor save and cancel buttons need to be disabled.
  5273. boolean editorOpen = editor.getState() != State.INACTIVE;
  5274. if (editorOpen) {
  5275. editor.setGridEnabled(enabled);
  5276. }
  5277. sidebar.setEnabled(enabled);
  5278. getEscalator().setScrollLocked(Direction.VERTICAL,
  5279. !enabled || editorOpen);
  5280. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  5281. fireEvent(new GridEnabledEvent(enabled));
  5282. }
  5283. @Override
  5284. public void setStylePrimaryName(String style) {
  5285. super.setStylePrimaryName(style);
  5286. escalator.setStylePrimaryName(style);
  5287. editor.setStylePrimaryName(style);
  5288. sidebar.setStylePrimaryName(style + "-sidebar");
  5289. sidebar.addStyleName("v-contextmenu");
  5290. String rowStyle = getStylePrimaryName() + "-row";
  5291. rowHasDataStyleName = rowStyle + "-has-data";
  5292. rowSelectedStyleName = rowStyle + "-selected";
  5293. rowStripeStyleName = rowStyle + "-stripe";
  5294. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  5295. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  5296. if (isAttached()) {
  5297. refreshHeader();
  5298. refreshBody();
  5299. refreshFooter();
  5300. }
  5301. }
  5302. /**
  5303. * Creates the escalator updater used to update the header rows in this
  5304. * grid. The updater is invoked when header rows or columns are added or
  5305. * removed, or the content of existing header cells is changed.
  5306. *
  5307. * @return the new header updater instance
  5308. *
  5309. * @see GridHeader
  5310. * @see Grid#getHeader()
  5311. */
  5312. protected EscalatorUpdater createHeaderUpdater() {
  5313. return new StaticSectionUpdater(header, escalator.getHeader());
  5314. }
  5315. /**
  5316. * Creates the escalator updater used to update the body rows in this grid.
  5317. * The updater is invoked when body rows or columns are added or removed,
  5318. * the content of body cells is changed, or the body is scrolled to expose
  5319. * previously hidden content.
  5320. *
  5321. * @return the new body updater instance
  5322. */
  5323. protected EscalatorUpdater createBodyUpdater() {
  5324. return new BodyUpdater();
  5325. }
  5326. /**
  5327. * Creates the escalator updater used to update the footer rows in this
  5328. * grid. The updater is invoked when header rows or columns are added or
  5329. * removed, or the content of existing header cells is changed.
  5330. *
  5331. * @return the new footer updater instance
  5332. *
  5333. * @see GridFooter
  5334. * @see #getFooter()
  5335. */
  5336. protected EscalatorUpdater createFooterUpdater() {
  5337. return new StaticSectionUpdater(footer, escalator.getFooter());
  5338. }
  5339. /**
  5340. * Refreshes header or footer rows on demand
  5341. *
  5342. * @param rows
  5343. * The row container
  5344. * @param firstRowIsVisible
  5345. * is the first row visible
  5346. * @param isHeader
  5347. * <code>true</code> if we refreshing the header, else assumed
  5348. * the footer
  5349. */
  5350. private void refreshRowContainer(RowContainer rows,
  5351. StaticSection<?> section) {
  5352. // Add or Remove rows on demand
  5353. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  5354. if (rowDiff > 0) {
  5355. rows.insertRows(0, rowDiff);
  5356. } else if (rowDiff < 0) {
  5357. rows.removeRows(0, -rowDiff);
  5358. }
  5359. // Refresh all the rows
  5360. if (rows.getRowCount() > 0) {
  5361. rows.refreshRows(0, rows.getRowCount());
  5362. }
  5363. }
  5364. /**
  5365. * Focus a body cell by row and column index.
  5366. *
  5367. * @param rowIndex
  5368. * index of row to focus
  5369. * @param columnIndex
  5370. * index of cell to focus
  5371. */
  5372. void focusCell(int rowIndex, int columnIndex) {
  5373. final Range rowRange = Range.between(0, dataSource.size());
  5374. final Range columnRange = Range.between(0, getVisibleColumns().size());
  5375. assert rowRange.contains(
  5376. rowIndex) : "Illegal row index. Should be in range " + rowRange;
  5377. assert columnRange.contains(
  5378. columnIndex) : "Illegal column index. Should be in range "
  5379. + columnRange;
  5380. if (rowRange.contains(rowIndex) && columnRange.contains(columnIndex)) {
  5381. cellFocusHandler.setCellFocus(rowIndex, columnIndex,
  5382. escalator.getBody());
  5383. WidgetUtil.focus(getElement());
  5384. }
  5385. }
  5386. /**
  5387. * Refreshes all header rows
  5388. */
  5389. void refreshHeader() {
  5390. refreshRowContainer(escalator.getHeader(), header);
  5391. }
  5392. /**
  5393. * Refreshes all body rows
  5394. */
  5395. private void refreshBody() {
  5396. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  5397. }
  5398. /**
  5399. * Refreshes all footer rows
  5400. */
  5401. void refreshFooter() {
  5402. refreshRowContainer(escalator.getFooter(), footer);
  5403. }
  5404. /**
  5405. * Adds columns as the last columns in the grid.
  5406. *
  5407. * @param columns
  5408. * the columns to add
  5409. */
  5410. public void addColumns(Column<?, T>... columns) {
  5411. int count = getColumnCount();
  5412. for (Column<?, T> column : columns) {
  5413. addColumn(column, count++);
  5414. }
  5415. }
  5416. /**
  5417. * Adds a column as the last column in the grid.
  5418. *
  5419. * @param column
  5420. * the column to add
  5421. * @return given column
  5422. */
  5423. public <C extends Column<?, T>> C addColumn(C column) {
  5424. addColumn(column, getColumnCount());
  5425. return column;
  5426. }
  5427. /**
  5428. * Inserts a column into a specific position in the grid.
  5429. *
  5430. * @param index
  5431. * the index where the column should be inserted into
  5432. * @param column
  5433. * the column to add
  5434. * @return given column
  5435. *
  5436. * @throws IllegalStateException
  5437. * if Grid's current selection model renders a selection column,
  5438. * and {@code index} is 0.
  5439. */
  5440. public <C extends Column<?, T>> C addColumn(C column, int index) {
  5441. if (column == selectionColumn) {
  5442. throw new IllegalArgumentException(
  5443. "The selection column many " + "not be added manually");
  5444. } else if (selectionColumn != null && index == 0) {
  5445. throw new IllegalStateException("A column cannot be inserted "
  5446. + "before the selection column");
  5447. }
  5448. addColumnSkipSelectionColumnCheck(column, index);
  5449. return column;
  5450. }
  5451. private void addColumnSkipSelectionColumnCheck(Column<?, T> column,
  5452. int index) {
  5453. // Register column with grid
  5454. columns.add(index, column);
  5455. header.addColumn(column);
  5456. footer.addColumn(column);
  5457. // Register this grid instance with the column
  5458. ((Column<?, T>) column).setGrid(this);
  5459. // Grid knows about hidden columns, Escalator only knows about what is
  5460. // visible so column indexes do not match
  5461. if (!column.isHidden()) {
  5462. int escalatorIndex = index;
  5463. for (int existingColumn = 0; existingColumn < index; existingColumn++) {
  5464. if (getColumn(existingColumn).isHidden()) {
  5465. escalatorIndex--;
  5466. }
  5467. }
  5468. escalator.getColumnConfiguration().insertColumns(escalatorIndex, 1);
  5469. }
  5470. // Reapply column width
  5471. column.reapplyWidth();
  5472. // Sink all renderer events
  5473. Set<String> events = new HashSet<String>();
  5474. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  5475. if (column.isHidable()) {
  5476. columnHider.updateColumnHidable(column);
  5477. }
  5478. sinkEvents(events);
  5479. }
  5480. private void sinkEvents(Collection<String> events) {
  5481. assert events != null;
  5482. int eventsToSink = 0;
  5483. for (String typeName : events) {
  5484. int typeInt = Event.getTypeInt(typeName);
  5485. if (typeInt < 0) {
  5486. // Type not recognized by typeInt
  5487. sinkBitlessEvent(typeName);
  5488. } else {
  5489. eventsToSink |= typeInt;
  5490. }
  5491. }
  5492. if (eventsToSink > 0) {
  5493. sinkEvents(eventsToSink);
  5494. }
  5495. }
  5496. private Renderer<?> findRenderer(FlyweightCell cell) {
  5497. Column<?, T> column = getVisibleColumn(cell.getColumn());
  5498. assert column != null : "Could not find column at index:"
  5499. + cell.getColumn();
  5500. return column.getRenderer();
  5501. }
  5502. /**
  5503. * Removes a column from the grid.
  5504. *
  5505. * @param column
  5506. * the column to remove
  5507. */
  5508. public void removeColumn(Column<?, T> column) {
  5509. if (column != null && column.equals(selectionColumn)) {
  5510. throw new IllegalArgumentException(
  5511. "The selection column may not be removed manually.");
  5512. }
  5513. removeColumnSkipSelectionColumnCheck(column);
  5514. }
  5515. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  5516. int columnIndex = columns.indexOf(column);
  5517. // Remove from column configuration
  5518. escalator.getColumnConfiguration()
  5519. .removeColumns(getVisibleColumns().indexOf(column), 1);
  5520. updateFrozenColumns();
  5521. header.removeColumn(column);
  5522. footer.removeColumn(column);
  5523. // de-register column with grid
  5524. ((Column<?, T>) column).setGrid(null);
  5525. columns.remove(columnIndex);
  5526. if (column.isHidable()) {
  5527. columnHider.removeColumnHidingToggle(column);
  5528. }
  5529. }
  5530. /**
  5531. * Returns the amount of columns in the grid.
  5532. * <p>
  5533. * <em>NOTE:</em> this includes the hidden columns in the count.
  5534. *
  5535. * @return The number of columns in the grid
  5536. */
  5537. public int getColumnCount() {
  5538. return columns.size();
  5539. }
  5540. /**
  5541. * Returns a list columns in the grid, including hidden columns.
  5542. * <p>
  5543. * For currently visible columns, use {@link #getVisibleColumns()}.
  5544. *
  5545. * @return A unmodifiable list of the columns in the grid
  5546. */
  5547. public List<Column<?, T>> getColumns() {
  5548. return Collections
  5549. .unmodifiableList(new ArrayList<Column<?, T>>(columns));
  5550. }
  5551. /**
  5552. * Returns a list of the currently visible columns in the grid.
  5553. * <p>
  5554. * No {@link Column#isHidden() hidden} columns included.
  5555. *
  5556. * @since 7.5.0
  5557. * @return A unmodifiable list of the currently visible columns in the grid
  5558. */
  5559. public List<Column<?, T>> getVisibleColumns() {
  5560. ArrayList<Column<?, T>> visible = new ArrayList<Column<?, T>>();
  5561. for (Column<?, T> c : columns) {
  5562. if (!c.isHidden()) {
  5563. visible.add(c);
  5564. }
  5565. }
  5566. return Collections.unmodifiableList(visible);
  5567. }
  5568. /**
  5569. * Returns a column by its index in the grid.
  5570. * <p>
  5571. * <em>NOTE:</em> The indexing includes hidden columns.
  5572. *
  5573. * @param index
  5574. * the index of the column
  5575. * @return The column in the given index
  5576. * @throws IllegalArgumentException
  5577. * if the column index does not exist in the grid
  5578. */
  5579. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  5580. if (index < 0 || index >= columns.size()) {
  5581. throw new IllegalStateException("Column not found.");
  5582. }
  5583. return columns.get(index);
  5584. }
  5585. private Column<?, T> getVisibleColumn(int index)
  5586. throws IllegalArgumentException {
  5587. List<Column<?, T>> visibleColumns = getVisibleColumns();
  5588. if (index < 0 || index >= visibleColumns.size()) {
  5589. throw new IllegalStateException("Column not found.");
  5590. }
  5591. return visibleColumns.get(index);
  5592. }
  5593. /**
  5594. * Returns the header section of this grid. The default header contains a
  5595. * single row displaying the column captions.
  5596. *
  5597. * @return the header
  5598. */
  5599. protected Header getHeader() {
  5600. return header;
  5601. }
  5602. /**
  5603. * Gets the header row at given index.
  5604. *
  5605. * @param rowIndex
  5606. * 0 based index for row. Counted from top to bottom
  5607. * @return header row at given index
  5608. * @throws IllegalArgumentException
  5609. * if no row exists at given index
  5610. */
  5611. public HeaderRow getHeaderRow(int rowIndex) {
  5612. return header.getRow(rowIndex);
  5613. }
  5614. /**
  5615. * Inserts a new row at the given position to the header section. Shifts the
  5616. * row currently at that position and any subsequent rows down (adds one to
  5617. * their indices).
  5618. *
  5619. * @param index
  5620. * the position at which to insert the row
  5621. * @return the new row
  5622. *
  5623. * @throws IllegalArgumentException
  5624. * if the index is less than 0 or greater than row count
  5625. * @see #appendHeaderRow()
  5626. * @see #prependHeaderRow()
  5627. * @see #removeHeaderRow(HeaderRow)
  5628. * @see #removeHeaderRow(int)
  5629. */
  5630. public HeaderRow addHeaderRowAt(int index) {
  5631. return header.addRowAt(index);
  5632. }
  5633. /**
  5634. * Adds a new row at the bottom of the header section.
  5635. *
  5636. * @return the new row
  5637. * @see #prependHeaderRow()
  5638. * @see #addHeaderRowAt(int)
  5639. * @see #removeHeaderRow(HeaderRow)
  5640. * @see #removeHeaderRow(int)
  5641. */
  5642. public HeaderRow appendHeaderRow() {
  5643. return header.appendRow();
  5644. }
  5645. /**
  5646. * Returns the current default row of the header section. The default row is
  5647. * a special header row providing a user interface for sorting columns.
  5648. * Setting a header caption for column updates cells in the default header.
  5649. *
  5650. * @return the default row or null if no default row set
  5651. */
  5652. public HeaderRow getDefaultHeaderRow() {
  5653. return header.getDefaultRow();
  5654. }
  5655. /**
  5656. * Gets the row count for the header section.
  5657. *
  5658. * @return row count
  5659. */
  5660. public int getHeaderRowCount() {
  5661. return header.getRowCount();
  5662. }
  5663. /**
  5664. * Adds a new row at the top of the header section.
  5665. *
  5666. * @return the new row
  5667. * @see #appendHeaderRow()
  5668. * @see #addHeaderRowAt(int)
  5669. * @see #removeHeaderRow(HeaderRow)
  5670. * @see #removeHeaderRow(int)
  5671. */
  5672. public HeaderRow prependHeaderRow() {
  5673. return header.prependRow();
  5674. }
  5675. /**
  5676. * Removes the given row from the header section.
  5677. *
  5678. * @param row
  5679. * the row to be removed
  5680. *
  5681. * @throws IllegalArgumentException
  5682. * if the row does not exist in this section
  5683. * @see #removeHeaderRow(int)
  5684. * @see #addHeaderRowAt(int)
  5685. * @see #appendHeaderRow()
  5686. * @see #prependHeaderRow()
  5687. */
  5688. public void removeHeaderRow(HeaderRow row) {
  5689. header.removeRow(row);
  5690. }
  5691. /**
  5692. * Removes the row at the given position from the header section.
  5693. *
  5694. * @param index
  5695. * the position of the row
  5696. *
  5697. * @throws IllegalArgumentException
  5698. * if no row exists at given index
  5699. * @see #removeHeaderRow(HeaderRow)
  5700. * @see #addHeaderRowAt(int)
  5701. * @see #appendHeaderRow()
  5702. * @see #prependHeaderRow()
  5703. */
  5704. public void removeHeaderRow(int rowIndex) {
  5705. header.removeRow(rowIndex);
  5706. }
  5707. /**
  5708. * Sets the default row of the header. The default row is a special header
  5709. * row providing a user interface for sorting columns.
  5710. * <p>
  5711. * Note: Setting the default header row will reset all cell contents to
  5712. * Column defaults.
  5713. *
  5714. * @param row
  5715. * the new default row, or null for no default row
  5716. *
  5717. * @throws IllegalArgumentException
  5718. * header does not contain the row
  5719. */
  5720. public void setDefaultHeaderRow(HeaderRow row) {
  5721. header.setDefaultRow(row);
  5722. }
  5723. /**
  5724. * Sets the visibility of the header section.
  5725. *
  5726. * @param visible
  5727. * true to show header section, false to hide
  5728. */
  5729. public void setHeaderVisible(boolean visible) {
  5730. header.setVisible(visible);
  5731. }
  5732. /**
  5733. * Returns the visibility of the header section.
  5734. *
  5735. * @return true if visible, false otherwise.
  5736. */
  5737. public boolean isHeaderVisible() {
  5738. return header.isVisible();
  5739. }
  5740. /* Grid Footers */
  5741. /**
  5742. * Returns the footer section of this grid. The default footer is empty.
  5743. *
  5744. * @return the footer
  5745. */
  5746. protected Footer getFooter() {
  5747. return footer;
  5748. }
  5749. /**
  5750. * Gets the footer row at given index.
  5751. *
  5752. * @param rowIndex
  5753. * 0 based index for row. Counted from top to bottom
  5754. * @return footer row at given index
  5755. * @throws IllegalArgumentException
  5756. * if no row exists at given index
  5757. */
  5758. public FooterRow getFooterRow(int rowIndex) {
  5759. return footer.getRow(rowIndex);
  5760. }
  5761. /**
  5762. * Inserts a new row at the given position to the footer section. Shifts the
  5763. * row currently at that position and any subsequent rows down (adds one to
  5764. * their indices).
  5765. *
  5766. * @param index
  5767. * the position at which to insert the row
  5768. * @return the new row
  5769. *
  5770. * @throws IllegalArgumentException
  5771. * if the index is less than 0 or greater than row count
  5772. * @see #appendFooterRow()
  5773. * @see #prependFooterRow()
  5774. * @see #removeFooterRow(FooterRow)
  5775. * @see #removeFooterRow(int)
  5776. */
  5777. public FooterRow addFooterRowAt(int index) {
  5778. return footer.addRowAt(index);
  5779. }
  5780. /**
  5781. * Adds a new row at the bottom of the footer section.
  5782. *
  5783. * @return the new row
  5784. * @see #prependFooterRow()
  5785. * @see #addFooterRowAt(int)
  5786. * @see #removeFooterRow(FooterRow)
  5787. * @see #removeFooterRow(int)
  5788. */
  5789. public FooterRow appendFooterRow() {
  5790. return footer.appendRow();
  5791. }
  5792. /**
  5793. * Gets the row count for the footer.
  5794. *
  5795. * @return row count
  5796. */
  5797. public int getFooterRowCount() {
  5798. return footer.getRowCount();
  5799. }
  5800. /**
  5801. * Adds a new row at the top of the footer section.
  5802. *
  5803. * @return the new row
  5804. * @see #appendFooterRow()
  5805. * @see #addFooterRowAt(int)
  5806. * @see #removeFooterRow(FooterRow)
  5807. * @see #removeFooterRow(int)
  5808. */
  5809. public FooterRow prependFooterRow() {
  5810. return footer.prependRow();
  5811. }
  5812. /**
  5813. * Removes the given row from the footer section.
  5814. *
  5815. * @param row
  5816. * the row to be removed
  5817. *
  5818. * @throws IllegalArgumentException
  5819. * if the row does not exist in this section
  5820. * @see #removeFooterRow(int)
  5821. * @see #addFooterRowAt(int)
  5822. * @see #appendFooterRow()
  5823. * @see #prependFooterRow()
  5824. */
  5825. public void removeFooterRow(FooterRow row) {
  5826. footer.removeRow(row);
  5827. }
  5828. /**
  5829. * Removes the row at the given position from the footer section.
  5830. *
  5831. * @param index
  5832. * the position of the row
  5833. *
  5834. * @throws IllegalArgumentException
  5835. * if no row exists at given index
  5836. * @see #removeFooterRow(FooterRow)
  5837. * @see #addFooterRowAt(int)
  5838. * @see #appendFooterRow()
  5839. * @see #prependFooterRow()
  5840. */
  5841. public void removeFooterRow(int rowIndex) {
  5842. footer.removeRow(rowIndex);
  5843. }
  5844. /**
  5845. * Sets the visibility of the footer section.
  5846. *
  5847. * @param visible
  5848. * true to show footer section, false to hide
  5849. */
  5850. public void setFooterVisible(boolean visible) {
  5851. footer.setVisible(visible);
  5852. }
  5853. /**
  5854. * Returns the visibility of the footer section.
  5855. *
  5856. * @return true if visible, false otherwise.
  5857. */
  5858. public boolean isFooterVisible() {
  5859. return footer.isVisible();
  5860. }
  5861. public Editor<T> getEditor() {
  5862. return editor;
  5863. }
  5864. protected Escalator getEscalator() {
  5865. return escalator;
  5866. }
  5867. /**
  5868. * {@inheritDoc}
  5869. * <p>
  5870. * <em>Note:</em> This method will change the widget's size in the browser
  5871. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  5872. *
  5873. * @see #setHeightMode(HeightMode)
  5874. */
  5875. @Override
  5876. public void setHeight(String height) {
  5877. escalator.setHeight(height);
  5878. }
  5879. @Override
  5880. public void setWidth(String width) {
  5881. escalator.setWidth(width);
  5882. }
  5883. /**
  5884. * Sets the data source used by this grid.
  5885. *
  5886. * @param dataSource
  5887. * the data source to use, not null
  5888. * @throws IllegalArgumentException
  5889. * if <code>dataSource</code> is <code>null</code>
  5890. */
  5891. public void setDataSource(final DataSource<T> dataSource)
  5892. throws IllegalArgumentException {
  5893. if (dataSource == null) {
  5894. throw new IllegalArgumentException("dataSource can't be null.");
  5895. }
  5896. selectionModel.reset();
  5897. if (this.dataSource != null) {
  5898. this.dataSource.setDataChangeHandler(null);
  5899. }
  5900. this.dataSource = dataSource;
  5901. dataSource.setDataChangeHandler(new DataChangeHandler() {
  5902. @Override
  5903. public void dataUpdated(int firstIndex, int numberOfItems) {
  5904. escalator.getBody().refreshRows(firstIndex, numberOfItems);
  5905. }
  5906. @Override
  5907. public void dataRemoved(int firstIndex, int numberOfItems) {
  5908. escalator.getBody().removeRows(firstIndex, numberOfItems);
  5909. Range removed = Range.withLength(firstIndex, numberOfItems);
  5910. cellFocusHandler.rowsRemovedFromBody(removed);
  5911. }
  5912. @Override
  5913. public void dataAdded(int firstIndex, int numberOfItems) {
  5914. escalator.getBody().insertRows(firstIndex, numberOfItems);
  5915. Range added = Range.withLength(firstIndex, numberOfItems);
  5916. cellFocusHandler.rowsAddedToBody(added);
  5917. }
  5918. @Override
  5919. public void dataAvailable(int firstIndex, int numberOfItems) {
  5920. currentDataAvailable = Range.withLength(firstIndex,
  5921. numberOfItems);
  5922. fireEvent(new DataAvailableEvent(currentDataAvailable));
  5923. }
  5924. @Override
  5925. public void resetDataAndSize(int newSize) {
  5926. RowContainer body = escalator.getBody();
  5927. int oldSize = body.getRowCount();
  5928. // Hide all details.
  5929. Set<Integer> oldDetails = new HashSet<Integer>(visibleDetails);
  5930. for (int i : oldDetails) {
  5931. setDetailsVisible(i, false);
  5932. }
  5933. if (newSize > oldSize) {
  5934. body.insertRows(oldSize, newSize - oldSize);
  5935. cellFocusHandler.rowsAddedToBody(
  5936. Range.withLength(oldSize, newSize - oldSize));
  5937. } else if (newSize < oldSize) {
  5938. body.removeRows(newSize, oldSize - newSize);
  5939. cellFocusHandler.rowsRemovedFromBody(
  5940. Range.withLength(newSize, oldSize - newSize));
  5941. }
  5942. if (newSize > 0) {
  5943. dataIsBeingFetched = true;
  5944. Range visibleRowRange = escalator.getVisibleRowRange();
  5945. dataSource.ensureAvailability(visibleRowRange.getStart(),
  5946. visibleRowRange.length());
  5947. } else {
  5948. // We won't expect any data more data updates, so just make
  5949. // the bookkeeping happy
  5950. dataAvailable(0, 0);
  5951. }
  5952. assert body.getRowCount() == newSize;
  5953. }
  5954. });
  5955. int previousRowCount = escalator.getBody().getRowCount();
  5956. if (previousRowCount != 0) {
  5957. escalator.getBody().removeRows(0, previousRowCount);
  5958. }
  5959. setEscalatorSizeFromDataSource();
  5960. }
  5961. private void setEscalatorSizeFromDataSource() {
  5962. assert escalator.getBody().getRowCount() == 0;
  5963. int size = dataSource.size();
  5964. if (size == -1 && isAttached()) {
  5965. // Exact size is not yet known, start with some reasonable guess
  5966. // just to get an initial backend request going
  5967. size = getEscalator().getMaxVisibleRowCount();
  5968. }
  5969. if (size > 0) {
  5970. escalator.getBody().insertRows(0, size);
  5971. }
  5972. }
  5973. /**
  5974. * Gets the {@Link DataSource} for this Grid.
  5975. *
  5976. * @return the data source used by this grid
  5977. */
  5978. public DataSource<T> getDataSource() {
  5979. return dataSource;
  5980. }
  5981. /**
  5982. * Sets the number of frozen columns in this grid. Setting the count to 0
  5983. * means that no data columns will be frozen, but the built-in selection
  5984. * checkbox column will still be frozen if it's in use. Setting the count to
  5985. * -1 will also disable the selection column.
  5986. * <p>
  5987. * The default value is 0.
  5988. *
  5989. * @param numberOfColumns
  5990. * the number of columns that should be frozen
  5991. *
  5992. * @throws IllegalArgumentException
  5993. * if the column count is < -1 or > the number of visible
  5994. * columns
  5995. */
  5996. public void setFrozenColumnCount(int numberOfColumns) {
  5997. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  5998. throw new IllegalArgumentException(
  5999. "count must be between -1 and the current number of columns ("
  6000. + getColumnCount() + ")");
  6001. }
  6002. frozenColumnCount = numberOfColumns;
  6003. updateFrozenColumns();
  6004. }
  6005. private void updateFrozenColumns() {
  6006. escalator.getColumnConfiguration()
  6007. .setFrozenColumnCount(getVisibleFrozenColumnCount());
  6008. }
  6009. private int getVisibleFrozenColumnCount() {
  6010. int numberOfColumns = getFrozenColumnCount();
  6011. // for the escalator the hidden columns are not in the frozen column
  6012. // count, but for grid they are. thus need to convert the index
  6013. for (int i = 0; i < frozenColumnCount; i++) {
  6014. if (getColumn(i).isHidden()) {
  6015. numberOfColumns--;
  6016. }
  6017. }
  6018. if (numberOfColumns == -1) {
  6019. numberOfColumns = 0;
  6020. } else if (selectionColumn != null) {
  6021. numberOfColumns++;
  6022. }
  6023. return numberOfColumns;
  6024. }
  6025. /**
  6026. * Gets the number of frozen columns in this grid. 0 means that no data
  6027. * columns will be frozen, but the built-in selection checkbox column will
  6028. * still be frozen if it's in use. -1 means that not even the selection
  6029. * column is frozen.
  6030. * <p>
  6031. * <em>NOTE:</em> This includes {@link Column#isHidden() hidden columns} in
  6032. * the count.
  6033. *
  6034. * @return the number of frozen columns
  6035. */
  6036. public int getFrozenColumnCount() {
  6037. return frozenColumnCount;
  6038. }
  6039. public HandlerRegistration addRowVisibilityChangeHandler(
  6040. RowVisibilityChangeHandler handler) {
  6041. /*
  6042. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  6043. * concept is too abstract. e.g. the event needs to be re-sent when the
  6044. * widget is resized.
  6045. */
  6046. return escalator.addRowVisibilityChangeHandler(handler);
  6047. }
  6048. /**
  6049. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  6050. * <p>
  6051. * If the details for that row are visible, those will be taken into account
  6052. * as well.
  6053. *
  6054. * @param rowIndex
  6055. * zero-based index of the row to scroll to.
  6056. * @throws IllegalArgumentException
  6057. * if rowIndex is below zero, or above the maximum value
  6058. * supported by the data source.
  6059. */
  6060. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  6061. scrollToRow(rowIndex, ScrollDestination.ANY,
  6062. GridConstants.DEFAULT_PADDING);
  6063. }
  6064. /**
  6065. * Scrolls to a certain row, using user-specified scroll destination.
  6066. * <p>
  6067. * If the details for that row are visible, those will be taken into account
  6068. * as well.
  6069. *
  6070. * @param rowIndex
  6071. * zero-based index of the row to scroll to.
  6072. * @param destination
  6073. * desired destination placement of scrolled-to-row. See
  6074. * {@link ScrollDestination} for more information.
  6075. * @throws IllegalArgumentException
  6076. * if rowIndex is below zero, or above the maximum value
  6077. * supported by the data source.
  6078. */
  6079. public void scrollToRow(int rowIndex, ScrollDestination destination)
  6080. throws IllegalArgumentException {
  6081. scrollToRow(rowIndex, destination,
  6082. destination == ScrollDestination.MIDDLE ? 0
  6083. : GridConstants.DEFAULT_PADDING);
  6084. }
  6085. /**
  6086. * Scrolls to a certain row using only user-specified parameters.
  6087. * <p>
  6088. * If the details for that row are visible, those will be taken into account
  6089. * as well.
  6090. *
  6091. * @param rowIndex
  6092. * zero-based index of the row to scroll to.
  6093. * @param destination
  6094. * desired destination placement of scrolled-to-row. See
  6095. * {@link ScrollDestination} for more information.
  6096. * @param paddingPx
  6097. * number of pixels to overscroll. Behavior depends on
  6098. * destination.
  6099. * @throws IllegalArgumentException
  6100. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6101. * and padding is nonzero, because having a padding on a
  6102. * centered row is undefined behavior, or if rowIndex is below
  6103. * zero or above the row count of the data source.
  6104. */
  6105. private void scrollToRow(int rowIndex, ScrollDestination destination,
  6106. int paddingPx) throws IllegalArgumentException {
  6107. int maxsize = escalator.getBody().getRowCount() - 1;
  6108. if (rowIndex < 0) {
  6109. throw new IllegalArgumentException(
  6110. "Row index (" + rowIndex + ") is below zero!");
  6111. }
  6112. if (rowIndex > maxsize) {
  6113. throw new IllegalArgumentException("Row index (" + rowIndex
  6114. + ") is above maximum (" + maxsize + ")!");
  6115. }
  6116. escalator.scrollToRowAndSpacer(rowIndex, destination, paddingPx);
  6117. }
  6118. /**
  6119. * Scrolls to the beginning of the very first row.
  6120. */
  6121. public void scrollToStart() {
  6122. scrollToRow(0, ScrollDestination.START);
  6123. }
  6124. /**
  6125. * Scrolls to the end of the very last row.
  6126. */
  6127. public void scrollToEnd() {
  6128. scrollToRow(escalator.getBody().getRowCount() - 1,
  6129. ScrollDestination.END);
  6130. }
  6131. /**
  6132. * Sets the vertical scroll offset.
  6133. *
  6134. * @param px
  6135. * the number of pixels this grid should be scrolled down
  6136. */
  6137. public void setScrollTop(double px) {
  6138. escalator.setScrollTop(px);
  6139. }
  6140. /**
  6141. * Gets the vertical scroll offset
  6142. *
  6143. * @return the number of pixels this grid is scrolled down
  6144. */
  6145. public double getScrollTop() {
  6146. return escalator.getScrollTop();
  6147. }
  6148. /**
  6149. * Sets the horizontal scroll offset
  6150. *
  6151. * @since 7.5.0
  6152. * @param px
  6153. * the number of pixels this grid should be scrolled right
  6154. */
  6155. public void setScrollLeft(double px) {
  6156. escalator.setScrollLeft(px);
  6157. }
  6158. /**
  6159. * Gets the horizontal scroll offset
  6160. *
  6161. * @return the number of pixels this grid is scrolled to the right
  6162. */
  6163. public double getScrollLeft() {
  6164. return escalator.getScrollLeft();
  6165. }
  6166. /**
  6167. * Returns the height of the scrollable area in pixels.
  6168. *
  6169. * @since 7.5.0
  6170. * @return the height of the scrollable area in pixels
  6171. */
  6172. public double getScrollHeight() {
  6173. return escalator.getScrollHeight();
  6174. }
  6175. /**
  6176. * Returns the width of the scrollable area in pixels.
  6177. *
  6178. * @since 7.5.0
  6179. * @return the width of the scrollable area in pixels.
  6180. */
  6181. public double getScrollWidth() {
  6182. return escalator.getScrollWidth();
  6183. }
  6184. private static final Logger getLogger() {
  6185. return Logger.getLogger(Grid.class.getName());
  6186. }
  6187. /**
  6188. * Sets the number of rows that should be visible in Grid's body, while
  6189. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6190. * <p>
  6191. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  6192. * remembered, and applied once the mode is applied.
  6193. *
  6194. * @param rows
  6195. * The height in terms of number of rows displayed in Grid's
  6196. * body. If Grid doesn't contain enough rows, white space is
  6197. * displayed instead.
  6198. * @throws IllegalArgumentException
  6199. * if {@code rows} is zero or less
  6200. * @throws IllegalArgumentException
  6201. * if {@code rows} is {@link Double#isInifinite(double)
  6202. * infinite}
  6203. * @throws IllegalArgumentException
  6204. * if {@code rows} is {@link Double#isNaN(double) NaN}
  6205. *
  6206. * @see #setHeightMode(HeightMode)
  6207. */
  6208. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6209. escalator.setHeightByRows(rows);
  6210. }
  6211. /**
  6212. * Gets the amount of rows in Grid's body that are shown, while
  6213. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6214. * <p>
  6215. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  6216. *
  6217. * @return the amount of rows that should be shown in Grid's body, while in
  6218. * {@link HeightMode#ROW}.
  6219. * @see #setHeightByRows(double)
  6220. */
  6221. public double getHeightByRows() {
  6222. return escalator.getHeightByRows();
  6223. }
  6224. /**
  6225. * Defines the mode in which the Grid widget's height is calculated.
  6226. * <p>
  6227. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  6228. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  6229. * <p>
  6230. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  6231. * will display as many rows as {@link #getHeightByRows()} defines.
  6232. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  6233. * will resize itself to still display the required amount of rows in its
  6234. * body. It also takes the horizontal scrollbar into account.
  6235. *
  6236. * @param heightMode
  6237. * the mode in to which Grid should be set
  6238. */
  6239. public void setHeightMode(HeightMode heightMode) {
  6240. /*
  6241. * This method is a workaround for the fact that Vaadin re-applies
  6242. * widget dimensions (height/width) on each state change event. The
  6243. * original design was to have setHeight an setHeightByRow be equals,
  6244. * and whichever was called the latest was considered in effect.
  6245. *
  6246. * But, because of Vaadin always calling setHeight on the widget, this
  6247. * approach doesn't work.
  6248. */
  6249. escalator.setHeightMode(heightMode);
  6250. }
  6251. /**
  6252. * Returns the current {@link HeightMode} the Grid is in.
  6253. * <p>
  6254. * Defaults to {@link HeightMode#CSS}.
  6255. *
  6256. * @return the current HeightMode
  6257. */
  6258. public HeightMode getHeightMode() {
  6259. return escalator.getHeightMode();
  6260. }
  6261. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  6262. Set<String> events = new HashSet<String>();
  6263. if (renderer instanceof ComplexRenderer) {
  6264. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  6265. .getConsumedEvents();
  6266. if (consumedEvents != null) {
  6267. events.addAll(consumedEvents);
  6268. }
  6269. }
  6270. return events;
  6271. }
  6272. @Override
  6273. public void onBrowserEvent(Event event) {
  6274. if (!isEnabled()) {
  6275. return;
  6276. }
  6277. String eventType = event.getType();
  6278. if (eventType.equals(BrowserEvents.FOCUS)
  6279. || eventType.equals(BrowserEvents.BLUR)) {
  6280. super.onBrowserEvent(event);
  6281. return;
  6282. }
  6283. EventTarget target = event.getEventTarget();
  6284. if (!Element.is(target) || isOrContainsInSpacer(Element.as(target))) {
  6285. return;
  6286. }
  6287. Element e = Element.as(target);
  6288. RowContainer container = escalator.findRowContainer(e);
  6289. Cell cell;
  6290. if (container == null) {
  6291. if (eventType.equals(BrowserEvents.KEYDOWN)
  6292. || eventType.equals(BrowserEvents.KEYUP)
  6293. || eventType.equals(BrowserEvents.KEYPRESS)) {
  6294. cell = cellFocusHandler.getFocusedCell();
  6295. container = cellFocusHandler.containerWithFocus;
  6296. } else {
  6297. // Click might be in an editor cell, should still map.
  6298. if (editor.editorOverlay != null
  6299. && editor.editorOverlay.isOrHasChild(e)) {
  6300. container = escalator.getBody();
  6301. int rowIndex = editor.getRow();
  6302. int colIndex = editor.getElementColumn(e);
  6303. if (colIndex < 0) {
  6304. // Click in editor, but not for any column.
  6305. return;
  6306. }
  6307. TableCellElement cellElement = container
  6308. .getRowElement(rowIndex).getCells()
  6309. .getItem(colIndex);
  6310. cell = new Cell(rowIndex, colIndex, cellElement);
  6311. } else {
  6312. if (escalator.getElement().isOrHasChild(e)) {
  6313. eventCell.set(new Cell(-1, -1, null), Section.BODY);
  6314. // Fire native events.
  6315. super.onBrowserEvent(event);
  6316. }
  6317. return;
  6318. }
  6319. }
  6320. } else {
  6321. cell = container.getCell(e);
  6322. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  6323. cellOnPrevMouseDown = cell;
  6324. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  6325. /*
  6326. * Chrome has an interesting idea on click targets (see
  6327. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  6328. * the mousedown target as the click target.
  6329. */
  6330. cell = cellOnPrevMouseDown;
  6331. }
  6332. }
  6333. assert cell != null : "received " + eventType
  6334. + "-event with a null cell target";
  6335. eventCell.set(cell, getSectionFromContainer(container));
  6336. // Editor can steal focus from Grid and is still handled
  6337. if (isEditorEnabled() && handleEditorEvent(event, container)) {
  6338. return;
  6339. }
  6340. // Fire GridKeyEvents and GridClickEvents. Pass the event to escalator.
  6341. super.onBrowserEvent(event);
  6342. if (!isElementInChildWidget(e)) {
  6343. if (handleHeaderCellDragStartEvent(event, container)) {
  6344. return;
  6345. }
  6346. // Sorting through header Click / KeyUp
  6347. if (handleHeaderDefaultRowEvent(event, container)) {
  6348. return;
  6349. }
  6350. if (handleRendererEvent(event, container)) {
  6351. return;
  6352. }
  6353. if (handleCellFocusEvent(event, container)) {
  6354. return;
  6355. }
  6356. }
  6357. }
  6358. private Section getSectionFromContainer(RowContainer container) {
  6359. assert container != null : "RowContainer should not be null";
  6360. if (container == escalator.getBody()) {
  6361. return Section.BODY;
  6362. } else if (container == escalator.getFooter()) {
  6363. return Section.FOOTER;
  6364. } else if (container == escalator.getHeader()) {
  6365. return Section.HEADER;
  6366. }
  6367. assert false : "RowContainer was not header, footer or body.";
  6368. return null;
  6369. }
  6370. private boolean isOrContainsInSpacer(Node node) {
  6371. Node n = node;
  6372. while (n != null && n != getElement()) {
  6373. boolean isElement = Element.is(n);
  6374. if (isElement) {
  6375. String className = Element.as(n).getClassName();
  6376. if (className.contains(getStylePrimaryName() + "-spacer")) {
  6377. return true;
  6378. }
  6379. }
  6380. n = n.getParentNode();
  6381. }
  6382. return false;
  6383. }
  6384. private boolean isElementInChildWidget(Element e) {
  6385. Widget w = WidgetUtil.findWidget(e, null);
  6386. if (w == this) {
  6387. return false;
  6388. }
  6389. /*
  6390. * If e is directly inside this grid, but the grid is wrapped in a
  6391. * Composite, findWidget is not going to find this, only the wrapper.
  6392. * Thus we need to check its parents to see if we encounter this; if we
  6393. * don't, the found widget is actually a parent of this, so we should
  6394. * return false.
  6395. */
  6396. while (w != null && w != this) {
  6397. w = w.getParent();
  6398. }
  6399. return w != null;
  6400. }
  6401. private boolean handleEditorEvent(Event event, RowContainer container) {
  6402. Widget w;
  6403. if (editor.focusedColumnIndex < 0) {
  6404. w = null;
  6405. } else {
  6406. w = editor.getWidget(getColumn(editor.focusedColumnIndex));
  6407. }
  6408. EditorDomEvent<T> editorEvent = new EditorDomEvent<T>(event,
  6409. getEventCell(), w);
  6410. return getEditor().getEventHandler().handleEvent(editorEvent);
  6411. }
  6412. private boolean handleRendererEvent(Event event, RowContainer container) {
  6413. if (container == escalator.getBody()) {
  6414. Column<?, T> gridColumn = eventCell.getColumn();
  6415. boolean enterKey = event.getType().equals(BrowserEvents.KEYDOWN)
  6416. && event.getKeyCode() == KeyCodes.KEY_ENTER;
  6417. boolean doubleClick = event.getType()
  6418. .equals(BrowserEvents.DBLCLICK);
  6419. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  6420. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  6421. .getRenderer();
  6422. if (cplxRenderer.getConsumedEvents()
  6423. .contains(event.getType())) {
  6424. if (cplxRenderer.onBrowserEvent(eventCell, event)) {
  6425. return true;
  6426. }
  6427. }
  6428. // Calls onActivate if KeyDown and Enter or double click
  6429. if ((enterKey || doubleClick)
  6430. && cplxRenderer.onActivate(eventCell)) {
  6431. return true;
  6432. }
  6433. }
  6434. }
  6435. return false;
  6436. }
  6437. private boolean handleCellFocusEvent(Event event, RowContainer container) {
  6438. Collection<String> navigation = cellFocusHandler.getNavigationEvents();
  6439. if (navigation.contains(event.getType())) {
  6440. cellFocusHandler.handleNavigationEvent(event, eventCell);
  6441. }
  6442. return false;
  6443. }
  6444. private boolean handleHeaderCellDragStartEvent(Event event,
  6445. RowContainer container) {
  6446. if (!isColumnReorderingAllowed()) {
  6447. return false;
  6448. }
  6449. if (container != escalator.getHeader()) {
  6450. return false;
  6451. }
  6452. if (eventCell.getColumnIndex() < escalator.getColumnConfiguration()
  6453. .getFrozenColumnCount()) {
  6454. return false;
  6455. }
  6456. if (event.getTypeInt() == Event.ONMOUSEDOWN
  6457. && event.getButton() == NativeEvent.BUTTON_LEFT
  6458. || event.getTypeInt() == Event.ONTOUCHSTART) {
  6459. dndHandler.onDragStartOnDraggableElement(event,
  6460. headerCellDndCallback);
  6461. event.preventDefault();
  6462. event.stopPropagation();
  6463. return true;
  6464. }
  6465. return false;
  6466. }
  6467. private Point rowEventTouchStartingPoint;
  6468. private CellStyleGenerator<T> cellStyleGenerator;
  6469. private RowStyleGenerator<T> rowStyleGenerator;
  6470. private RowReference<T> rowReference = new RowReference<T>(this);
  6471. private CellReference<T> cellReference = new CellReference<T>(rowReference);
  6472. private RendererCellReference rendererCellReference = new RendererCellReference(
  6473. (RowReference<Object>) rowReference);
  6474. private boolean handleHeaderDefaultRowEvent(Event event,
  6475. RowContainer container) {
  6476. if (container != escalator.getHeader()) {
  6477. return false;
  6478. }
  6479. if (!getHeader().getRow(eventCell.getRowIndex()).isDefault()) {
  6480. return false;
  6481. }
  6482. if (!eventCell.getColumn().isSortable()) {
  6483. // Only handle sorting events if the column is sortable
  6484. return false;
  6485. }
  6486. if (BrowserEvents.MOUSEDOWN.equals(event.getType())
  6487. && event.getShiftKey()) {
  6488. // Don't select text when shift clicking on a header.
  6489. event.preventDefault();
  6490. }
  6491. if (BrowserEvents.TOUCHSTART.equals(event.getType())) {
  6492. if (event.getTouches().length() > 1) {
  6493. return false;
  6494. }
  6495. event.preventDefault();
  6496. Touch touch = event.getChangedTouches().get(0);
  6497. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  6498. touch.getClientY());
  6499. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, true);
  6500. return true;
  6501. } else if (BrowserEvents.TOUCHMOVE.equals(event.getType())) {
  6502. if (event.getTouches().length() > 1) {
  6503. return false;
  6504. }
  6505. event.preventDefault();
  6506. Touch touch = event.getChangedTouches().get(0);
  6507. double diffX = Math.abs(
  6508. touch.getClientX() - rowEventTouchStartingPoint.getX());
  6509. double diffY = Math.abs(
  6510. touch.getClientY() - rowEventTouchStartingPoint.getY());
  6511. // Cancel long tap if finger strays too far from
  6512. // starting point
  6513. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  6514. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  6515. sorter.cancelDelayedSort();
  6516. }
  6517. return true;
  6518. } else if (BrowserEvents.TOUCHEND.equals(event.getType())) {
  6519. if (event.getTouches().length() > 1) {
  6520. return false;
  6521. }
  6522. if (sorter.isDelayedSortScheduled()) {
  6523. // Not a long tap yet, perform single sort
  6524. sorter.cancelDelayedSort();
  6525. sorter.sort(eventCell.getColumn(), false);
  6526. }
  6527. return true;
  6528. } else if (BrowserEvents.TOUCHCANCEL.equals(event.getType())) {
  6529. if (event.getTouches().length() > 1) {
  6530. return false;
  6531. }
  6532. sorter.cancelDelayedSort();
  6533. return true;
  6534. } else if (BrowserEvents.CLICK.equals(event.getType())) {
  6535. sorter.sort(eventCell.getColumn(), event.getShiftKey());
  6536. // Click events should go onward to cell focus logic
  6537. return false;
  6538. } else {
  6539. return false;
  6540. }
  6541. }
  6542. @Override
  6543. @SuppressWarnings("deprecation")
  6544. public com.google.gwt.user.client.Element getSubPartElement(
  6545. String subPart) {
  6546. /*
  6547. * handles details[] (translated to spacer[] for Escalator), cell[],
  6548. * header[] and footer[]
  6549. */
  6550. // "#header[0][0]/DRAGhANDLE"
  6551. Element escalatorElement = escalator.getSubPartElement(
  6552. subPart.replaceFirst("^details\\[", "spacer["));
  6553. if (escalatorElement != null) {
  6554. int detailIdx = subPart.indexOf("/");
  6555. if (detailIdx > 0) {
  6556. String detail = subPart.substring(detailIdx + 1);
  6557. getLogger().severe("Looking up detail from index " + detailIdx
  6558. + " onward: \"" + detail + "\"");
  6559. if (detail.equalsIgnoreCase("content")) {
  6560. // XXX: Fix this to look up by class name!
  6561. return DOM.asOld(Element.as(escalatorElement.getChild(0)));
  6562. }
  6563. if (detail.equalsIgnoreCase("draghandle")) {
  6564. // XXX: Fix this to look up by class name!
  6565. return DOM.asOld(Element.as(escalatorElement.getChild(1)));
  6566. }
  6567. }
  6568. return DOM.asOld(escalatorElement);
  6569. }
  6570. SubPartArguments args = SubPartArguments.create(subPart);
  6571. Element editor = getSubPartElementEditor(args);
  6572. if (editor != null) {
  6573. return DOM.asOld(editor);
  6574. }
  6575. return null;
  6576. }
  6577. private Element getSubPartElementEditor(SubPartArguments args) {
  6578. if (!args.getType().equalsIgnoreCase("editor")
  6579. || editor.getState() != State.ACTIVE) {
  6580. return null;
  6581. }
  6582. if (args.getIndicesLength() == 0) {
  6583. return editor.editorOverlay;
  6584. } else if (args.getIndicesLength() == 1) {
  6585. int index = args.getIndex(0);
  6586. if (index >= columns.size()) {
  6587. return null;
  6588. }
  6589. escalator.scrollToColumn(index, ScrollDestination.ANY, 0);
  6590. Widget widget = editor.getWidget(columns.get(index));
  6591. if (widget != null) {
  6592. return widget.getElement();
  6593. }
  6594. // No widget for the column.
  6595. return null;
  6596. }
  6597. return null;
  6598. }
  6599. @Override
  6600. @SuppressWarnings("deprecation")
  6601. public String getSubPartName(
  6602. com.google.gwt.user.client.Element subElement) {
  6603. String escalatorStructureName = escalator.getSubPartName(subElement);
  6604. if (escalatorStructureName != null) {
  6605. return escalatorStructureName.replaceFirst("^spacer", "details");
  6606. }
  6607. String editorName = getSubPartNameEditor(subElement);
  6608. if (editorName != null) {
  6609. return editorName;
  6610. }
  6611. return null;
  6612. }
  6613. private String getSubPartNameEditor(Element subElement) {
  6614. if (editor.getState() != State.ACTIVE
  6615. || !editor.editorOverlay.isOrHasChild(subElement)) {
  6616. return null;
  6617. }
  6618. int i = 0;
  6619. for (Column<?, T> column : columns) {
  6620. if (editor.getWidget(column).getElement()
  6621. .isOrHasChild(subElement)) {
  6622. return "editor[" + i + "]";
  6623. }
  6624. ++i;
  6625. }
  6626. return "editor";
  6627. }
  6628. private void setSelectColumnRenderer(
  6629. final Renderer<Boolean> selectColumnRenderer) {
  6630. if (this.selectColumnRenderer == selectColumnRenderer) {
  6631. return;
  6632. }
  6633. if (this.selectColumnRenderer != null) {
  6634. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  6635. // End of Life for the old selection column renderer.
  6636. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  6637. }
  6638. // Clear field so frozen column logic in the remove method knows
  6639. // what to do
  6640. Column<?, T> colToRemove = selectionColumn;
  6641. selectionColumn = null;
  6642. removeColumnSkipSelectionColumnCheck(colToRemove);
  6643. cellFocusHandler.offsetRangeBy(-1);
  6644. }
  6645. this.selectColumnRenderer = selectColumnRenderer;
  6646. if (selectColumnRenderer != null) {
  6647. cellFocusHandler.offsetRangeBy(1);
  6648. selectionColumn = new SelectionColumn(selectColumnRenderer);
  6649. addColumnSkipSelectionColumnCheck(selectionColumn, 0);
  6650. selectionColumn.setEnabled(isEnabled());
  6651. selectionColumn.initDone();
  6652. } else {
  6653. selectionColumn = null;
  6654. refreshBody();
  6655. }
  6656. updateFrozenColumns();
  6657. }
  6658. /**
  6659. * Sets the current selection model.
  6660. * <p>
  6661. * This function will call {@link SelectionModel#setGrid(Grid)}.
  6662. *
  6663. * @param selectionModel
  6664. * a selection model implementation.
  6665. * @throws IllegalArgumentException
  6666. * if selection model argument is null
  6667. */
  6668. public void setSelectionModel(SelectionModel<T> selectionModel) {
  6669. if (selectionModel == null) {
  6670. throw new IllegalArgumentException("Selection model can't be null");
  6671. }
  6672. if (this.selectionModel != null) {
  6673. // Detach selection model from Grid.
  6674. this.selectionModel.setGrid(null);
  6675. }
  6676. this.selectionModel = selectionModel;
  6677. selectionModel.setGrid(this);
  6678. setSelectColumnRenderer(
  6679. this.selectionModel.getSelectionColumnRenderer());
  6680. // Refresh rendered rows to update selection, if it has changed
  6681. refreshBody();
  6682. }
  6683. /**
  6684. * Gets a reference to the current selection model.
  6685. *
  6686. * @return the currently used SelectionModel instance.
  6687. */
  6688. public SelectionModel<T> getSelectionModel() {
  6689. return selectionModel;
  6690. }
  6691. /**
  6692. * Sets current selection mode.
  6693. * <p>
  6694. * This is a shorthand method for {@link Grid#setSelectionModel}.
  6695. *
  6696. * @param mode
  6697. * a selection mode value
  6698. * @see {@link SelectionMode}.
  6699. */
  6700. public void setSelectionMode(SelectionMode mode) {
  6701. SelectionModel<T> model = mode.createModel();
  6702. setSelectionModel(model);
  6703. }
  6704. /**
  6705. * Test if a row is selected.
  6706. *
  6707. * @param row
  6708. * a row object
  6709. * @return true, if the current selection model considers the provided row
  6710. * object selected.
  6711. */
  6712. public boolean isSelected(T row) {
  6713. return selectionModel.isSelected(row);
  6714. }
  6715. /**
  6716. * Select a row using the current selection model.
  6717. * <p>
  6718. * Only selection models implementing {@link SelectionModel.Single} and
  6719. * {@link SelectionModel.Multi} are supported; for anything else, an
  6720. * exception will be thrown.
  6721. *
  6722. * @param row
  6723. * a row object
  6724. * @return <code>true</code> iff the current selection changed
  6725. * @throws IllegalStateException
  6726. * if the current selection model is not an instance of
  6727. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6728. */
  6729. public boolean select(T row) {
  6730. if (selectionModel instanceof SelectionModel.Single<?>) {
  6731. return ((SelectionModel.Single<T>) selectionModel).select(row);
  6732. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6733. return ((SelectionModel.Multi<T>) selectionModel)
  6734. .select(Collections.singleton(row));
  6735. } else {
  6736. throw new IllegalStateException("Unsupported selection model");
  6737. }
  6738. }
  6739. /**
  6740. * Deselect a row using the current selection model.
  6741. * <p>
  6742. * Only selection models implementing {@link SelectionModel.Single} and
  6743. * {@link SelectionModel.Multi} are supported; for anything else, an
  6744. * exception will be thrown.
  6745. *
  6746. * @param row
  6747. * a row object
  6748. * @return <code>true</code> iff the current selection changed
  6749. * @throws IllegalStateException
  6750. * if the current selection model is not an instance of
  6751. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6752. */
  6753. public boolean deselect(T row) {
  6754. if (selectionModel instanceof SelectionModel.Single<?>) {
  6755. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  6756. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6757. return ((SelectionModel.Multi<T>) selectionModel)
  6758. .deselect(Collections.singleton(row));
  6759. } else {
  6760. throw new IllegalStateException("Unsupported selection model");
  6761. }
  6762. }
  6763. /**
  6764. * Deselect all rows using the current selection model.
  6765. *
  6766. * @param row
  6767. * a row object
  6768. * @return <code>true</code> iff the current selection changed
  6769. * @throws IllegalStateException
  6770. * if the current selection model is not an instance of
  6771. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6772. */
  6773. public boolean deselectAll() {
  6774. if (selectionModel instanceof SelectionModel.Single<?>) {
  6775. Single<T> single = ((SelectionModel.Single<T>) selectionModel);
  6776. if (single.getSelectedRow() != null) {
  6777. return single.deselect(single.getSelectedRow());
  6778. } else {
  6779. return false;
  6780. }
  6781. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6782. return ((SelectionModel.Multi<T>) selectionModel).deselectAll();
  6783. } else {
  6784. throw new IllegalStateException("Unsupported selection model");
  6785. }
  6786. }
  6787. /**
  6788. * Gets last selected row from the current SelectionModel.
  6789. * <p>
  6790. * Only selection models implementing {@link SelectionModel.Single} are
  6791. * valid for this method; for anything else, use the
  6792. * {@link Grid#getSelectedRows()} method.
  6793. *
  6794. * @return a selected row reference, or null, if no row is selected
  6795. * @throws IllegalStateException
  6796. * if the current selection model is not an instance of
  6797. * {@link SelectionModel.Single}
  6798. */
  6799. public T getSelectedRow() {
  6800. if (selectionModel instanceof SelectionModel.Single<?>) {
  6801. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  6802. } else {
  6803. throw new IllegalStateException(
  6804. "Unsupported selection model; can not get single selected row");
  6805. }
  6806. }
  6807. /**
  6808. * Gets currently selected rows from the current selection model.
  6809. *
  6810. * @return a non-null collection containing all currently selected rows.
  6811. */
  6812. public Collection<T> getSelectedRows() {
  6813. return selectionModel.getSelectedRows();
  6814. }
  6815. @Override
  6816. public HandlerRegistration addSelectionHandler(
  6817. final SelectionHandler<T> handler) {
  6818. return addHandler(handler, SelectionEvent.getType());
  6819. }
  6820. /**
  6821. * Sets the current sort order using the fluid Sort API. Read the
  6822. * documentation for {@link Sort} for more information.
  6823. *
  6824. * @param s
  6825. * a sort instance
  6826. */
  6827. public void sort(Sort s) {
  6828. setSortOrder(s.build());
  6829. }
  6830. /**
  6831. * Sorts the Grid data in ascending order along one column.
  6832. *
  6833. * @param column
  6834. * a grid column reference
  6835. */
  6836. public <C> void sort(Column<C, T> column) {
  6837. sort(column, SortDirection.ASCENDING);
  6838. }
  6839. /**
  6840. * Sorts the Grid data along one column.
  6841. *
  6842. * @param column
  6843. * a grid column reference
  6844. * @param direction
  6845. * a sort direction value
  6846. */
  6847. public <C> void sort(Column<C, T> column, SortDirection direction) {
  6848. sort(Sort.by(column, direction));
  6849. }
  6850. /**
  6851. * Sets the sort order to use. Setting this causes the Grid to re-sort
  6852. * itself.
  6853. *
  6854. * @param order
  6855. * a sort order list. If set to null, the sort order is cleared.
  6856. */
  6857. public void setSortOrder(List<SortOrder> order) {
  6858. setSortOrder(order, false);
  6859. }
  6860. /**
  6861. * Clears the sort order and indicators without re-sorting.
  6862. */
  6863. private void clearSortOrder() {
  6864. sortOrder.clear();
  6865. refreshHeader();
  6866. }
  6867. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  6868. if (order != sortOrder) {
  6869. sortOrder.clear();
  6870. if (order != null) {
  6871. sortOrder.addAll(order);
  6872. }
  6873. }
  6874. sort(userOriginated);
  6875. }
  6876. /**
  6877. * Get a copy of the current sort order array.
  6878. *
  6879. * @return a copy of the current sort order array
  6880. */
  6881. public List<SortOrder> getSortOrder() {
  6882. return Collections.unmodifiableList(sortOrder);
  6883. }
  6884. /**
  6885. * Finds the sorting order for this column
  6886. */
  6887. private SortOrder getSortOrder(Column<?, ?> column) {
  6888. for (SortOrder order : getSortOrder()) {
  6889. if (order.getColumn() == column) {
  6890. return order;
  6891. }
  6892. }
  6893. return null;
  6894. }
  6895. /**
  6896. * Register a GWT event handler for a sorting event. This handler gets
  6897. * called whenever this Grid needs its data source to provide data sorted in
  6898. * a specific order.
  6899. *
  6900. * @param handler
  6901. * a sort event handler
  6902. * @return the registration for the event
  6903. */
  6904. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  6905. return addHandler(handler, SortEvent.getType());
  6906. }
  6907. /**
  6908. * Register a GWT event handler for a select all event. This handler gets
  6909. * called whenever Grid needs all rows selected.
  6910. *
  6911. * @param handler
  6912. * a select all event handler
  6913. */
  6914. public HandlerRegistration addSelectAllHandler(
  6915. SelectAllHandler<T> handler) {
  6916. return addHandler(handler, SelectAllEvent.getType());
  6917. }
  6918. /**
  6919. * Register a GWT event handler for a data available event. This handler
  6920. * gets called whenever the {@link DataSource} for this Grid has new data
  6921. * available.
  6922. * <p>
  6923. * This handle will be fired with the current available data after
  6924. * registration is done.
  6925. *
  6926. * @param handler
  6927. * a data available event handler
  6928. * @return the registartion for the event
  6929. */
  6930. public HandlerRegistration addDataAvailableHandler(
  6931. final DataAvailableHandler handler) {
  6932. // Deferred call to handler with current row range
  6933. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  6934. @Override
  6935. public void execute() {
  6936. if (!dataIsBeingFetched) {
  6937. handler.onDataAvailable(
  6938. new DataAvailableEvent(currentDataAvailable));
  6939. }
  6940. }
  6941. });
  6942. return addHandler(handler, DataAvailableEvent.TYPE);
  6943. }
  6944. /**
  6945. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  6946. * fired when a KeyDown event occurs while cell focus is in the Body of this
  6947. * Grid.
  6948. *
  6949. * @param handler
  6950. * the key handler to register
  6951. * @return the registration for the event
  6952. */
  6953. public HandlerRegistration addBodyKeyDownHandler(
  6954. BodyKeyDownHandler handler) {
  6955. return addHandler(handler, keyDown.getAssociatedType());
  6956. }
  6957. /**
  6958. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  6959. * fired when a KeyUp event occurs while cell focus is in the Body of this
  6960. * Grid.
  6961. *
  6962. * @param handler
  6963. * the key handler to register
  6964. * @return the registration for the event
  6965. */
  6966. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  6967. return addHandler(handler, keyUp.getAssociatedType());
  6968. }
  6969. /**
  6970. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  6971. * is fired when a KeyPress event occurs while cell focus is in the Body of
  6972. * this Grid.
  6973. *
  6974. * @param handler
  6975. * the key handler to register
  6976. * @return the registration for the event
  6977. */
  6978. public HandlerRegistration addBodyKeyPressHandler(
  6979. BodyKeyPressHandler handler) {
  6980. return addHandler(handler, keyPress.getAssociatedType());
  6981. }
  6982. /**
  6983. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  6984. * is fired when a KeyDown event occurs while cell focus is in the Header of
  6985. * this Grid.
  6986. *
  6987. * @param handler
  6988. * the key handler to register
  6989. * @return the registration for the event
  6990. */
  6991. public HandlerRegistration addHeaderKeyDownHandler(
  6992. HeaderKeyDownHandler handler) {
  6993. return addHandler(handler, keyDown.getAssociatedType());
  6994. }
  6995. /**
  6996. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  6997. * fired when a KeyUp event occurs while cell focus is in the Header of this
  6998. * Grid.
  6999. *
  7000. * @param handler
  7001. * the key handler to register
  7002. * @return the registration for the event
  7003. */
  7004. public HandlerRegistration addHeaderKeyUpHandler(
  7005. HeaderKeyUpHandler handler) {
  7006. return addHandler(handler, keyUp.getAssociatedType());
  7007. }
  7008. /**
  7009. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  7010. * is fired when a KeyPress event occurs while cell focus is in the Header
  7011. * of this Grid.
  7012. *
  7013. * @param handler
  7014. * the key handler to register
  7015. * @return the registration for the event
  7016. */
  7017. public HandlerRegistration addHeaderKeyPressHandler(
  7018. HeaderKeyPressHandler handler) {
  7019. return addHandler(handler, keyPress.getAssociatedType());
  7020. }
  7021. /**
  7022. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  7023. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  7024. * this Grid.
  7025. *
  7026. * @param handler
  7027. * the key handler to register
  7028. * @return the registration for the event
  7029. */
  7030. public HandlerRegistration addFooterKeyDownHandler(
  7031. FooterKeyDownHandler handler) {
  7032. return addHandler(handler, keyDown.getAssociatedType());
  7033. }
  7034. /**
  7035. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  7036. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  7037. * Grid.
  7038. *
  7039. * @param handler
  7040. * the key handler to register
  7041. * @return the registration for the event
  7042. */
  7043. public HandlerRegistration addFooterKeyUpHandler(
  7044. FooterKeyUpHandler handler) {
  7045. return addHandler(handler, keyUp.getAssociatedType());
  7046. }
  7047. /**
  7048. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  7049. * is fired when a KeyPress event occurs while cell focus is in the Footer
  7050. * of this Grid.
  7051. *
  7052. * @param handler
  7053. * the key handler to register
  7054. * @return the registration for the event
  7055. */
  7056. public HandlerRegistration addFooterKeyPressHandler(
  7057. FooterKeyPressHandler handler) {
  7058. return addHandler(handler, keyPress.getAssociatedType());
  7059. }
  7060. /**
  7061. * Register a BodyClickHandler to this Grid. The event for this handler is
  7062. * fired when a Click event occurs in the Body of this Grid.
  7063. *
  7064. * @param handler
  7065. * the click handler to register
  7066. * @return the registration for the event
  7067. */
  7068. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  7069. return addHandler(handler, clickEvent.getAssociatedType());
  7070. }
  7071. /**
  7072. * Register a HeaderClickHandler to this Grid. The event for this handler is
  7073. * fired when a Click event occurs in the Header of this Grid.
  7074. *
  7075. * @param handler
  7076. * the click handler to register
  7077. * @return the registration for the event
  7078. */
  7079. public HandlerRegistration addHeaderClickHandler(
  7080. HeaderClickHandler handler) {
  7081. return addHandler(handler, clickEvent.getAssociatedType());
  7082. }
  7083. /**
  7084. * Register a FooterClickHandler to this Grid. The event for this handler is
  7085. * fired when a Click event occurs in the Footer of this Grid.
  7086. *
  7087. * @param handler
  7088. * the click handler to register
  7089. * @return the registration for the event
  7090. */
  7091. public HandlerRegistration addFooterClickHandler(
  7092. FooterClickHandler handler) {
  7093. return addHandler(handler, clickEvent.getAssociatedType());
  7094. }
  7095. /**
  7096. * Register a BodyDoubleClickHandler to this Grid. The event for this
  7097. * handler is fired when a double click event occurs in the Body of this
  7098. * Grid.
  7099. *
  7100. * @param handler
  7101. * the double click handler to register
  7102. * @return the registration for the event
  7103. */
  7104. public HandlerRegistration addBodyDoubleClickHandler(
  7105. BodyDoubleClickHandler handler) {
  7106. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7107. }
  7108. /**
  7109. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  7110. * handler is fired when a double click event occurs in the Header of this
  7111. * Grid.
  7112. *
  7113. * @param handler
  7114. * the double click handler to register
  7115. * @return the registration for the event
  7116. */
  7117. public HandlerRegistration addHeaderDoubleClickHandler(
  7118. HeaderDoubleClickHandler handler) {
  7119. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7120. }
  7121. /**
  7122. * Register a FooterDoubleClickHandler to this Grid. The event for this
  7123. * handler is fired when a double click event occurs in the Footer of this
  7124. * Grid.
  7125. *
  7126. * @param handler
  7127. * the double click handler to register
  7128. * @return the registration for the event
  7129. */
  7130. public HandlerRegistration addFooterDoubleClickHandler(
  7131. FooterDoubleClickHandler handler) {
  7132. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7133. }
  7134. /**
  7135. * Register a column reorder handler to this Grid. The event for this
  7136. * handler is fired when the Grid's columns are reordered.
  7137. *
  7138. * @since 7.5.0
  7139. * @param handler
  7140. * the handler for the event
  7141. * @return the registration for the event
  7142. */
  7143. public HandlerRegistration addColumnReorderHandler(
  7144. ColumnReorderHandler<T> handler) {
  7145. return addHandler(handler, ColumnReorderEvent.getType());
  7146. }
  7147. /**
  7148. * Register a column visibility change handler to this Grid. The event for
  7149. * this handler is fired when the Grid's columns change visibility.
  7150. *
  7151. * @since 7.5.0
  7152. * @param handler
  7153. * the handler for the event
  7154. * @return the registration for the event
  7155. */
  7156. public HandlerRegistration addColumnVisibilityChangeHandler(
  7157. ColumnVisibilityChangeHandler<T> handler) {
  7158. return addHandler(handler, ColumnVisibilityChangeEvent.getType());
  7159. }
  7160. /**
  7161. * Register a column resize handler to this Grid. The event for this handler
  7162. * is fired when the Grid's columns are resized.
  7163. *
  7164. * @since 7.6
  7165. * @param handler
  7166. * the handler for the event
  7167. * @return the registration for the event
  7168. */
  7169. public HandlerRegistration addColumnResizeHandler(
  7170. ColumnResizeHandler<T> handler) {
  7171. return addHandler(handler, ColumnResizeEvent.getType());
  7172. }
  7173. /**
  7174. * Register a enabled status change handler to this Grid. The event for this
  7175. * handler is fired when the Grid changes from disabled to enabled and
  7176. * vice-versa.
  7177. *
  7178. * @param handler
  7179. * the handler for the event
  7180. * @return the registration for the event
  7181. */
  7182. public HandlerRegistration addEnabledHandler(GridEnabledHandler handler) {
  7183. return addHandler(handler, GridEnabledEvent.TYPE);
  7184. }
  7185. public HandlerRegistration addRowHeightChangedHandler(
  7186. RowHeightChangedHandler handler) {
  7187. return escalator.addHandler(handler, RowHeightChangedEvent.TYPE);
  7188. }
  7189. /**
  7190. * Apply sorting to data source.
  7191. */
  7192. private void sort(boolean userOriginated) {
  7193. refreshHeader();
  7194. fireEvent(new SortEvent<T>(this,
  7195. Collections.unmodifiableList(sortOrder), userOriginated));
  7196. }
  7197. private int getLastVisibleRowIndex() {
  7198. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  7199. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  7200. Element lastRow;
  7201. do {
  7202. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  7203. } while (lastRow.getAbsoluteTop() > footerTop);
  7204. return lastRowIndex;
  7205. }
  7206. private int getFirstVisibleRowIndex() {
  7207. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  7208. int headerBottom = escalator.getHeader().getElement()
  7209. .getAbsoluteBottom();
  7210. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  7211. while (firstRow.getAbsoluteBottom() < headerBottom) {
  7212. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  7213. }
  7214. return firstRowIndex;
  7215. }
  7216. /**
  7217. * Adds a scroll handler to this grid
  7218. *
  7219. * @param handler
  7220. * the scroll handler to add
  7221. * @return a handler registration for the registered scroll handler
  7222. */
  7223. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7224. return addHandler(handler, ScrollEvent.TYPE);
  7225. }
  7226. @Override
  7227. public boolean isWorkPending() {
  7228. return escalator.isWorkPending() || dataIsBeingFetched
  7229. || autoColumnWidthsRecalculator.isScheduled()
  7230. || editor.isWorkPending();
  7231. }
  7232. /**
  7233. * Returns whether columns can be reordered with drag and drop.
  7234. *
  7235. * @since 7.5.0
  7236. * @return <code>true</code> if columns can be reordered, false otherwise
  7237. */
  7238. public boolean isColumnReorderingAllowed() {
  7239. return columnReorderingAllowed;
  7240. }
  7241. /**
  7242. * Sets whether column reordering with drag and drop is allowed or not.
  7243. *
  7244. * @since 7.5.0
  7245. * @param columnReorderingAllowed
  7246. * specifies whether column reordering is allowed
  7247. */
  7248. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  7249. this.columnReorderingAllowed = columnReorderingAllowed;
  7250. }
  7251. /**
  7252. * Sets a new column order for the grid. All columns which are not ordered
  7253. * here will remain in the order they were before as the last columns of
  7254. * grid.
  7255. *
  7256. * @param orderedColumns
  7257. * array of columns in wanted order
  7258. */
  7259. public void setColumnOrder(Column<?, T>... orderedColumns) {
  7260. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  7261. // Trigger ComplexRenderer.destroy for old content
  7262. conf.removeColumns(0, conf.getColumnCount());
  7263. List<Column<?, T>> newOrder = new ArrayList<Column<?, T>>();
  7264. if (selectionColumn != null) {
  7265. newOrder.add(selectionColumn);
  7266. }
  7267. int i = 0;
  7268. for (Column<?, T> column : orderedColumns) {
  7269. if (columns.contains(column)) {
  7270. newOrder.add(column);
  7271. ++i;
  7272. } else {
  7273. throw new IllegalArgumentException("Given column at index " + i
  7274. + " does not exist in Grid");
  7275. }
  7276. }
  7277. if (columns.size() != newOrder.size()) {
  7278. columns.removeAll(newOrder);
  7279. newOrder.addAll(columns);
  7280. }
  7281. columns = newOrder;
  7282. List<Column<?, T>> visibleColumns = getVisibleColumns();
  7283. // Do ComplexRenderer.init and render new content
  7284. conf.insertColumns(0, visibleColumns.size());
  7285. // Number of frozen columns should be kept same #16901
  7286. updateFrozenColumns();
  7287. // Update column widths.
  7288. for (Column<?, T> column : columns) {
  7289. column.reapplyWidth();
  7290. }
  7291. // Recalculate all the colspans
  7292. for (HeaderRow row : header.getRows()) {
  7293. row.calculateColspans();
  7294. }
  7295. for (FooterRow row : footer.getRows()) {
  7296. row.calculateColspans();
  7297. }
  7298. columnHider.updateTogglesOrder();
  7299. fireEvent(new ColumnReorderEvent<T>());
  7300. }
  7301. /**
  7302. * Sets the style generator that is used for generating styles for cells
  7303. *
  7304. * @param cellStyleGenerator
  7305. * the cell style generator to set, or <code>null</code> to
  7306. * remove a previously set generator
  7307. */
  7308. public void setCellStyleGenerator(
  7309. CellStyleGenerator<T> cellStyleGenerator) {
  7310. this.cellStyleGenerator = cellStyleGenerator;
  7311. refreshBody();
  7312. }
  7313. /**
  7314. * Gets the style generator that is used for generating styles for cells
  7315. *
  7316. * @return the cell style generator, or <code>null</code> if no generator is
  7317. * set
  7318. */
  7319. public CellStyleGenerator<T> getCellStyleGenerator() {
  7320. return cellStyleGenerator;
  7321. }
  7322. /**
  7323. * Sets the style generator that is used for generating styles for rows
  7324. *
  7325. * @param rowStyleGenerator
  7326. * the row style generator to set, or <code>null</code> to remove
  7327. * a previously set generator
  7328. */
  7329. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  7330. this.rowStyleGenerator = rowStyleGenerator;
  7331. refreshBody();
  7332. }
  7333. /**
  7334. * Gets the style generator that is used for generating styles for rows
  7335. *
  7336. * @return the row style generator, or <code>null</code> if no generator is
  7337. * set
  7338. */
  7339. public RowStyleGenerator<T> getRowStyleGenerator() {
  7340. return rowStyleGenerator;
  7341. }
  7342. private static void setCustomStyleName(Element element, String styleName) {
  7343. assert element != null;
  7344. String oldStyleName = element
  7345. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  7346. if (!SharedUtil.equals(oldStyleName, styleName)) {
  7347. if (oldStyleName != null && !oldStyleName.isEmpty()) {
  7348. element.removeClassName(oldStyleName);
  7349. }
  7350. if (styleName != null && !styleName.isEmpty()) {
  7351. element.addClassName(styleName);
  7352. }
  7353. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  7354. }
  7355. }
  7356. /**
  7357. * Opens the editor over the row with the given index.
  7358. *
  7359. * @param rowIndex
  7360. * the index of the row to be edited
  7361. *
  7362. * @throws IllegalStateException
  7363. * if the editor is not enabled
  7364. * @throws IllegalStateException
  7365. * if the editor is already in edit mode
  7366. */
  7367. public void editRow(int rowIndex) {
  7368. editor.editRow(rowIndex);
  7369. }
  7370. /**
  7371. * Returns whether the editor is currently open on some row.
  7372. *
  7373. * @return {@code true} if the editor is active, {@code false} otherwise.
  7374. */
  7375. public boolean isEditorActive() {
  7376. return editor.getState() != State.INACTIVE;
  7377. }
  7378. /**
  7379. * Saves any unsaved changes in the editor to the data source.
  7380. *
  7381. * @throws IllegalStateException
  7382. * if the editor is not enabled
  7383. * @throws IllegalStateException
  7384. * if the editor is not in edit mode
  7385. */
  7386. public void saveEditor() {
  7387. editor.save();
  7388. }
  7389. /**
  7390. * Cancels the currently active edit and hides the editor. Any changes that
  7391. * are not {@link #saveEditor() saved} are lost.
  7392. *
  7393. * @throws IllegalStateException
  7394. * if the editor is not enabled
  7395. * @throws IllegalStateException
  7396. * if the editor is not in edit mode
  7397. */
  7398. public void cancelEditor() {
  7399. editor.cancel();
  7400. }
  7401. /**
  7402. * Returns the handler responsible for binding data and editor widgets to
  7403. * the editor.
  7404. *
  7405. * @return the editor handler or null if not set
  7406. */
  7407. public EditorHandler<T> getEditorHandler() {
  7408. return editor.getHandler();
  7409. }
  7410. /**
  7411. * Sets the handler responsible for binding data and editor widgets to the
  7412. * editor.
  7413. *
  7414. * @param rowHandler
  7415. * the new editor handler
  7416. *
  7417. * @throws IllegalStateException
  7418. * if the editor is currently in edit mode
  7419. */
  7420. public void setEditorHandler(EditorHandler<T> handler) {
  7421. editor.setHandler(handler);
  7422. }
  7423. /**
  7424. * Returns the enabled state of the editor.
  7425. *
  7426. * @return true if editing is enabled, false otherwise
  7427. */
  7428. public boolean isEditorEnabled() {
  7429. return editor.isEnabled();
  7430. }
  7431. /**
  7432. * Sets the enabled state of the editor.
  7433. *
  7434. * @param enabled
  7435. * true to enable editing, false to disable
  7436. *
  7437. * @throws IllegalStateException
  7438. * if in edit mode and trying to disable
  7439. * @throws IllegalStateException
  7440. * if the editor handler is not set
  7441. */
  7442. public void setEditorEnabled(boolean enabled) {
  7443. editor.setEnabled(enabled);
  7444. }
  7445. /**
  7446. * Returns the editor widget associated with the given column. If the editor
  7447. * is not active, returns null.
  7448. *
  7449. * @param column
  7450. * the column
  7451. * @return the widget if the editor is open, null otherwise
  7452. */
  7453. public Widget getEditorWidget(Column<?, T> column) {
  7454. return editor.getWidget(column);
  7455. }
  7456. /**
  7457. * Sets the caption on the save button in the Grid editor.
  7458. *
  7459. * @param saveCaption
  7460. * the caption to set
  7461. * @throws IllegalArgumentException
  7462. * if {@code saveCaption} is {@code null}
  7463. */
  7464. public void setEditorSaveCaption(String saveCaption)
  7465. throws IllegalArgumentException {
  7466. editor.setSaveCaption(saveCaption);
  7467. }
  7468. /**
  7469. * Gets the current caption on the save button in the Grid editor.
  7470. *
  7471. * @return the current caption on the save button
  7472. */
  7473. public String getEditorSaveCaption() {
  7474. return editor.getSaveCaption();
  7475. }
  7476. /**
  7477. * Sets the caption on the cancel button in the Grid editor.
  7478. *
  7479. * @param cancelCaption
  7480. * the caption to set
  7481. * @throws IllegalArgumentException
  7482. * if {@code cancelCaption} is {@code null}
  7483. */
  7484. public void setEditorCancelCaption(String cancelCaption)
  7485. throws IllegalArgumentException {
  7486. editor.setCancelCaption(cancelCaption);
  7487. }
  7488. /**
  7489. * Gets the caption on the cancel button in the Grid editor.
  7490. *
  7491. * @return the current caption on the cancel button
  7492. */
  7493. public String getEditorCancelCaption() {
  7494. return editor.getCancelCaption();
  7495. }
  7496. @Override
  7497. protected void onAttach() {
  7498. super.onAttach();
  7499. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  7500. setEscalatorSizeFromDataSource();
  7501. }
  7502. // Grid was just attached to DOM. Column widths should be calculated.
  7503. recalculateColumnWidths();
  7504. }
  7505. @Override
  7506. protected void onDetach() {
  7507. Set<Integer> details = new HashSet<Integer>(visibleDetails);
  7508. for (int row : details) {
  7509. setDetailsVisible(row, false);
  7510. }
  7511. super.onDetach();
  7512. }
  7513. @Override
  7514. public void onResize() {
  7515. super.onResize();
  7516. /*
  7517. * Delay calculation to be deferred so Escalator can do it's magic.
  7518. */
  7519. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7520. @Override
  7521. public void execute() {
  7522. if (escalator
  7523. .getInnerWidth() != autoColumnWidthsRecalculator.lastCalculatedInnerWidth) {
  7524. recalculateColumnWidths();
  7525. }
  7526. // Vertical resizing could make editor positioning invalid so it
  7527. // needs to be recalculated on resize
  7528. if (isEditorActive()) {
  7529. editor.updateVerticalScrollPosition();
  7530. }
  7531. // if there is a resize, we need to refresh the body to avoid an
  7532. // off-by-one error which occurs when the user scrolls all the
  7533. // way to the bottom.
  7534. refreshBody();
  7535. }
  7536. });
  7537. }
  7538. /**
  7539. * Grid does not support adding Widgets this way.
  7540. * <p>
  7541. * This method is implemented only because removing widgets from Grid (added
  7542. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7543. *
  7544. * @param w
  7545. * irrelevant
  7546. * @throws UnsupportedOperationException
  7547. * always
  7548. */
  7549. @Override
  7550. @Deprecated
  7551. public void add(Widget w) {
  7552. throw new UnsupportedOperationException(
  7553. "Cannot add widgets to Grid with this method");
  7554. }
  7555. /**
  7556. * Grid does not support clearing Widgets this way.
  7557. * <p>
  7558. * This method is implemented only because removing widgets from Grid (added
  7559. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7560. *
  7561. * @throws UnsupportedOperationException
  7562. * always
  7563. */
  7564. @Override
  7565. @Deprecated
  7566. public void clear() {
  7567. throw new UnsupportedOperationException(
  7568. "Cannot clear widgets from Grid this way");
  7569. }
  7570. /**
  7571. * Grid does not support iterating through Widgets this way.
  7572. * <p>
  7573. * This method is implemented only because removing widgets from Grid (added
  7574. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7575. *
  7576. * @return never
  7577. * @throws UnsupportedOperationException
  7578. * always
  7579. */
  7580. @Override
  7581. @Deprecated
  7582. public Iterator<Widget> iterator() {
  7583. throw new UnsupportedOperationException(
  7584. "Cannot iterate through widgets in Grid this way");
  7585. }
  7586. /**
  7587. * Grid does not support removing Widgets this way.
  7588. * <p>
  7589. * This method is implemented only because removing widgets from Grid (added
  7590. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7591. *
  7592. * @return always <code>false</code>
  7593. */
  7594. @Override
  7595. @Deprecated
  7596. public boolean remove(Widget w) {
  7597. /*
  7598. * This is the method that is the sole reason to have Grid implement
  7599. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  7600. * corresponding Widget will call removeFromParent() on itself. GWT will
  7601. * check there that its parent (i.e. Grid) implements HasWidgets, and
  7602. * will call this remove(Widget) method.
  7603. *
  7604. * tl;dr: all this song and dance to make sure GWT's sanity checks
  7605. * aren't triggered, even though they effectively do nothing interesting
  7606. * from Grid's perspective.
  7607. */
  7608. return false;
  7609. }
  7610. /**
  7611. * Accesses the package private method Widget#setParent()
  7612. *
  7613. * @param widget
  7614. * The widget to access
  7615. * @param parent
  7616. * The parent to set
  7617. */
  7618. private static native final void setParent(Widget widget, Grid<?> parent)
  7619. /*-{
  7620. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  7621. }-*/;
  7622. private static native final void onAttach(Widget widget)
  7623. /*-{
  7624. widget.@Widget::onAttach()();
  7625. }-*/;
  7626. private static native final void onDetach(Widget widget)
  7627. /*-{
  7628. widget.@Widget::onDetach()();
  7629. }-*/;
  7630. @Override
  7631. protected void doAttachChildren() {
  7632. if (sidebar.getParent() == this) {
  7633. onAttach(sidebar);
  7634. }
  7635. }
  7636. @Override
  7637. protected void doDetachChildren() {
  7638. if (sidebar.getParent() == this) {
  7639. onDetach(sidebar);
  7640. }
  7641. }
  7642. private void attachWidget(Widget w, Element parent) {
  7643. assert w.getParent() == null;
  7644. parent.appendChild(w.getElement());
  7645. setParent(w, this);
  7646. }
  7647. private void detachWidget(Widget w) {
  7648. assert w.getParent() == this;
  7649. setParent(w, null);
  7650. w.getElement().removeFromParent();
  7651. }
  7652. /**
  7653. * Resets all cached pixel sizes and reads new values from the DOM. This
  7654. * methods should be used e.g. when styles affecting the dimensions of
  7655. * elements in this grid have been changed.
  7656. */
  7657. public void resetSizesFromDom() {
  7658. getEscalator().resetSizesFromDom();
  7659. }
  7660. /**
  7661. * Sets a new details generator for row details.
  7662. * <p>
  7663. * The currently opened row details will be re-rendered.
  7664. *
  7665. * @since 7.5.0
  7666. * @param detailsGenerator
  7667. * the details generator to set
  7668. * @throws IllegalArgumentException
  7669. * if detailsGenerator is <code>null</code>;
  7670. */
  7671. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  7672. throws IllegalArgumentException {
  7673. if (detailsGenerator == null) {
  7674. throw new IllegalArgumentException(
  7675. "Details generator may not be null");
  7676. }
  7677. for (Integer index : visibleDetails) {
  7678. setDetailsVisible(index, false);
  7679. }
  7680. this.detailsGenerator = detailsGenerator;
  7681. // this will refresh all visible spacers
  7682. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  7683. }
  7684. /**
  7685. * Gets the current details generator for row details.
  7686. *
  7687. * @since 7.5.0
  7688. * @return the detailsGenerator the current details generator
  7689. */
  7690. public DetailsGenerator getDetailsGenerator() {
  7691. return detailsGenerator;
  7692. }
  7693. /**
  7694. * Shows or hides the details for a specific row.
  7695. * <p>
  7696. * This method does nothing if trying to set show already-visible details,
  7697. * or hide already-hidden details.
  7698. *
  7699. * @since 7.5.0
  7700. * @param rowIndex
  7701. * the index of the affected row
  7702. * @param visible
  7703. * <code>true</code> to show the details, or <code>false</code>
  7704. * to hide them
  7705. * @see #isDetailsVisible(int)
  7706. */
  7707. public void setDetailsVisible(int rowIndex, boolean visible) {
  7708. if (DetailsGenerator.NULL.equals(detailsGenerator)) {
  7709. return;
  7710. }
  7711. Integer rowIndexInteger = Integer.valueOf(rowIndex);
  7712. /*
  7713. * We want to prevent opening a details row twice, so any subsequent
  7714. * openings (or closings) of details is a NOOP.
  7715. *
  7716. * When a details row is opened, it is given an arbitrary height
  7717. * (because Escalator requires a height upon opening). Only when it's
  7718. * opened, Escalator will ask the generator to generate a widget, which
  7719. * we then can measure. When measured, we correct the initial height by
  7720. * the original height.
  7721. *
  7722. * Without this check, we would override the measured height, and revert
  7723. * back to the initial, arbitrary, height which would most probably be
  7724. * wrong.
  7725. *
  7726. * see GridSpacerUpdater.init for implementation details.
  7727. */
  7728. boolean isVisible = isDetailsVisible(rowIndex);
  7729. if (visible && !isVisible) {
  7730. escalator.getBody().setSpacer(rowIndex, DETAILS_ROW_INITIAL_HEIGHT);
  7731. visibleDetails.add(rowIndexInteger);
  7732. }
  7733. else if (!visible && isVisible) {
  7734. escalator.getBody().setSpacer(rowIndex, -1);
  7735. visibleDetails.remove(rowIndexInteger);
  7736. }
  7737. }
  7738. /**
  7739. * Check whether the details for a row is visible or not.
  7740. *
  7741. * @since 7.5.0
  7742. * @param rowIndex
  7743. * the index of the row for which to check details
  7744. * @return <code>true</code> iff the details for the given row is visible
  7745. * @see #setDetailsVisible(int, boolean)
  7746. */
  7747. public boolean isDetailsVisible(int rowIndex) {
  7748. return visibleDetails.contains(Integer.valueOf(rowIndex));
  7749. }
  7750. /**
  7751. * Requests that the column widths should be recalculated.
  7752. * <p>
  7753. * The actual recalculation is not necessarily done immediately so you
  7754. * cannot rely on the columns being the correct width after the call
  7755. * returns.
  7756. *
  7757. * @since 7.4.1
  7758. */
  7759. public void recalculateColumnWidths() {
  7760. autoColumnWidthsRecalculator.schedule();
  7761. }
  7762. /**
  7763. * Gets the customizable menu bar that is by default used for toggling
  7764. * column hidability. The application developer is allowed to add their
  7765. * custom items to the end of the menu, but should try to avoid modifying
  7766. * the items in the beginning of the menu that control the column hiding if
  7767. * any columns are marked as hidable. A toggle for opening the menu will be
  7768. * displayed whenever the menu contains at least one item.
  7769. *
  7770. * @since 7.5.0
  7771. * @return the menu bar
  7772. */
  7773. public MenuBar getSidebarMenu() {
  7774. return sidebar.menuBar;
  7775. }
  7776. /**
  7777. * Tests whether the sidebar menu is currently open.
  7778. *
  7779. * @since 7.5.0
  7780. * @see #getSidebarMenu()
  7781. * @return <code>true</code> if the sidebar is open; <code>false</code> if
  7782. * it is closed
  7783. */
  7784. public boolean isSidebarOpen() {
  7785. return sidebar.isOpen();
  7786. }
  7787. /**
  7788. * Sets whether the sidebar menu is open.
  7789. *
  7790. *
  7791. * @since 7.5.0
  7792. * @see #getSidebarMenu()
  7793. * @see #isSidebarOpen()
  7794. * @param sidebarOpen
  7795. * <code>true</code> to open the sidebar; <code>false</code> to
  7796. * close it
  7797. */
  7798. public void setSidebarOpen(boolean sidebarOpen) {
  7799. if (sidebarOpen) {
  7800. sidebar.open();
  7801. } else {
  7802. sidebar.close();
  7803. }
  7804. }
  7805. @Override
  7806. public int getTabIndex() {
  7807. return FocusUtil.getTabIndex(this);
  7808. }
  7809. @Override
  7810. public void setAccessKey(char key) {
  7811. FocusUtil.setAccessKey(this, key);
  7812. }
  7813. @Override
  7814. public void setFocus(boolean focused) {
  7815. FocusUtil.setFocus(this, focused);
  7816. }
  7817. @Override
  7818. public void setTabIndex(int index) {
  7819. FocusUtil.setTabIndex(this, index);
  7820. }
  7821. @Override
  7822. public void focus() {
  7823. setFocus(true);
  7824. }
  7825. /**
  7826. * Sets the buffered editor mode.
  7827. *
  7828. * @since 7.6
  7829. * @param editorUnbuffered
  7830. * <code>true</code> to enable buffered editor,
  7831. * <code>false</code> to disable it
  7832. */
  7833. public void setEditorBuffered(boolean editorBuffered) {
  7834. editor.setBuffered(editorBuffered);
  7835. }
  7836. /**
  7837. * Gets the buffered editor mode.
  7838. *
  7839. * @since 7.6
  7840. * @return <code>true</code> if buffered editor is enabled,
  7841. * <code>false</code> otherwise
  7842. */
  7843. public boolean isEditorBuffered() {
  7844. return editor.isBuffered();
  7845. }
  7846. /**
  7847. * Returns the {@link EventCellReference} for the latest event fired from
  7848. * this Grid.
  7849. * <p>
  7850. * Note: This cell reference will be updated when firing the next event.
  7851. *
  7852. * @since 7.5
  7853. * @return event cell reference
  7854. */
  7855. public EventCellReference<T> getEventCell() {
  7856. return eventCell;
  7857. }
  7858. /**
  7859. * Returns a CellReference for the cell to which the given element belongs
  7860. * to.
  7861. *
  7862. * @since 7.6
  7863. * @param element
  7864. * Element to find from the cell's content.
  7865. * @return CellReference or <code>null</code> if cell was not found.
  7866. */
  7867. public CellReference<T> getCellReference(Element element) {
  7868. RowContainer container = getEscalator().findRowContainer(element);
  7869. if (container != null) {
  7870. Cell cell = container.getCell(element);
  7871. if (cell != null) {
  7872. EventCellReference<T> cellRef = new EventCellReference<T>(this);
  7873. cellRef.set(cell, getSectionFromContainer(container));
  7874. return cellRef;
  7875. }
  7876. }
  7877. return null;
  7878. }
  7879. }