您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Grid.java 325KB

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