Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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