Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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