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

Grid.java 326KB

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