Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Grid.java 327KB

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