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

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