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 337KB

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