You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Grid.java 327KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.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 iff 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, isBuffered()
  1453. ? ScrollDestination.MIDDLE : ScrollDestination.ANY);
  1454. }
  1455. }
  1456. /**
  1457. * Cancels the currently active edit and hides the editor. Any changes
  1458. * that are not {@link #save() saved} are lost.
  1459. *
  1460. * @throws IllegalStateException
  1461. * if this editor is not enabled
  1462. * @throws IllegalStateException
  1463. * if this editor is not in edit mode
  1464. */
  1465. public void cancel() {
  1466. if (!enabled) {
  1467. throw new IllegalStateException(
  1468. "Cannot cancel edit: editor is not enabled");
  1469. }
  1470. if (state == State.INACTIVE) {
  1471. throw new IllegalStateException(
  1472. "Cannot cancel edit: editor is not in edit mode");
  1473. }
  1474. handler.cancel(new EditorRequestImpl<T>(grid, rowIndex,
  1475. focusedColumnIndexDOM, null));
  1476. doCancel();
  1477. }
  1478. private void doCancel() {
  1479. hideOverlay();
  1480. state = State.INACTIVE;
  1481. rowIndex = -1;
  1482. focusedColumnIndexDOM = -1;
  1483. grid.getEscalator().setScrollLocked(Direction.VERTICAL, false);
  1484. updateSelectionCheckboxesAsNeeded(true);
  1485. }
  1486. private void updateSelectionCheckboxesAsNeeded(boolean isEnabled) {
  1487. // FIXME: This is too much guessing. Define a better way to do this.
  1488. if (grid.selectionColumn != null && grid.selectionColumn
  1489. .getRenderer() instanceof MultiSelectionRenderer) {
  1490. grid.refreshBody();
  1491. CheckBox checkBox = (CheckBox) grid.getDefaultHeaderRow()
  1492. .getCell(grid.selectionColumn).getWidget();
  1493. checkBox.setEnabled(isEnabled);
  1494. }
  1495. }
  1496. /**
  1497. * Saves any unsaved changes to the data source and hides the editor.
  1498. *
  1499. * @throws IllegalStateException
  1500. * if this editor is not enabled
  1501. * @throws IllegalStateException
  1502. * if this editor is not in edit mode
  1503. */
  1504. public void save() {
  1505. if (!enabled) {
  1506. throw new IllegalStateException(
  1507. "Cannot save: editor is not enabled");
  1508. }
  1509. if (state != State.ACTIVE) {
  1510. throw new IllegalStateException(
  1511. "Cannot save: editor is not in edit mode");
  1512. }
  1513. state = State.SAVING;
  1514. setButtonsEnabled(false);
  1515. saveTimeout.schedule(SAVE_TIMEOUT_MS);
  1516. EditorRequest<T> request = new EditorRequestImpl<T>(grid, rowIndex,
  1517. focusedColumnIndexDOM, saveRequestCallback);
  1518. handler.save(request);
  1519. updateSelectionCheckboxesAsNeeded(true);
  1520. }
  1521. /**
  1522. * Returns the handler responsible for binding data and editor widgets
  1523. * to this editor.
  1524. *
  1525. * @return the editor handler or null if not set
  1526. */
  1527. public EditorHandler<T> getHandler() {
  1528. return handler;
  1529. }
  1530. /**
  1531. * Sets the handler responsible for binding data and editor widgets to
  1532. * this editor.
  1533. *
  1534. * @param rowHandler
  1535. * the new editor handler
  1536. *
  1537. * @throws IllegalStateException
  1538. * if this editor is currently in edit mode
  1539. */
  1540. public void setHandler(EditorHandler<T> rowHandler) {
  1541. if (state != State.INACTIVE) {
  1542. throw new IllegalStateException(
  1543. "Cannot set EditorHandler: editor is currently in edit mode");
  1544. }
  1545. handler = rowHandler;
  1546. }
  1547. public boolean isEnabled() {
  1548. return enabled;
  1549. }
  1550. /**
  1551. * Sets the enabled state of this editor.
  1552. *
  1553. * @param enabled
  1554. * true if enabled, false otherwise
  1555. *
  1556. * @throws IllegalStateException
  1557. * if in edit mode and trying to disable
  1558. * @throws IllegalStateException
  1559. * if the editor handler is not set
  1560. */
  1561. public void setEnabled(boolean enabled) {
  1562. if (!enabled && state != State.INACTIVE) {
  1563. throw new IllegalStateException(
  1564. "Cannot disable: editor is in edit mode");
  1565. } else if (enabled && getHandler() == null) {
  1566. throw new IllegalStateException(
  1567. "Cannot enable: EditorHandler not set");
  1568. }
  1569. this.enabled = enabled;
  1570. }
  1571. protected void show(int rowIndex, int columnIndex) {
  1572. if (state == State.ACTIVATING) {
  1573. state = State.BINDING;
  1574. bindTimeout.schedule(BIND_TIMEOUT_MS);
  1575. EditorRequest<T> request = new EditorRequestImpl<T>(grid,
  1576. rowIndex, columnIndex, bindRequestCallback);
  1577. handler.bind(request);
  1578. grid.getEscalator().setScrollLocked(Direction.VERTICAL,
  1579. isBuffered());
  1580. updateSelectionCheckboxesAsNeeded(false);
  1581. }
  1582. }
  1583. protected void setGrid(final Grid<T> grid) {
  1584. assert grid != null : "Grid cannot be null";
  1585. assert this.grid == null : "Can only attach editor to Grid once";
  1586. this.grid = grid;
  1587. }
  1588. protected State getState() {
  1589. return state;
  1590. }
  1591. protected void setState(State state) {
  1592. this.state = state;
  1593. }
  1594. /**
  1595. * Returns the editor widget associated with the given column. If the
  1596. * editor is not active or the column is not
  1597. * {@link Grid.Column#isEditable() editable}, returns null.
  1598. *
  1599. * @param column
  1600. * the column
  1601. * @return the widget if the editor is open and the column is editable,
  1602. * null otherwise
  1603. */
  1604. protected Widget getWidget(Column<?, T> column) {
  1605. return columnToWidget.get(column);
  1606. }
  1607. /**
  1608. * Equivalent to {@code showOverlay()}. The argument is ignored.
  1609. *
  1610. * @param unused
  1611. * ignored argument
  1612. *
  1613. * @deprecated As of 7.5, use {@link #showOverlay()} instead.
  1614. */
  1615. @Deprecated
  1616. protected void showOverlay(TableRowElement unused) {
  1617. showOverlay();
  1618. }
  1619. /**
  1620. * Opens the editor overlay over the table row indicated by
  1621. * {@link #getRow()}.
  1622. *
  1623. * @since 7.5
  1624. */
  1625. protected void showOverlay() {
  1626. // Ensure overlay is hidden initially
  1627. hideOverlay();
  1628. DivElement gridElement = DivElement.as(grid.getElement());
  1629. TableRowElement tr = grid.getEscalator().getBody()
  1630. .getRowElement(rowIndex);
  1631. hScrollHandler = grid.addScrollHandler(new ScrollHandler() {
  1632. @Override
  1633. public void onScroll(ScrollEvent event) {
  1634. updateHorizontalScrollPosition();
  1635. updateVerticalScrollPosition();
  1636. }
  1637. });
  1638. gridElement.appendChild(editorOverlay);
  1639. editorOverlay.appendChild(frozenCellWrapper);
  1640. editorOverlay.appendChild(cellWrapper);
  1641. editorOverlay.appendChild(messageAndButtonsWrapper);
  1642. updateBufferedStyleName();
  1643. int frozenColumns = grid.getVisibleFrozenColumnCount();
  1644. double frozenColumnsWidth = 0;
  1645. double cellHeight = 0;
  1646. for (int i = 0; i < tr.getCells().getLength(); i++) {
  1647. Element cell = createCell(tr.getCells().getItem(i));
  1648. cellHeight = Math.max(cellHeight,
  1649. WidgetUtil.getRequiredHeightBoundingClientRectDouble(
  1650. tr.getCells().getItem(i)));
  1651. Column<?, T> column = grid.getVisibleColumn(i);
  1652. if (i < frozenColumns) {
  1653. frozenCellWrapper.appendChild(cell);
  1654. frozenColumnsWidth += WidgetUtil
  1655. .getRequiredWidthBoundingClientRectDouble(
  1656. tr.getCells().getItem(i));
  1657. } else {
  1658. cellWrapper.appendChild(cell);
  1659. }
  1660. if (column.isEditable()) {
  1661. Widget editor = getHandler().getWidget(column);
  1662. if (editor != null) {
  1663. columnToWidget.put(column, editor);
  1664. grid.attachWidget(editor, cell);
  1665. }
  1666. if (i == focusedColumnIndexDOM) {
  1667. focusColumn(focusedColumnIndexDOM);
  1668. }
  1669. } else {
  1670. cell.addClassName(NOT_EDITABLE_CLASS_NAME);
  1671. cell.addClassName(tr.getCells().getItem(i).getClassName());
  1672. // If the focused or frozen stylename is present it should
  1673. // not be inherited by the editor cell as it is not useful
  1674. // in the editor and would look broken without additional
  1675. // style rules. This is a bit of a hack.
  1676. cell.removeClassName(grid.cellFocusStyleName);
  1677. cell.removeClassName("frozen");
  1678. if (column == grid.selectionColumn) {
  1679. // Duplicate selection column CheckBox
  1680. pinnedRowHandle = grid.getDataSource().getHandle(
  1681. grid.getDataSource().getRow(rowIndex));
  1682. pinnedRowHandle.pin();
  1683. // We need to duplicate the selection CheckBox for the
  1684. // editor overlay since the original one is hidden by
  1685. // the overlay
  1686. final CheckBox checkBox = GWT.create(CheckBox.class);
  1687. checkBox.setValue(
  1688. grid.isSelected(pinnedRowHandle.getRow()));
  1689. checkBox.sinkEvents(Event.ONCLICK);
  1690. checkBox.addClickHandler(new ClickHandler() {
  1691. @Override
  1692. public void onClick(ClickEvent event) {
  1693. if (!grid.isUserSelectionAllowed()) {
  1694. return;
  1695. }
  1696. T row = pinnedRowHandle.getRow();
  1697. if (grid.isSelected(row)) {
  1698. grid.deselect(row);
  1699. } else {
  1700. grid.select(row);
  1701. }
  1702. }
  1703. });
  1704. grid.attachWidget(checkBox, cell);
  1705. columnToWidget.put(column, checkBox);
  1706. // Only enable CheckBox in non-buffered mode
  1707. checkBox.setEnabled(!isBuffered());
  1708. } else if (!(column
  1709. .getRenderer() instanceof WidgetRenderer)) {
  1710. // Copy non-widget content directly
  1711. cell.setInnerHTML(
  1712. tr.getCells().getItem(i).getInnerHTML());
  1713. }
  1714. }
  1715. }
  1716. setBounds(frozenCellWrapper, 0, 0, frozenColumnsWidth, 0);
  1717. setBounds(cellWrapper, frozenColumnsWidth, 0,
  1718. tr.getOffsetWidth() - frozenColumnsWidth, cellHeight);
  1719. // Only add these elements once
  1720. if (!messageAndButtonsWrapper.isOrHasChild(messageWrapper)) {
  1721. messageAndButtonsWrapper.appendChild(messageWrapper);
  1722. messageAndButtonsWrapper.appendChild(buttonsWrapper);
  1723. }
  1724. if (isBuffered()) {
  1725. grid.attachWidget(saveButton, buttonsWrapper);
  1726. grid.attachWidget(cancelButton, buttonsWrapper);
  1727. }
  1728. setMessageAndButtonsWrapperVisible(isBuffered());
  1729. updateHorizontalScrollPosition();
  1730. AbstractRowContainer body = (AbstractRowContainer) grid
  1731. .getEscalator().getBody();
  1732. double rowTop = body.getRowTop(tr);
  1733. int bodyTop = body.getElement().getAbsoluteTop();
  1734. int gridTop = gridElement.getAbsoluteTop();
  1735. double overlayTop = rowTop + bodyTop - gridTop;
  1736. originalScrollTop = grid.getScrollTop();
  1737. if (!isBuffered() || buttonsShouldBeRenderedBelow(tr)) {
  1738. // Default case, editor buttons are below the edited row
  1739. editorOverlay.getStyle().setTop(overlayTop, Unit.PX);
  1740. originalTop = overlayTop;
  1741. editorOverlay.getStyle().clearBottom();
  1742. } else {
  1743. // Move message and buttons wrapper on top of cell wrapper if
  1744. // there is not enough space visible space under and fix the
  1745. // overlay from the bottom
  1746. editorOverlay.insertFirst(messageAndButtonsWrapper);
  1747. int gridHeight = grid.getElement().getOffsetHeight();
  1748. editorOverlay.getStyle().setBottom(
  1749. gridHeight - overlayTop - tr.getOffsetHeight(),
  1750. Unit.PX);
  1751. editorOverlay.getStyle().clearTop();
  1752. }
  1753. // Do not render over the vertical scrollbar
  1754. editorOverlay.getStyle().setWidth(grid.escalator.getInnerWidth(),
  1755. Unit.PX);
  1756. }
  1757. private void focusColumn(int columnIndexDOM) {
  1758. if (columnIndexDOM < 0
  1759. || columnIndexDOM >= grid.getVisibleColumns().size()) {
  1760. // NO-OP
  1761. return;
  1762. }
  1763. Widget editor = getWidget(grid.getVisibleColumn(columnIndexDOM));
  1764. if (editor instanceof Focusable) {
  1765. ((Focusable) editor).focus();
  1766. } else if (editor instanceof com.google.gwt.user.client.ui.Focusable) {
  1767. ((com.google.gwt.user.client.ui.Focusable) editor)
  1768. .setFocus(true);
  1769. } else {
  1770. grid.focus();
  1771. }
  1772. }
  1773. private boolean buttonsShouldBeRenderedBelow(TableRowElement tr) {
  1774. TableSectionElement tfoot = grid.escalator.getFooter().getElement();
  1775. double tfootPageTop = WidgetUtil.getBoundingClientRect(tfoot)
  1776. .getTop();
  1777. double trPageBottom = WidgetUtil.getBoundingClientRect(tr)
  1778. .getBottom();
  1779. int messageAndButtonsHeight = messageAndButtonsWrapper
  1780. .getOffsetHeight();
  1781. double bottomOfButtons = trPageBottom + messageAndButtonsHeight;
  1782. return bottomOfButtons < tfootPageTop;
  1783. }
  1784. protected void hideOverlay() {
  1785. if (editorOverlay.getParentElement() == null) {
  1786. return;
  1787. }
  1788. if (pinnedRowHandle != null) {
  1789. pinnedRowHandle.unpin();
  1790. pinnedRowHandle = null;
  1791. }
  1792. for (HandlerRegistration r : focusHandlers) {
  1793. r.removeHandler();
  1794. }
  1795. focusHandlers.clear();
  1796. for (Widget w : columnToWidget.values()) {
  1797. setParent(w, null);
  1798. }
  1799. columnToWidget.clear();
  1800. if (isBuffered()) {
  1801. grid.detachWidget(saveButton);
  1802. grid.detachWidget(cancelButton);
  1803. }
  1804. editorOverlay.removeAllChildren();
  1805. cellWrapper.removeAllChildren();
  1806. frozenCellWrapper.removeAllChildren();
  1807. editorOverlay.removeFromParent();
  1808. hScrollHandler.removeHandler();
  1809. clearEditorColumnErrors();
  1810. }
  1811. private void updateBufferedStyleName() {
  1812. if (isBuffered()) {
  1813. editorOverlay.removeClassName("unbuffered");
  1814. editorOverlay.addClassName("buffered");
  1815. } else {
  1816. editorOverlay.removeClassName("buffered");
  1817. editorOverlay.addClassName("unbuffered");
  1818. }
  1819. }
  1820. protected void setStylePrimaryName(String primaryName) {
  1821. if (styleName != null) {
  1822. editorOverlay.removeClassName(styleName);
  1823. cellWrapper.removeClassName(styleName + "-cells");
  1824. frozenCellWrapper.removeClassName(styleName + "-cells");
  1825. messageAndButtonsWrapper.removeClassName(styleName + "-footer");
  1826. messageWrapper.removeClassName(styleName + "-message");
  1827. buttonsWrapper.removeClassName(styleName + "-buttons");
  1828. saveButton.removeStyleName(styleName + "-save");
  1829. cancelButton.removeStyleName(styleName + "-cancel");
  1830. }
  1831. styleName = primaryName + "-editor";
  1832. editorOverlay.setClassName(styleName);
  1833. cellWrapper.setClassName(styleName + "-cells");
  1834. frozenCellWrapper.setClassName(styleName + "-cells frozen");
  1835. messageAndButtonsWrapper.setClassName(styleName + "-footer");
  1836. messageWrapper.setClassName(styleName + "-message");
  1837. buttonsWrapper.setClassName(styleName + "-buttons");
  1838. saveButton.setStyleName(styleName + "-save");
  1839. cancelButton.setStyleName(styleName + "-cancel");
  1840. }
  1841. /**
  1842. * Creates an editor cell corresponding to the given table cell. The
  1843. * returned element is empty and has the same dimensions and position as
  1844. * the table cell.
  1845. *
  1846. * @param td
  1847. * the table cell used as a reference
  1848. * @return an editor cell corresponding to the given cell
  1849. */
  1850. protected Element createCell(TableCellElement td) {
  1851. DivElement cell = DivElement.as(DOM.createDiv());
  1852. double width = WidgetUtil
  1853. .getRequiredWidthBoundingClientRectDouble(td);
  1854. double height = WidgetUtil
  1855. .getRequiredHeightBoundingClientRectDouble(td);
  1856. setBounds(cell, td.getOffsetLeft(), td.getOffsetTop(), width,
  1857. height);
  1858. return cell;
  1859. }
  1860. private static void setBounds(Element e, double left, double top,
  1861. double width, double height) {
  1862. Style style = e.getStyle();
  1863. style.setLeft(left, Unit.PX);
  1864. style.setTop(top, Unit.PX);
  1865. style.setWidth(width, Unit.PX);
  1866. style.setHeight(height, Unit.PX);
  1867. }
  1868. private void updateHorizontalScrollPosition() {
  1869. double scrollLeft = grid.getScrollLeft();
  1870. cellWrapper.getStyle().setLeft(
  1871. frozenCellWrapper.getOffsetWidth() - scrollLeft, Unit.PX);
  1872. }
  1873. /**
  1874. * Moves the editor overlay on scroll so that it stays on top of the
  1875. * edited row. This will also snap the editor to top or bottom of the
  1876. * row container if the edited row is scrolled out of the visible area.
  1877. */
  1878. private void updateVerticalScrollPosition() {
  1879. if (isBuffered()) {
  1880. return;
  1881. }
  1882. double newScrollTop = grid.getScrollTop();
  1883. int gridTop = grid.getElement().getAbsoluteTop();
  1884. int editorHeight = editorOverlay.getOffsetHeight();
  1885. Escalator escalator = grid.getEscalator();
  1886. TableSectionElement header = escalator.getHeader().getElement();
  1887. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  1888. int headerBottom = header.getAbsoluteBottom();
  1889. double newTop = originalTop - (newScrollTop - originalScrollTop);
  1890. if (newTop + gridTop < headerBottom) {
  1891. // Snap editor to top of the row container
  1892. newTop = header.getOffsetHeight();
  1893. } else if (newTop + gridTop > footerTop - editorHeight) {
  1894. // Snap editor to the bottom of the row container
  1895. newTop = footerTop - editorHeight - gridTop;
  1896. }
  1897. editorOverlay.getStyle().setTop(newTop, Unit.PX);
  1898. }
  1899. protected void setGridEnabled(boolean enabled) {
  1900. // TODO: This should be informed to handler as well so possible
  1901. // fields can be disabled.
  1902. setButtonsEnabled(enabled);
  1903. }
  1904. private void setButtonsEnabled(boolean enabled) {
  1905. saveButton.setEnabled(enabled);
  1906. cancelButton.setEnabled(enabled);
  1907. }
  1908. public void setSaveCaption(String saveCaption)
  1909. throws IllegalArgumentException {
  1910. if (saveCaption == null) {
  1911. throw new IllegalArgumentException(
  1912. "Save caption cannot be null");
  1913. }
  1914. saveButton.setText(saveCaption);
  1915. }
  1916. public String getSaveCaption() {
  1917. return saveButton.getText();
  1918. }
  1919. public void setCancelCaption(String cancelCaption)
  1920. throws IllegalArgumentException {
  1921. if (cancelCaption == null) {
  1922. throw new IllegalArgumentException(
  1923. "Cancel caption cannot be null");
  1924. }
  1925. cancelButton.setText(cancelCaption);
  1926. }
  1927. public String getCancelCaption() {
  1928. return cancelButton.getText();
  1929. }
  1930. public void setEditorColumnError(Column<?, T> column,
  1931. boolean hasError) {
  1932. if (state != State.ACTIVE && state != State.SAVING) {
  1933. throw new IllegalStateException("Cannot set cell error "
  1934. + "status: editor is neither active nor saving.");
  1935. }
  1936. if (isEditorColumnError(column) == hasError) {
  1937. return;
  1938. }
  1939. Element editorCell = getWidget(column).getElement()
  1940. .getParentElement();
  1941. if (hasError) {
  1942. editorCell.addClassName(ERROR_CLASS_NAME);
  1943. columnErrors.add(column);
  1944. } else {
  1945. editorCell.removeClassName(ERROR_CLASS_NAME);
  1946. columnErrors.remove(column);
  1947. }
  1948. }
  1949. public void clearEditorColumnErrors() {
  1950. /*
  1951. * editorOverlay has no children if it's not active, effectively
  1952. * making this loop a NOOP.
  1953. */
  1954. Element e = editorOverlay.getFirstChildElement();
  1955. while (e != null) {
  1956. e.removeClassName(ERROR_CLASS_NAME);
  1957. e = e.getNextSiblingElement();
  1958. }
  1959. columnErrors.clear();
  1960. }
  1961. public boolean isEditorColumnError(Column<?, T> column) {
  1962. return columnErrors.contains(column);
  1963. }
  1964. public void setBuffered(boolean buffered) {
  1965. this.buffered = buffered;
  1966. setMessageAndButtonsWrapperVisible(buffered);
  1967. }
  1968. public boolean isBuffered() {
  1969. return buffered;
  1970. }
  1971. private void setMessageAndButtonsWrapperVisible(boolean visible) {
  1972. if (visible) {
  1973. messageAndButtonsWrapper.getStyle().clearDisplay();
  1974. } else {
  1975. messageAndButtonsWrapper.getStyle().setDisplay(Display.NONE);
  1976. }
  1977. }
  1978. /**
  1979. * Sets the event handler for this Editor.
  1980. *
  1981. * @since 7.6
  1982. * @param handler
  1983. * the new event handler
  1984. */
  1985. public void setEventHandler(EventHandler<T> handler) {
  1986. eventHandler = handler;
  1987. }
  1988. /**
  1989. * Returns the event handler of this Editor.
  1990. *
  1991. * @since 7.6
  1992. * @return the current event handler
  1993. */
  1994. public EventHandler<T> getEventHandler() {
  1995. return eventHandler;
  1996. }
  1997. @Override
  1998. public boolean isWorkPending() {
  1999. return saveTimeout.isRunning() || bindTimeout.isRunning();
  2000. }
  2001. protected int getElementColumn(Element e) {
  2002. int frozenCells = frozenCellWrapper.getChildCount();
  2003. if (frozenCellWrapper.isOrHasChild(e)) {
  2004. for (int i = 0; i < frozenCells; ++i) {
  2005. if (frozenCellWrapper.getChild(i).isOrHasChild(e)) {
  2006. return i;
  2007. }
  2008. }
  2009. }
  2010. if (cellWrapper.isOrHasChild(e)) {
  2011. for (int i = 0; i < cellWrapper.getChildCount(); ++i) {
  2012. if (cellWrapper.getChild(i).isOrHasChild(e)) {
  2013. return i + frozenCells;
  2014. }
  2015. }
  2016. }
  2017. return -1;
  2018. }
  2019. }
  2020. public abstract static class AbstractGridKeyEvent<HANDLER extends AbstractGridKeyEventHandler>
  2021. extends KeyEvent<HANDLER> {
  2022. /**
  2023. * @since 7.7.9
  2024. */
  2025. public AbstractGridKeyEvent() {
  2026. }
  2027. /**
  2028. * @deprecated This constructor's arguments are no longer used. Use the
  2029. * no-args constructor instead.
  2030. */
  2031. @Deprecated
  2032. public AbstractGridKeyEvent(Grid<?> grid, CellReference<?> targetCell) {
  2033. }
  2034. protected abstract String getBrowserEventType();
  2035. /**
  2036. * Gets the Grid instance for this event, if it originated from a Grid.
  2037. *
  2038. * @return the grid this event originated from, or {@code null} if this
  2039. * event did not originate from a grid
  2040. */
  2041. public Grid<?> getGrid() {
  2042. EventTarget target = getNativeEvent().getEventTarget();
  2043. if (!Element.is(target)) {
  2044. return null;
  2045. }
  2046. return WidgetUtil.findWidget(Element.as(target), Grid.class);
  2047. }
  2048. /**
  2049. * Gets the reference of target cell for this event, if this event
  2050. * originated from a Grid.
  2051. *
  2052. * @return target cell, or {@code null} if this event did not originate
  2053. * from a grid
  2054. */
  2055. public CellReference<?> getFocusedCell() {
  2056. return getGrid().getEventCell();
  2057. }
  2058. @Override
  2059. protected void dispatch(HANDLER handler) {
  2060. EventTarget target = getNativeEvent().getEventTarget();
  2061. Grid<?> grid = getGrid();
  2062. if (Element.is(target) && grid != null
  2063. && !grid.isElementInChildWidget(Element.as(target))) {
  2064. Section section = Section.FOOTER;
  2065. final RowContainer container = grid.cellFocusHandler.containerWithFocus;
  2066. if (container == grid.escalator.getHeader()) {
  2067. section = Section.HEADER;
  2068. } else if (container == getGrid().escalator.getBody()) {
  2069. section = Section.BODY;
  2070. }
  2071. doDispatch(handler, section);
  2072. }
  2073. }
  2074. protected abstract void doDispatch(HANDLER handler, Section section);
  2075. }
  2076. public abstract static class AbstractGridMouseEvent<HANDLER extends AbstractGridMouseEventHandler>
  2077. extends MouseEvent<HANDLER> {
  2078. /**
  2079. * @since 7.7.9
  2080. */
  2081. public AbstractGridMouseEvent() {
  2082. }
  2083. /**
  2084. * @deprecated This constructor's arguments are no longer used. Use the
  2085. * no-args constructor instead.
  2086. */
  2087. @Deprecated
  2088. public AbstractGridMouseEvent(Grid<?> grid,
  2089. CellReference<?> targetCell) {
  2090. }
  2091. protected abstract String getBrowserEventType();
  2092. /**
  2093. * Gets the Grid instance for this event, if it originated from a Grid.
  2094. *
  2095. * @return the grid this event originated from, or {@code null} if this
  2096. * event did not originate from a grid
  2097. */
  2098. public Grid<?> getGrid() {
  2099. EventTarget target = getNativeEvent().getEventTarget();
  2100. if (!Element.is(target)) {
  2101. return null;
  2102. }
  2103. return WidgetUtil.findWidget(Element.as(target), Grid.class);
  2104. }
  2105. /**
  2106. * Gets the reference of target cell for this event, if this event
  2107. * originated from a Grid.
  2108. *
  2109. * @return target cell, or {@code null} if this event did not originate
  2110. * from a grid
  2111. */
  2112. public CellReference<?> getTargetCell() {
  2113. Grid<?> grid = getGrid();
  2114. if (grid == null) {
  2115. return null;
  2116. }
  2117. return grid.getEventCell();
  2118. }
  2119. @Override
  2120. protected void dispatch(HANDLER handler) {
  2121. EventTarget target = getNativeEvent().getEventTarget();
  2122. if (!Element.is(target)) {
  2123. // Target is not an element
  2124. return;
  2125. }
  2126. Grid<?> grid = getGrid();
  2127. if (grid == null) {
  2128. // Target is not an element of a grid
  2129. return;
  2130. }
  2131. Element targetElement = Element.as(target);
  2132. if (grid.isElementInChildWidget(targetElement)) {
  2133. // Target is some widget inside of Grid
  2134. return;
  2135. }
  2136. final RowContainer container = grid.escalator
  2137. .findRowContainer(targetElement);
  2138. if (container == null) {
  2139. // No container for given element
  2140. return;
  2141. }
  2142. Section section = Section.FOOTER;
  2143. if (container == grid.escalator.getHeader()) {
  2144. section = Section.HEADER;
  2145. } else if (container == grid.escalator.getBody()) {
  2146. section = Section.BODY;
  2147. }
  2148. doDispatch(handler, section);
  2149. }
  2150. protected abstract void doDispatch(HANDLER handler, Section section);
  2151. }
  2152. private static final String CUSTOM_STYLE_PROPERTY_NAME = "customStyle";
  2153. /**
  2154. * An initial height that is given to new details rows before rendering the
  2155. * appropriate widget that we then can be measure
  2156. *
  2157. * @see GridSpacerUpdater
  2158. */
  2159. private static final double DETAILS_ROW_INITIAL_HEIGHT = 50;
  2160. private EventCellReference<T> eventCell = new EventCellReference<T>(this);
  2161. private class CellFocusHandler {
  2162. private RowContainer containerWithFocus = escalator.getBody();
  2163. private int rowWithFocus = 0;
  2164. private Range cellFocusRange = Range.withLength(0, 1);
  2165. private int lastFocusedBodyRow = 0;
  2166. private int lastFocusedHeaderRow = 0;
  2167. private int lastFocusedFooterRow = 0;
  2168. private TableCellElement cellWithFocusStyle = null;
  2169. private TableRowElement rowWithFocusStyle = null;
  2170. public CellFocusHandler() {
  2171. sinkEvents(getNavigationEvents());
  2172. }
  2173. private Cell getFocusedCell() {
  2174. return new Cell(rowWithFocus, cellFocusRange.getStart(),
  2175. cellWithFocusStyle);
  2176. }
  2177. /**
  2178. * Sets style names for given cell when needed.
  2179. */
  2180. public void updateFocusedCellStyle(FlyweightCell cell,
  2181. RowContainer cellContainer) {
  2182. int cellRow = cell.getRow();
  2183. int cellColumn = cell.getColumn();
  2184. int colSpan = cell.getColSpan();
  2185. boolean columnHasFocus = Range.withLength(cellColumn, colSpan)
  2186. .intersects(cellFocusRange);
  2187. if (cellContainer == containerWithFocus) {
  2188. // Cell is in the current container
  2189. if (cellRow == rowWithFocus && columnHasFocus) {
  2190. if (cellWithFocusStyle != cell.getElement()) {
  2191. // Cell is correct but it does not have focused style
  2192. if (cellWithFocusStyle != null) {
  2193. // Remove old focus style
  2194. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2195. false);
  2196. }
  2197. cellWithFocusStyle = cell.getElement();
  2198. // Add focus style to correct cell.
  2199. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  2200. true);
  2201. }
  2202. } else if (cellWithFocusStyle == cell.getElement()) {
  2203. // Due to escalator reusing cells, a new cell has the same
  2204. // element but is not the focused cell.
  2205. setStyleName(cellWithFocusStyle, cellFocusStyleName, false);
  2206. cellWithFocusStyle = null;
  2207. }
  2208. }
  2209. }
  2210. /**
  2211. * Sets focus style for the given row if needed.
  2212. *
  2213. * @param row
  2214. * a row object
  2215. */
  2216. public void updateFocusedRowStyle(Row row) {
  2217. if (rowWithFocus == row.getRow()
  2218. && containerWithFocus == escalator.getBody()) {
  2219. if (row.getElement() != rowWithFocusStyle) {
  2220. // Row should have focus style but does not have it.
  2221. if (rowWithFocusStyle != null) {
  2222. setStyleName(rowWithFocusStyle, rowFocusStyleName,
  2223. false);
  2224. }
  2225. rowWithFocusStyle = row.getElement();
  2226. setStyleName(rowWithFocusStyle, rowFocusStyleName, true);
  2227. }
  2228. } else if (rowWithFocusStyle == row.getElement()
  2229. || containerWithFocus != escalator.getBody()
  2230. && rowWithFocusStyle != null) {
  2231. // Remove focus style.
  2232. setStyleName(rowWithFocusStyle, rowFocusStyleName, false);
  2233. rowWithFocusStyle = null;
  2234. }
  2235. }
  2236. /**
  2237. * Sets the currently focused.
  2238. * <p>
  2239. * <em>NOTE:</em> the column index is the index in DOM, not the logical
  2240. * column index which includes hidden columns.
  2241. *
  2242. * @param rowIndex
  2243. * the index of the row having focus
  2244. * @param columnIndexDOM
  2245. * the index of the cell having focus
  2246. * @param container
  2247. * the row container having focus
  2248. */
  2249. private void setCellFocus(int rowIndex, int columnIndexDOM,
  2250. RowContainer container) {
  2251. if (container == null || rowIndex == rowWithFocus
  2252. && cellFocusRange.contains(columnIndexDOM)
  2253. && container == this.containerWithFocus) {
  2254. return;
  2255. }
  2256. int oldRow = rowWithFocus;
  2257. rowWithFocus = rowIndex;
  2258. Range oldRange = cellFocusRange;
  2259. if (container == escalator.getBody()) {
  2260. scrollToRow(rowWithFocus);
  2261. cellFocusRange = Range.withLength(columnIndexDOM, 1);
  2262. } else {
  2263. int i = 0;
  2264. Element cell = container.getRowElement(rowWithFocus)
  2265. .getFirstChildElement();
  2266. do {
  2267. int colSpan = cell
  2268. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  2269. Range cellRange = Range.withLength(i, colSpan);
  2270. if (cellRange.contains(columnIndexDOM)) {
  2271. cellFocusRange = cellRange;
  2272. break;
  2273. }
  2274. cell = cell.getNextSiblingElement();
  2275. ++i;
  2276. } while (cell != null);
  2277. }
  2278. if (columnIndexDOM >= escalator.getColumnConfiguration()
  2279. .getFrozenColumnCount()) {
  2280. escalator.scrollToColumn(columnIndexDOM, ScrollDestination.ANY,
  2281. 10);
  2282. }
  2283. if (this.containerWithFocus == container) {
  2284. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  2285. refreshRow(oldRow);
  2286. } else {
  2287. refreshHeader();
  2288. refreshFooter();
  2289. }
  2290. } else {
  2291. RowContainer oldContainer = this.containerWithFocus;
  2292. this.containerWithFocus = container;
  2293. if (oldContainer == escalator.getBody()) {
  2294. lastFocusedBodyRow = oldRow;
  2295. } else if (oldContainer == escalator.getHeader()) {
  2296. lastFocusedHeaderRow = oldRow;
  2297. } else {
  2298. lastFocusedFooterRow = oldRow;
  2299. }
  2300. if (!oldRange.equals(cellFocusRange)) {
  2301. refreshHeader();
  2302. refreshFooter();
  2303. if (oldContainer == escalator.getBody()) {
  2304. oldContainer.refreshRows(oldRow, 1);
  2305. }
  2306. } else {
  2307. oldContainer.refreshRows(oldRow, 1);
  2308. }
  2309. }
  2310. refreshRow(rowWithFocus);
  2311. }
  2312. /**
  2313. * Sets focus on a cell.
  2314. *
  2315. * <p>
  2316. * <em>Note</em>: cell focus is not the same as JavaScript's
  2317. * {@code document.activeElement}.
  2318. *
  2319. * @param cell
  2320. * a cell object
  2321. */
  2322. public void setCellFocus(CellReference<T> cell) {
  2323. setCellFocus(cell.getRowIndex(), cell.getColumnIndexDOM(),
  2324. escalator.findRowContainer(cell.getElement()));
  2325. }
  2326. /**
  2327. * Gets list of events that can be used for cell focusing.
  2328. *
  2329. * @return list of navigation related event types
  2330. */
  2331. public Collection<String> getNavigationEvents() {
  2332. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  2333. }
  2334. /**
  2335. * Handle events that can move the cell focus.
  2336. */
  2337. public void handleNavigationEvent(Event event, CellReference<T> cell) {
  2338. if (event.getType().equals(BrowserEvents.CLICK)) {
  2339. setCellFocus(cell);
  2340. // Grid should have focus when clicked.
  2341. getElement().focus();
  2342. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  2343. int newRow = rowWithFocus;
  2344. RowContainer newContainer = containerWithFocus;
  2345. int newColumn = cellFocusRange.getStart();
  2346. switch (event.getKeyCode()) {
  2347. case KeyCodes.KEY_DOWN:
  2348. ++newRow;
  2349. break;
  2350. case KeyCodes.KEY_UP:
  2351. --newRow;
  2352. break;
  2353. case KeyCodes.KEY_RIGHT:
  2354. if (cellFocusRange.getEnd() >= getVisibleColumns().size()) {
  2355. return;
  2356. }
  2357. newColumn = cellFocusRange.getEnd();
  2358. break;
  2359. case KeyCodes.KEY_LEFT:
  2360. if (newColumn == 0) {
  2361. return;
  2362. }
  2363. --newColumn;
  2364. break;
  2365. case KeyCodes.KEY_TAB:
  2366. if (event.getShiftKey()) {
  2367. newContainer = getPreviousContainer(containerWithFocus);
  2368. } else {
  2369. newContainer = getNextContainer(containerWithFocus);
  2370. }
  2371. if (newContainer == containerWithFocus) {
  2372. return;
  2373. }
  2374. break;
  2375. case KeyCodes.KEY_HOME:
  2376. if (newContainer.getRowCount() > 0) {
  2377. newRow = 0;
  2378. }
  2379. break;
  2380. case KeyCodes.KEY_END:
  2381. if (newContainer.getRowCount() > 0) {
  2382. newRow = newContainer.getRowCount() - 1;
  2383. }
  2384. break;
  2385. case KeyCodes.KEY_PAGEDOWN:
  2386. case KeyCodes.KEY_PAGEUP:
  2387. if (newContainer.getRowCount() > 0) {
  2388. boolean down = event
  2389. .getKeyCode() == KeyCodes.KEY_PAGEDOWN;
  2390. // If there is a visible focused cell, scroll by one
  2391. // page from its position. Otherwise, use the first or
  2392. // the last visible row as the scroll start position.
  2393. // This avoids jumping when using both keyboard and the
  2394. // scroll bar for scrolling.
  2395. int firstVisible = getFirstVisibleRowIndex();
  2396. int lastVisible = getLastVisibleRowIndex();
  2397. if (newRow < firstVisible || newRow > lastVisible) {
  2398. newRow = down ? lastVisible : firstVisible;
  2399. }
  2400. // Scroll by a little less than the visible area to
  2401. // account for the possibility that the top and the
  2402. // bottom row are only partially visible.
  2403. int moveFocusBy = Math.max(1,
  2404. lastVisible - firstVisible - 1);
  2405. moveFocusBy *= down ? 1 : -1;
  2406. newRow += moveFocusBy;
  2407. newRow = Math.max(0, Math
  2408. .min(newContainer.getRowCount() - 1, newRow));
  2409. }
  2410. break;
  2411. default:
  2412. return;
  2413. }
  2414. if (newContainer != containerWithFocus) {
  2415. if (newContainer == escalator.getBody()) {
  2416. newRow = lastFocusedBodyRow;
  2417. } else if (newContainer == escalator.getHeader()) {
  2418. newRow = lastFocusedHeaderRow;
  2419. } else {
  2420. newRow = lastFocusedFooterRow;
  2421. }
  2422. } else if (newRow < 0) {
  2423. newContainer = getPreviousContainer(newContainer);
  2424. if (newContainer == containerWithFocus) {
  2425. newRow = 0;
  2426. } else if (newContainer == escalator.getBody()) {
  2427. newRow = getLastVisibleRowIndex();
  2428. } else {
  2429. newRow = newContainer.getRowCount() - 1;
  2430. }
  2431. } else if (newRow >= containerWithFocus.getRowCount()) {
  2432. newContainer = getNextContainer(newContainer);
  2433. if (newContainer == containerWithFocus) {
  2434. newRow = containerWithFocus.getRowCount() - 1;
  2435. } else if (newContainer == escalator.getBody()) {
  2436. newRow = getFirstVisibleRowIndex();
  2437. } else {
  2438. newRow = 0;
  2439. }
  2440. }
  2441. if (newContainer.getRowCount() == 0) {
  2442. /*
  2443. * There are no rows in the container. Can't change the
  2444. * focused cell.
  2445. */
  2446. return;
  2447. }
  2448. event.preventDefault();
  2449. event.stopPropagation();
  2450. setCellFocus(newRow, newColumn, newContainer);
  2451. }
  2452. }
  2453. private RowContainer getPreviousContainer(RowContainer current) {
  2454. if (current == escalator.getFooter()) {
  2455. current = escalator.getBody();
  2456. } else if (current == escalator.getBody()) {
  2457. current = escalator.getHeader();
  2458. } else {
  2459. return current;
  2460. }
  2461. if (current.getRowCount() == 0) {
  2462. return getPreviousContainer(current);
  2463. }
  2464. return current;
  2465. }
  2466. private RowContainer getNextContainer(RowContainer current) {
  2467. if (current == escalator.getHeader()) {
  2468. current = escalator.getBody();
  2469. } else if (current == escalator.getBody()) {
  2470. current = escalator.getFooter();
  2471. } else {
  2472. return current;
  2473. }
  2474. if (current.getRowCount() == 0) {
  2475. return getNextContainer(current);
  2476. }
  2477. return current;
  2478. }
  2479. private void refreshRow(int row) {
  2480. containerWithFocus.refreshRows(row, 1);
  2481. }
  2482. /**
  2483. * Offsets the focused cell's range.
  2484. *
  2485. * @param offset
  2486. * offset for fixing focused cell's range
  2487. */
  2488. public void offsetRangeBy(int offset) {
  2489. cellFocusRange = cellFocusRange.offsetBy(offset);
  2490. }
  2491. /**
  2492. * Informs {@link CellFocusHandler} that certain range of rows has been
  2493. * added to the Grid body. {@link CellFocusHandler} will fix indices
  2494. * accordingly.
  2495. *
  2496. * @param added
  2497. * a range of added rows
  2498. */
  2499. public void rowsAddedToBody(Range added) {
  2500. boolean bodyHasFocus = containerWithFocus == escalator.getBody();
  2501. boolean insertionIsAboveFocusedCell = added
  2502. .getStart() <= rowWithFocus;
  2503. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  2504. rowWithFocus += added.length();
  2505. rowWithFocus = Math.min(rowWithFocus,
  2506. escalator.getBody().getRowCount() - 1);
  2507. refreshRow(rowWithFocus);
  2508. }
  2509. }
  2510. /**
  2511. * Informs {@link CellFocusHandler} that certain range of rows has been
  2512. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  2513. * accordingly.
  2514. *
  2515. * @param removed
  2516. * a range of removed rows
  2517. */
  2518. public void rowsRemovedFromBody(Range removed) {
  2519. if (containerWithFocus != escalator.getBody()) {
  2520. return;
  2521. } else if (!removed.contains(rowWithFocus)) {
  2522. if (removed.getStart() > rowWithFocus) {
  2523. return;
  2524. }
  2525. rowWithFocus = rowWithFocus - removed.length();
  2526. } else {
  2527. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  2528. rowWithFocus = removed.getStart();
  2529. } else if (removed.getStart() > 0) {
  2530. rowWithFocus = removed.getStart() - 1;
  2531. } else {
  2532. if (escalator.getHeader().getRowCount() > 0) {
  2533. rowWithFocus = Math.min(lastFocusedHeaderRow,
  2534. escalator.getHeader().getRowCount() - 1);
  2535. containerWithFocus = escalator.getHeader();
  2536. } else if (escalator.getFooter().getRowCount() > 0) {
  2537. rowWithFocus = Math.min(lastFocusedFooterRow,
  2538. escalator.getFooter().getRowCount() - 1);
  2539. containerWithFocus = escalator.getFooter();
  2540. }
  2541. }
  2542. }
  2543. refreshRow(rowWithFocus);
  2544. }
  2545. }
  2546. private final List<GridEventHandler<T>> browserEventHandlers = new ArrayList<GridEventHandler<T>>();
  2547. private CellStyleGenerator<T> cellStyleGenerator;
  2548. private RowStyleGenerator<T> rowStyleGenerator;
  2549. private RowReference<T> rowReference = new RowReference<T>(this);
  2550. private CellReference<T> cellReference = new CellReference<T>(rowReference);
  2551. private RendererCellReference rendererCellReference = new RendererCellReference(
  2552. (RowReference<Object>) rowReference);
  2553. public final class SelectionColumn extends Column<Boolean, T>
  2554. implements GridEnabledHandler {
  2555. private boolean initDone = false;
  2556. private boolean selected = false;
  2557. private CheckBox selectAllCheckBox;
  2558. private boolean userSelectionAllowed = true;
  2559. private boolean enabled = true;
  2560. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  2561. super(selectColumnRenderer);
  2562. addEnabledHandler(this);
  2563. }
  2564. void initDone() {
  2565. setWidth(-1);
  2566. setEditable(false);
  2567. setResizable(false);
  2568. initDone = true;
  2569. }
  2570. @Override
  2571. protected void setDefaultHeaderContent(HeaderCell selectionCell) {
  2572. /*
  2573. * TODO: Currently the select all check box is shown when multi
  2574. * selection is in use. This might result in malfunctions if no
  2575. * SelectAllHandlers are present.
  2576. *
  2577. * Later on this could be fixed so that it check such handlers
  2578. * exist.
  2579. */
  2580. final SelectionModel.Multi<T> model = (Multi<T>) getSelectionModel();
  2581. if (selectAllCheckBox == null) {
  2582. selectAllCheckBox = GWT.create(CheckBox.class);
  2583. selectAllCheckBox.setEnabled(enabled && userSelectionAllowed);
  2584. selectAllCheckBox.setStylePrimaryName(
  2585. getStylePrimaryName() + SELECT_ALL_CHECKBOX_CLASSNAME);
  2586. selectAllCheckBox.addValueChangeHandler(
  2587. new ValueChangeHandler<Boolean>() {
  2588. @Override
  2589. public void onValueChange(
  2590. ValueChangeEvent<Boolean> event) {
  2591. if (!isUserSelectionAllowed()) {
  2592. return;
  2593. }
  2594. if (event.getValue()) {
  2595. fireEvent(new SelectAllEvent<T>(model));
  2596. selected = true;
  2597. } else {
  2598. model.deselectAll();
  2599. selected = false;
  2600. }
  2601. }
  2602. });
  2603. selectAllCheckBox.setValue(selected);
  2604. addHeaderClickHandler(new HeaderClickHandler() {
  2605. @Override
  2606. public void onClick(GridClickEvent event) {
  2607. if (!userSelectionAllowed) {
  2608. return;
  2609. }
  2610. CellReference<?> targetCell = event.getTargetCell();
  2611. int defaultRowIndex = getHeader().getRows()
  2612. .indexOf(getDefaultHeaderRow());
  2613. if (targetCell.getColumnIndex() == 0 && targetCell
  2614. .getRowIndex() == defaultRowIndex) {
  2615. selectAllCheckBox.setValue(
  2616. !selectAllCheckBox.getValue(), true);
  2617. }
  2618. }
  2619. });
  2620. // Select all with space when "select all" cell is active
  2621. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  2622. @Override
  2623. public void onKeyUp(GridKeyUpEvent event) {
  2624. if (event.getNativeKeyCode() != KeyCodes.KEY_SPACE) {
  2625. return;
  2626. }
  2627. if (!isUserSelectionAllowed()) {
  2628. return;
  2629. }
  2630. HeaderRow targetHeaderRow = getHeader()
  2631. .getRow(event.getFocusedCell().getRowIndex());
  2632. if (!targetHeaderRow.isDefault()) {
  2633. return;
  2634. }
  2635. if (event.getFocusedCell()
  2636. .getColumn() == SelectionColumn.this) {
  2637. // Send events to ensure state is updated
  2638. selectAllCheckBox.setValue(
  2639. !selectAllCheckBox.getValue(), true);
  2640. }
  2641. }
  2642. });
  2643. } else {
  2644. for (HeaderRow row : header.getRows()) {
  2645. if (row.getCell(this)
  2646. .getType() == GridStaticCellType.WIDGET) {
  2647. // Detach from old header.
  2648. row.getCell(this).setText("");
  2649. }
  2650. }
  2651. }
  2652. selectionCell.setWidget(selectAllCheckBox);
  2653. }
  2654. @Override
  2655. public Column<Boolean, T> setWidth(double pixels) {
  2656. if (pixels != getWidth() && initDone) {
  2657. throw new UnsupportedOperationException("The selection "
  2658. + "column cannot be modified after init");
  2659. } else {
  2660. super.setWidth(pixels);
  2661. }
  2662. return this;
  2663. }
  2664. @Override
  2665. public Boolean getValue(T row) {
  2666. return Boolean.valueOf(isSelected(row));
  2667. }
  2668. @Override
  2669. public Column<Boolean, T> setExpandRatio(int ratio) {
  2670. throw new UnsupportedOperationException(
  2671. "can't change the expand ratio of the selection column");
  2672. }
  2673. @Override
  2674. public int getExpandRatio() {
  2675. return 0;
  2676. }
  2677. @Override
  2678. public Column<Boolean, T> setMaximumWidth(double pixels) {
  2679. throw new UnsupportedOperationException(
  2680. "can't change the maximum width of the selection column");
  2681. }
  2682. @Override
  2683. public double getMaximumWidth() {
  2684. return -1;
  2685. }
  2686. @Override
  2687. public Column<Boolean, T> setMinimumWidth(double pixels) {
  2688. throw new UnsupportedOperationException(
  2689. "can't change the minimum width of the selection column");
  2690. }
  2691. @Override
  2692. public double getMinimumWidth() {
  2693. return -1;
  2694. }
  2695. @Override
  2696. public Column<Boolean, T> setEditable(boolean editable) {
  2697. if (initDone) {
  2698. throw new UnsupportedOperationException(
  2699. "can't set the selection column editable");
  2700. }
  2701. super.setEditable(editable);
  2702. return this;
  2703. }
  2704. /**
  2705. * Sets whether the selection column is enabled.
  2706. *
  2707. * @since 7.7
  2708. * @param enabled
  2709. * <code>true</code> to enable the column, <code>false</code>
  2710. * to disable it.
  2711. */
  2712. public void setEnabled(boolean enabled) {
  2713. this.enabled = enabled;
  2714. if (selectAllCheckBox != null) {
  2715. selectAllCheckBox.setEnabled(enabled && userSelectionAllowed);
  2716. }
  2717. }
  2718. @Override
  2719. public void onEnabled(boolean enabled) {
  2720. setEnabled(enabled);
  2721. }
  2722. /**
  2723. * Sets whether the user is allowed to change the selection.
  2724. *
  2725. * @param userSelectionAllowed
  2726. * <code>true</code> if the user is allowed to change the
  2727. * selection, <code>false</code> otherwise
  2728. * @since 7.7.7
  2729. */
  2730. public void setUserSelectionAllowed(boolean userSelectionAllowed) {
  2731. if (userSelectionAllowed == this.userSelectionAllowed) {
  2732. return;
  2733. }
  2734. this.userSelectionAllowed = userSelectionAllowed;
  2735. // Update checkbox state
  2736. setEnabled(enabled);
  2737. // Re-render select checkboxes
  2738. getEscalator().getBody().refreshRows(0,
  2739. getEscalator().getBody().getRowCount());
  2740. }
  2741. }
  2742. /**
  2743. * Helper class for performing sorting through the user interface. Controls
  2744. * the sort() method, reporting USER as the event originator. This is a
  2745. * completely internal class, and is, as such, safe to re-name should a more
  2746. * descriptive name come to mind.
  2747. */
  2748. private final class UserSorter {
  2749. private final Timer timer;
  2750. private boolean scheduledMultisort;
  2751. private Column<?, T> column;
  2752. private UserSorter() {
  2753. timer = new Timer() {
  2754. @Override
  2755. public void run() {
  2756. UserSorter.this.sort(column, scheduledMultisort);
  2757. }
  2758. };
  2759. }
  2760. /**
  2761. * Toggle sorting for a cell. If the multisort parameter is set to true,
  2762. * the cell's sort order is modified as a natural part of a multi-sort
  2763. * chain. If false, the sorting order is set to ASCENDING for that
  2764. * cell's column. If that column was already the only sorted column in
  2765. * the Grid, the sort direction is flipped.
  2766. *
  2767. * @param cell
  2768. * a valid cell reference
  2769. * @param multisort
  2770. * whether the sort command should act as a multi-sort stack
  2771. * or not
  2772. */
  2773. public void sort(Column<?, ?> column, boolean multisort) {
  2774. if (!columns.contains(column)) {
  2775. throw new IllegalArgumentException(
  2776. "Given column is not a column in this grid. "
  2777. + column.toString());
  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.getRowCount() == 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 HashMap<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 StringBuffer buf = new StringBuffer();
  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. }
  3791. // Check if the drop marker shouldn't be shown at all
  3792. else if (dropMarkerLeft < frozenColumnsWidth
  3793. || dropMarkerLeft > Math.min(rightBoundaryForDrag,
  3794. escalator.getInnerWidth())
  3795. || dropMarkerLeft < 0) {
  3796. dropMarkerLeft = -10000000;
  3797. }
  3798. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  3799. }
  3800. private void resolveDragElementHorizontalPosition(final int clientX) {
  3801. double left = clientX - table.getAbsoluteLeft();
  3802. // Do not show the drag element beyond a spanned header cell
  3803. // limitation
  3804. final Double leftBound = possibleDropPositions.firstKey();
  3805. final Double rightBound = possibleDropPositions.lastKey();
  3806. final double scrollLeft = getScrollLeft();
  3807. if (left + scrollLeft < leftBound) {
  3808. left = leftBound - scrollLeft + autoScrollX;
  3809. } else if (left + scrollLeft > rightBound) {
  3810. left = rightBound - scrollLeft + autoScrollX;
  3811. }
  3812. // Do not show the drag element beyond the grid
  3813. final double sidebarBoundary = getSidebarBoundaryComparedTo(left);
  3814. final double gridBoundary = escalator.getInnerWidth();
  3815. final double rightBoundary = Math.min(sidebarBoundary,
  3816. gridBoundary);
  3817. // Do not show on left of the frozen columns (even if scrolled)
  3818. final int frozenColumnsWidth = (int) autoScroller
  3819. .getFrozenColumnsWidth();
  3820. left = Math.max(frozenColumnsWidth, Math.min(left, rightBoundary));
  3821. left -= dragElement.getClientWidth() / 2;
  3822. dragElement.getStyle().setLeft(left, Unit.PX);
  3823. }
  3824. private boolean isSidebarOnDraggedRow() {
  3825. return eventCell.getRowIndex() == 0 && sidebar.isInDOM()
  3826. && !sidebar.isOpen();
  3827. }
  3828. /**
  3829. * Returns the sidebar left coordinate, in relation to the grid. Or
  3830. * Double.MAX_VALUE if it doesn't cause a boundary.
  3831. */
  3832. private double getSidebarBoundaryComparedTo(double left) {
  3833. if (isSidebarOnDraggedRow()) {
  3834. double absoluteLeft = left + getElement().getAbsoluteLeft();
  3835. double sidebarLeft = sidebar.getElement().getAbsoluteLeft();
  3836. double diff = absoluteLeft - sidebarLeft;
  3837. if (diff > 0) {
  3838. return left - diff;
  3839. }
  3840. }
  3841. return Double.MAX_VALUE;
  3842. }
  3843. @Override
  3844. public boolean onDragStart(Event e) {
  3845. calculatePossibleDropPositions();
  3846. if (possibleDropPositions.isEmpty()) {
  3847. return false;
  3848. }
  3849. initHeaderDragElementDOM();
  3850. // needs to clone focus and sorting indicators too (UX)
  3851. dragElement = DOM.clone(eventCell.getElement(), true);
  3852. dragElement.getStyle().clearWidth();
  3853. dropMarker.getStyle().setProperty("height",
  3854. dragElement.getStyle().getHeight());
  3855. tableHeader.appendChild(dragElement);
  3856. // mark the column being dragged for styling
  3857. eventCell.getElement().addClassName("dragged");
  3858. // mark the floating cell, for styling & testing
  3859. dragElement.addClassName("dragged-column-header");
  3860. // start the auto scroll handler
  3861. autoScroller.setScrollArea(60);
  3862. autoScroller.start(e, ScrollAxis.HORIZONTAL, autoScrollerCallback);
  3863. return true;
  3864. }
  3865. @Override
  3866. public void onDragEnd() {
  3867. table.removeFromParent();
  3868. dragElement.removeFromParent();
  3869. eventCell.getElement().removeClassName("dragged");
  3870. }
  3871. @Override
  3872. public void onDrop() {
  3873. final int draggedColumnIndex = eventCell.getColumnIndex();
  3874. final int colspan = header.getRow(eventCell.getRowIndex())
  3875. .getCell(eventCell.getColumn()).getColspan();
  3876. if (latestColumnDropIndex != draggedColumnIndex
  3877. && latestColumnDropIndex != draggedColumnIndex + colspan) {
  3878. List<Column<?, T>> columns = getColumns();
  3879. List<Column<?, T>> reordered = new ArrayList<Column<?, T>>();
  3880. if (draggedColumnIndex < latestColumnDropIndex) {
  3881. reordered.addAll(columns.subList(0, draggedColumnIndex));
  3882. reordered.addAll(
  3883. columns.subList(draggedColumnIndex + colspan,
  3884. latestColumnDropIndex));
  3885. reordered.addAll(columns.subList(draggedColumnIndex,
  3886. draggedColumnIndex + colspan));
  3887. reordered.addAll(columns.subList(latestColumnDropIndex,
  3888. columns.size()));
  3889. } else {
  3890. reordered.addAll(columns.subList(0, latestColumnDropIndex));
  3891. reordered.addAll(columns.subList(draggedColumnIndex,
  3892. draggedColumnIndex + colspan));
  3893. reordered.addAll(columns.subList(latestColumnDropIndex,
  3894. draggedColumnIndex));
  3895. reordered.addAll(columns.subList(
  3896. draggedColumnIndex + colspan, columns.size()));
  3897. }
  3898. reordered.remove(selectionColumn); // since setColumnOrder will
  3899. // add it anyway!
  3900. // capture focused cell column before reorder
  3901. Cell focusedCell = cellFocusHandler.getFocusedCell();
  3902. if (focusedCell != null) {
  3903. // take hidden columns into account
  3904. focusedColumnIndex = getColumns()
  3905. .indexOf(getVisibleColumn(focusedCell.getColumn()));
  3906. }
  3907. Column<?, T>[] array = reordered
  3908. .toArray(new Column[reordered.size()]);
  3909. setColumnOrder(array);
  3910. transferCellFocusOnDrop();
  3911. } // else no reordering
  3912. }
  3913. private void transferCellFocusOnDrop() {
  3914. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  3915. if (focusedCell != null) {
  3916. final int focusedColumnIndexDOM = focusedCell.getColumn();
  3917. final int focusedRowIndex = focusedCell.getRow();
  3918. final int draggedColumnIndex = eventCell.getColumnIndex();
  3919. // transfer focus if it was effected by the new column order
  3920. final RowContainer rowContainer = escalator
  3921. .findRowContainer(focusedCell.getElement());
  3922. if (focusedColumnIndex == draggedColumnIndex) {
  3923. // move with the dragged column
  3924. int adjustedDropIndex = latestColumnDropIndex > draggedColumnIndex
  3925. ? latestColumnDropIndex - 1 : 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. }
  4045. else { // 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 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(Column.this.toString() + ": "
  4136. + 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. * @param immediately
  4659. * <code>true</code> if the widths should be executed
  4660. * immediately (ignoring lazy loading completely), or
  4661. * <code>false</code> if the command should be run after a
  4662. * while (duplicate non-immediately invocations are ignored).
  4663. * @return this column
  4664. */
  4665. public Column<C, T> setMaximumWidth(double pixels) {
  4666. final double minwidth = getMinimumWidth();
  4667. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  4668. throw new IllegalArgumentException("New maximum width ("
  4669. + pixels + ") was less than minimum width (" + minwidth
  4670. + ")");
  4671. }
  4672. if (maximumWidthPx != pixels) {
  4673. maximumWidthPx = pixels;
  4674. scheduleColumnWidthRecalculator();
  4675. }
  4676. return this;
  4677. }
  4678. /**
  4679. * Sets the ratio with which the column expands.
  4680. * <p>
  4681. * By default, all columns expand equally (treated as if all of them had
  4682. * an expand ratio of 1). Once at least one column gets a defined expand
  4683. * ratio, the implicit expand ratio is removed, and only the defined
  4684. * expand ratios are taken into account.
  4685. * <p>
  4686. * If a column has a defined width ({@link #setWidth(double)}), it
  4687. * overrides this method's effects.
  4688. * <p>
  4689. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  4690. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  4691. * as wide as its contents requires</strong>. The column with a ratio of
  4692. * 1 is as wide as it needs, <strong>plus a third of any excess
  4693. * space</strong>, bceause we have 3 parts total, and this column
  4694. * reservs only one of those. The column with a ratio of 2, is as wide
  4695. * as it needs to be, <strong>plus two thirds</strong> of the excess
  4696. * width.
  4697. * <p>
  4698. * This action is done "finally", once the current execution loop
  4699. * returns. This is done to reduce overhead of unintentionally always
  4700. * recalculate all columns, when modifying several columns at once.
  4701. *
  4702. * @param expandRatio
  4703. * the expand ratio of this column. {@code 0} to not have it
  4704. * expand at all. A negative number to clear the expand
  4705. * value.
  4706. * @return this column
  4707. */
  4708. public Column<C, T> setExpandRatio(int ratio) {
  4709. if (expandRatio != ratio) {
  4710. expandRatio = ratio;
  4711. scheduleColumnWidthRecalculator();
  4712. }
  4713. return this;
  4714. }
  4715. /**
  4716. * Clears the column's expand ratio.
  4717. * <p>
  4718. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  4719. *
  4720. * @return this column
  4721. */
  4722. public Column<C, T> clearExpandRatio() {
  4723. return setExpandRatio(-1);
  4724. }
  4725. /**
  4726. * Gets the minimum width for this column.
  4727. *
  4728. * @return the minimum width for this column
  4729. * @see #setMinimumWidth(double)
  4730. */
  4731. public double getMinimumWidth() {
  4732. return minimumWidthPx;
  4733. }
  4734. /**
  4735. * Gets the maximum width for this column.
  4736. *
  4737. * @return the maximum width for this column
  4738. * @see #setMaximumWidth(double)
  4739. */
  4740. public double getMaximumWidth() {
  4741. return maximumWidthPx;
  4742. }
  4743. /**
  4744. * Gets the expand ratio for this column.
  4745. *
  4746. * @return the expand ratio for this column
  4747. * @see #setExpandRatio(int)
  4748. */
  4749. public int getExpandRatio() {
  4750. return expandRatio;
  4751. }
  4752. /**
  4753. * Sets whether the values in this column should be editable by the user
  4754. * when the row editor is active. By default columns are editable.
  4755. *
  4756. * @param editable
  4757. * {@code true} to set this column editable, {@code false}
  4758. * otherwise
  4759. * @return this column
  4760. *
  4761. * @throws IllegalStateException
  4762. * if the editor is currently active
  4763. *
  4764. * @see Grid#editRow(int)
  4765. * @see Grid#isEditorActive()
  4766. */
  4767. public Column<C, T> setEditable(boolean editable) {
  4768. if (editable != this.editable && grid.isEditorActive()) {
  4769. throw new IllegalStateException(
  4770. "Cannot change column editable status while the editor is active");
  4771. }
  4772. this.editable = editable;
  4773. return this;
  4774. }
  4775. /**
  4776. * Returns whether the values in this column are editable by the user
  4777. * when the row editor is active.
  4778. *
  4779. * @return {@code true} if this column is editable, {@code false}
  4780. * otherwise
  4781. *
  4782. * @see #setEditable(boolean)
  4783. */
  4784. public boolean isEditable() {
  4785. return editable;
  4786. }
  4787. private void scheduleColumnWidthRecalculator() {
  4788. if (grid != null) {
  4789. grid.recalculateColumnWidths();
  4790. } else {
  4791. /*
  4792. * NOOP
  4793. *
  4794. * Since setGrid() will call reapplyWidths as the colum is
  4795. * attached to a grid, it will call setWidth, which, in turn,
  4796. * will call this method again. Therefore, it's guaranteed that
  4797. * the recalculation is scheduled eventually, once the column is
  4798. * attached to a grid.
  4799. */
  4800. }
  4801. }
  4802. /**
  4803. * Resets the default header cell contents to column header captions.
  4804. *
  4805. * @since 7.5.1
  4806. * @param cell
  4807. * default header cell for this column
  4808. */
  4809. protected void setDefaultHeaderContent(HeaderCell cell) {
  4810. cell.setText(headerCaption);
  4811. }
  4812. }
  4813. protected class BodyUpdater implements EscalatorUpdater {
  4814. @Override
  4815. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  4816. int rowIndex = row.getRow();
  4817. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  4818. row.getElement());
  4819. for (FlyweightCell cell : cellsToAttach) {
  4820. Renderer<?> renderer = findRenderer(cell);
  4821. if (renderer instanceof ComplexRenderer) {
  4822. try {
  4823. Column<?, T> column = getVisibleColumn(
  4824. cell.getColumn());
  4825. rendererCellReference.set(cell,
  4826. getColumns().indexOf(column), column);
  4827. ((ComplexRenderer<?>) renderer)
  4828. .init(rendererCellReference);
  4829. } catch (RuntimeException e) {
  4830. getLogger().log(Level.SEVERE,
  4831. "Error initing cell in column "
  4832. + cell.getColumn(),
  4833. e);
  4834. }
  4835. }
  4836. }
  4837. }
  4838. @Override
  4839. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  4840. for (FlyweightCell cell : attachedCells) {
  4841. Renderer<?> renderer = findRenderer(cell);
  4842. if (renderer instanceof WidgetRenderer) {
  4843. try {
  4844. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  4845. Widget widget = widgetRenderer.createWidget();
  4846. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  4847. assert widget
  4848. .getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  4849. assert cell.getElement()
  4850. .getChildCount() == 0 : "Cell content should be empty when adding Widget";
  4851. // Physical attach
  4852. cell.getElement().appendChild(widget.getElement());
  4853. // Logical attach
  4854. setParent(widget, Grid.this);
  4855. } catch (RuntimeException e) {
  4856. getLogger().log(Level.SEVERE,
  4857. "Error attaching child widget in column "
  4858. + cell.getColumn(),
  4859. e);
  4860. }
  4861. }
  4862. }
  4863. }
  4864. @Override
  4865. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4866. int rowIndex = row.getRow();
  4867. TableRowElement rowElement = row.getElement();
  4868. T rowData = dataSource.getRow(rowIndex);
  4869. boolean hasData = rowData != null;
  4870. /*
  4871. * TODO could be more efficient to build a list of all styles that
  4872. * should be used and update the element only once instead of
  4873. * attempting to update only the ones that have changed.
  4874. */
  4875. // Assign stylename for rows with data
  4876. boolean usedToHaveData = rowElement
  4877. .hasClassName(rowHasDataStyleName);
  4878. if (usedToHaveData != hasData) {
  4879. setStyleName(rowElement, rowHasDataStyleName, hasData);
  4880. }
  4881. boolean isEvenIndex = row.getRow() % 2 == 0;
  4882. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  4883. rowReference.set(rowIndex, rowData, rowElement);
  4884. if (hasData) {
  4885. setStyleName(rowElement, rowSelectedStyleName,
  4886. isSelected(rowData));
  4887. if (rowStyleGenerator != null) {
  4888. try {
  4889. String rowStylename = rowStyleGenerator
  4890. .getStyle(rowReference);
  4891. setCustomStyleName(rowElement, rowStylename);
  4892. } catch (RuntimeException e) {
  4893. getLogger().log(Level.SEVERE,
  4894. "Error generating styles for row "
  4895. + row.getRow(),
  4896. e);
  4897. }
  4898. } else {
  4899. // Remove in case there was a generator previously
  4900. setCustomStyleName(rowElement, null);
  4901. }
  4902. } else if (usedToHaveData) {
  4903. setStyleName(rowElement, rowSelectedStyleName, false);
  4904. setCustomStyleName(rowElement, null);
  4905. }
  4906. cellFocusHandler.updateFocusedRowStyle(row);
  4907. for (FlyweightCell cell : cellsToUpdate) {
  4908. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4909. final int columnIndex = getColumns().indexOf(column);
  4910. assert column != null : "Column was not found from cell ("
  4911. + cell.getColumn() + "," + cell.getRow() + ")";
  4912. cellFocusHandler.updateFocusedCellStyle(cell,
  4913. escalator.getBody());
  4914. if (hasData && cellStyleGenerator != null) {
  4915. try {
  4916. cellReference.set(cell.getColumn(), columnIndex,
  4917. column);
  4918. String generatedStyle = cellStyleGenerator
  4919. .getStyle(cellReference);
  4920. setCustomStyleName(cell.getElement(), generatedStyle);
  4921. } catch (RuntimeException e) {
  4922. getLogger().log(Level.SEVERE,
  4923. "Error generating style for cell in column "
  4924. + cell.getColumn(),
  4925. e);
  4926. }
  4927. } else if (hasData || usedToHaveData) {
  4928. setCustomStyleName(cell.getElement(), null);
  4929. }
  4930. Renderer renderer = column.getRenderer();
  4931. try {
  4932. rendererCellReference.set(cell, columnIndex, column);
  4933. if (renderer instanceof ComplexRenderer) {
  4934. // Hide cell content if needed
  4935. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  4936. if (hasData) {
  4937. if (!usedToHaveData) {
  4938. // Prepare cell for rendering
  4939. clxRenderer.setContentVisible(
  4940. rendererCellReference, true);
  4941. }
  4942. Object value = column.getValue(rowData);
  4943. clxRenderer.render(rendererCellReference, value);
  4944. } else {
  4945. // Prepare cell for no data
  4946. clxRenderer.setContentVisible(rendererCellReference,
  4947. false);
  4948. }
  4949. } else if (hasData) {
  4950. // Simple renderers just render
  4951. Object value = column.getValue(rowData);
  4952. renderer.render(rendererCellReference, value);
  4953. } else {
  4954. // Clear cell if there is no data
  4955. cell.getElement().removeAllChildren();
  4956. }
  4957. } catch (RuntimeException e) {
  4958. getLogger().log(Level.SEVERE,
  4959. "Error rendering cell in column "
  4960. + cell.getColumn(),
  4961. e);
  4962. }
  4963. }
  4964. }
  4965. @Override
  4966. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  4967. for (FlyweightCell cell : cellsToDetach) {
  4968. Renderer<?> renderer = findRenderer(cell);
  4969. if (renderer instanceof WidgetRenderer) {
  4970. try {
  4971. Widget w = WidgetUtil.findWidget(
  4972. cell.getElement().getFirstChildElement(), null);
  4973. if (w != null) {
  4974. // Logical detach
  4975. setParent(w, null);
  4976. // Physical detach
  4977. cell.getElement().removeChild(w.getElement());
  4978. }
  4979. } catch (RuntimeException e) {
  4980. getLogger().log(Level.SEVERE,
  4981. "Error detaching widget in column "
  4982. + cell.getColumn(),
  4983. e);
  4984. }
  4985. }
  4986. }
  4987. }
  4988. @Override
  4989. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  4990. int rowIndex = row.getRow();
  4991. // Passing null row data since it might not exist in the data source
  4992. // any more
  4993. rowReference.set(rowIndex, null, row.getElement());
  4994. for (FlyweightCell cell : detachedCells) {
  4995. Renderer<?> renderer = findRenderer(cell);
  4996. if (renderer instanceof ComplexRenderer) {
  4997. try {
  4998. Column<?, T> column = getVisibleColumn(
  4999. cell.getColumn());
  5000. rendererCellReference.set(cell,
  5001. getColumns().indexOf(column), column);
  5002. ((ComplexRenderer) renderer)
  5003. .destroy(rendererCellReference);
  5004. } catch (RuntimeException e) {
  5005. getLogger().log(Level.SEVERE,
  5006. "Error destroying cell in column "
  5007. + cell.getColumn(),
  5008. e);
  5009. }
  5010. }
  5011. }
  5012. }
  5013. }
  5014. protected class StaticSectionUpdater implements EscalatorUpdater {
  5015. private StaticSection<?> section;
  5016. private RowContainer container;
  5017. public StaticSectionUpdater(StaticSection<?> section,
  5018. RowContainer container) {
  5019. super();
  5020. this.section = section;
  5021. this.container = container;
  5022. }
  5023. @Override
  5024. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  5025. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  5026. final List<Column<?, T>> columns = getVisibleColumns();
  5027. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  5028. for (FlyweightCell cell : cellsToUpdate) {
  5029. final StaticSection.StaticCell metadata = staticRow
  5030. .getCell(columns.get(cell.getColumn()));
  5031. // Decorate default row with sorting indicators
  5032. if (staticRow instanceof HeaderRow) {
  5033. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow,
  5034. cell);
  5035. }
  5036. // Assign colspan to cell before rendering
  5037. cell.setColSpan(metadata.getColspan());
  5038. Element td = cell.getElement();
  5039. td.removeAllChildren();
  5040. setCustomStyleName(td, metadata.getStyleName());
  5041. Element content;
  5042. // Wrap text or html content in default header to isolate
  5043. // the content from the possible column resize drag handle
  5044. // next to it
  5045. if (metadata.getType() != GridStaticCellType.WIDGET) {
  5046. content = DOM.createDiv();
  5047. if (staticRow instanceof HeaderRow) {
  5048. content.setClassName(getStylePrimaryName()
  5049. + "-column-header-content");
  5050. if (((HeaderRow) staticRow).isDefault()) {
  5051. content.setClassName(content.getClassName() + " "
  5052. + getStylePrimaryName()
  5053. + "-column-default-header-content");
  5054. }
  5055. } else if (staticRow instanceof FooterRow) {
  5056. content.setClassName(getStylePrimaryName()
  5057. + "-column-footer-content");
  5058. } else {
  5059. getLogger().severe("Unhandled static row type "
  5060. + staticRow.getClass().getCanonicalName());
  5061. }
  5062. td.appendChild(content);
  5063. } else {
  5064. content = td;
  5065. }
  5066. switch (metadata.getType()) {
  5067. case TEXT:
  5068. content.setInnerText(metadata.getText());
  5069. break;
  5070. case HTML:
  5071. content.setInnerHTML(metadata.getHtml());
  5072. break;
  5073. case WIDGET:
  5074. preDetach(row, Arrays.asList(cell));
  5075. content.setInnerHTML("");
  5076. postAttach(row, Arrays.asList(cell));
  5077. break;
  5078. }
  5079. // XXX: Should add only once in preAttach/postAttach or when
  5080. // resizable status changes
  5081. // Only add resize handles to default header row for now
  5082. if (columns.get(cell.getColumn()).isResizable()
  5083. && staticRow instanceof HeaderRow
  5084. && ((HeaderRow) staticRow).isDefault()) {
  5085. final DivElement resizeElement = Document.get()
  5086. .createDivElement();
  5087. resizeElement.addClassName(getStylePrimaryName()
  5088. + "-column-resize-simple-indicator");
  5089. final int column = cell.getColumn();
  5090. final DragHandle dragger = new DragHandle(
  5091. getStylePrimaryName() + "-column-resize-handle");
  5092. dragger.addTo(td);
  5093. // Common functionality for drag handle callback
  5094. // implementations
  5095. abstract class AbstractDHCallback
  5096. implements DragHandleCallback {
  5097. protected Column<?, T> col = getVisibleColumn(column);
  5098. protected double initialWidth = 0;
  5099. protected double minCellWidth;
  5100. protected double width;
  5101. protected void dragStarted() {
  5102. initialWidth = col.getWidthActual();
  5103. width = initialWidth;
  5104. minCellWidth = escalator.getMinCellWidth(
  5105. getVisibleColumns().indexOf(col));
  5106. for (Column<?, T> c : getVisibleColumns()) {
  5107. if (selectionColumn == c) {
  5108. // Don't modify selection column.
  5109. continue;
  5110. }
  5111. if (c.getWidth() < 0) {
  5112. c.setWidth(c.getWidthActual());
  5113. fireEvent(new ColumnResizeEvent<T>(c));
  5114. }
  5115. }
  5116. WidgetUtil.setTextSelectionEnabled(getElement(),
  5117. false);
  5118. }
  5119. protected void dragEnded() {
  5120. WidgetUtil.setTextSelectionEnabled(getElement(),
  5121. true);
  5122. }
  5123. }
  5124. final DragHandleCallback simpleResizeMode = new AbstractDHCallback() {
  5125. @Override
  5126. protected void dragEnded() {
  5127. super.dragEnded();
  5128. dragger.getElement().removeChild(resizeElement);
  5129. }
  5130. @Override
  5131. public void onStart() {
  5132. dragStarted();
  5133. dragger.getElement().appendChild(resizeElement);
  5134. resizeElement.getStyle().setLeft(
  5135. (dragger.getElement().getOffsetWidth()
  5136. - resizeElement.getOffsetWidth())
  5137. * .5,
  5138. Unit.PX);
  5139. resizeElement.getStyle().setHeight(
  5140. col.grid.getOffsetHeight(), Unit.PX);
  5141. }
  5142. @Override
  5143. public void onUpdate(double deltaX, double deltaY) {
  5144. width = Math.max(minCellWidth,
  5145. initialWidth + deltaX);
  5146. resizeElement.getStyle().setLeft(
  5147. (dragger.getElement().getOffsetWidth()
  5148. - resizeElement.getOffsetWidth())
  5149. * .5 + (width - initialWidth),
  5150. Unit.PX);
  5151. }
  5152. @Override
  5153. public void onCancel() {
  5154. dragEnded();
  5155. }
  5156. @Override
  5157. public void onComplete() {
  5158. dragEnded();
  5159. col.setWidth(width);
  5160. fireEvent(new ColumnResizeEvent<T>(col));
  5161. }
  5162. };
  5163. final DragHandleCallback animatedResizeMode = new AbstractDHCallback() {
  5164. @Override
  5165. public void onStart() {
  5166. dragStarted();
  5167. }
  5168. @Override
  5169. public void onUpdate(double deltaX, double deltaY) {
  5170. width = Math.max(minCellWidth,
  5171. initialWidth + deltaX);
  5172. col.setWidth(width);
  5173. }
  5174. @Override
  5175. public void onCancel() {
  5176. dragEnded();
  5177. col.setWidth(initialWidth);
  5178. }
  5179. @Override
  5180. public void onComplete() {
  5181. dragEnded();
  5182. col.setWidth(width);
  5183. fireEvent(new ColumnResizeEvent<T>(col));
  5184. }
  5185. };
  5186. // DragHandle gets assigned a 'master callback' that
  5187. // delegates
  5188. // functionality to the correct case-specific implementation
  5189. dragger.setCallback(new DragHandleCallback() {
  5190. private DragHandleCallback currentCallback;
  5191. @Override
  5192. public void onStart() {
  5193. switch (getColumnResizeMode()) {
  5194. case SIMPLE:
  5195. currentCallback = simpleResizeMode;
  5196. break;
  5197. case ANIMATED:
  5198. currentCallback = animatedResizeMode;
  5199. break;
  5200. default:
  5201. throw new UnsupportedOperationException(
  5202. "Support for current column resize mode is not yet implemented");
  5203. }
  5204. currentCallback.onStart();
  5205. }
  5206. @Override
  5207. public void onUpdate(double deltaX, double deltaY) {
  5208. currentCallback.onUpdate(deltaX, deltaY);
  5209. }
  5210. @Override
  5211. public void onCancel() {
  5212. currentCallback.onCancel();
  5213. }
  5214. @Override
  5215. public void onComplete() {
  5216. currentCallback.onComplete();
  5217. }
  5218. });
  5219. }
  5220. cellFocusHandler.updateFocusedCellStyle(cell, container);
  5221. }
  5222. }
  5223. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  5224. FlyweightCell cell) {
  5225. Element cellElement = cell.getElement();
  5226. boolean sortedBefore = cellElement.hasClassName("sort-asc")
  5227. || cellElement.hasClassName("sort-desc");
  5228. cleanup(cell);
  5229. if (!headerRow.isDefault()) {
  5230. // Nothing more to do if not in the default row
  5231. return;
  5232. }
  5233. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5234. SortOrder sortingOrder = getSortOrder(column);
  5235. boolean sortable = column.isSortable();
  5236. if (sortable) {
  5237. cellElement.addClassName("sortable");
  5238. }
  5239. if (!sortable || sortingOrder == null) {
  5240. // Only apply sorting indicators to sortable header columns
  5241. return;
  5242. }
  5243. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  5244. cellElement.addClassName("sort-asc");
  5245. } else {
  5246. cellElement.addClassName("sort-desc");
  5247. }
  5248. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  5249. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  5250. // Show sort order indicator if column is
  5251. // sorted and other sorted columns also exists.
  5252. cellElement.setAttribute("sort-order",
  5253. String.valueOf(sortIndex + 1));
  5254. }
  5255. if (!sortedBefore) {
  5256. verifyColumnWidth(column);
  5257. }
  5258. }
  5259. /**
  5260. * Sort indicator requires a bit more space from the cell than normally.
  5261. * This method check that the now sorted column has enough width.
  5262. *
  5263. * @param column
  5264. * sorted column
  5265. */
  5266. private void verifyColumnWidth(Column<?, T> column) {
  5267. int colIndex = getColumns().indexOf(column);
  5268. double minWidth = escalator.getMinCellWidth(colIndex);
  5269. if (column.getWidthActual() < minWidth) {
  5270. // Fix column size
  5271. escalator.getColumnConfiguration().setColumnWidth(colIndex,
  5272. minWidth);
  5273. fireEvent(new ColumnResizeEvent<T>(column));
  5274. }
  5275. }
  5276. /**
  5277. * Finds the sort order for this column
  5278. */
  5279. private SortOrder getSortOrder(Column<?, ?> column) {
  5280. for (SortOrder order : Grid.this.getSortOrder()) {
  5281. if (order.getColumn() == column) {
  5282. return order;
  5283. }
  5284. }
  5285. return null;
  5286. }
  5287. private void cleanup(FlyweightCell cell) {
  5288. Element cellElement = cell.getElement();
  5289. cellElement.removeAttribute("sort-order");
  5290. cellElement.removeClassName("sort-desc");
  5291. cellElement.removeClassName("sort-asc");
  5292. cellElement.removeClassName("sortable");
  5293. }
  5294. @Override
  5295. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5296. }
  5297. @Override
  5298. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5299. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  5300. List<Column<?, T>> columns = getVisibleColumns();
  5301. for (FlyweightCell cell : attachedCells) {
  5302. StaticSection.StaticCell metadata = gridRow
  5303. .getCell(columns.get(cell.getColumn()));
  5304. /*
  5305. * If the cell contains widgets that are not currently attached
  5306. * then attach them now.
  5307. */
  5308. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  5309. final Widget widget = metadata.getWidget();
  5310. if (widget != null && !widget.isAttached()) {
  5311. getGrid().attachWidget(metadata.getWidget(),
  5312. cell.getElement());
  5313. }
  5314. }
  5315. }
  5316. }
  5317. @Override
  5318. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5319. if (section.getRowCount() > row.getRow()) {
  5320. StaticSection.StaticRow<?> gridRow = section
  5321. .getRow(row.getRow());
  5322. List<Column<?, T>> columns = getVisibleColumns();
  5323. for (FlyweightCell cell : cellsToDetach) {
  5324. StaticSection.StaticCell metadata = gridRow
  5325. .getCell(columns.get(cell.getColumn()));
  5326. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  5327. && metadata.getWidget() != null
  5328. && metadata.getWidget().isAttached()) {
  5329. getGrid().detachWidget(metadata.getWidget());
  5330. }
  5331. }
  5332. }
  5333. }
  5334. protected Grid getGrid() {
  5335. return section.grid;
  5336. }
  5337. @Override
  5338. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5339. }
  5340. };
  5341. /**
  5342. * Creates a new instance.
  5343. */
  5344. public Grid() {
  5345. initWidget(escalator);
  5346. getElement().setTabIndex(0);
  5347. cellFocusHandler = new CellFocusHandler();
  5348. setStylePrimaryName(STYLE_NAME);
  5349. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  5350. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  5351. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  5352. header.setGrid(this);
  5353. HeaderRow defaultRow = header.appendRow();
  5354. header.setDefaultRow(defaultRow);
  5355. footer.setGrid(this);
  5356. editor.setGrid(this);
  5357. setSelectionMode(SelectionMode.SINGLE);
  5358. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  5359. escalator.addScrollHandler(new ScrollHandler() {
  5360. @Override
  5361. public void onScroll(ScrollEvent event) {
  5362. fireEvent(new ScrollEvent());
  5363. }
  5364. });
  5365. escalator.addRowVisibilityChangeHandler(
  5366. new RowVisibilityChangeHandler() {
  5367. @Override
  5368. public void onRowVisibilityChange(
  5369. RowVisibilityChangeEvent event) {
  5370. if (dataSource != null && dataSource.size() != 0) {
  5371. dataSource.ensureAvailability(
  5372. event.getFirstVisibleRow(),
  5373. event.getVisibleRowCount());
  5374. }
  5375. }
  5376. });
  5377. // Default action on SelectionEvents. Refresh the body so changed
  5378. // become visible.
  5379. addSelectionHandler(new SelectionHandler<T>() {
  5380. @Override
  5381. public void onSelect(SelectionEvent<T> event) {
  5382. refreshBody();
  5383. }
  5384. });
  5385. // Sink header events and key events
  5386. sinkEvents(getHeader().getConsumedEvents());
  5387. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  5388. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  5389. BrowserEvents.MOUSEDOWN, BrowserEvents.CLICK));
  5390. // Make ENTER and SHIFT+ENTER in the header perform sorting
  5391. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  5392. @Override
  5393. public void onKeyUp(GridKeyUpEvent event) {
  5394. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  5395. return;
  5396. }
  5397. if (getHeader().getRow(event.getFocusedCell().getRowIndex())
  5398. .isDefault()) {
  5399. // Only sort for enter on the default header
  5400. sorter.sort(event.getFocusedCell().getColumn(),
  5401. event.isShiftKeyDown());
  5402. }
  5403. }
  5404. });
  5405. browserEventHandlers.addAll(Arrays.asList(
  5406. // Opening, closing and navigating in the editor
  5407. new EditorEventHandler(),
  5408. // Keyboard and click handlers, Escalator events
  5409. new SuperEventHandler(),
  5410. // Column reordering via header drag&drop
  5411. new HeaderCellDragStartHandler(),
  5412. // Column sorting via header click
  5413. new HeaderDefaultRowEventHandler(),
  5414. // Invoking event-aware renderers
  5415. new RendererEventHandler(),
  5416. // Moving cell focus by keyboard or mouse
  5417. new CellFocusEventHandler()));
  5418. }
  5419. @Override
  5420. public boolean isEnabled() {
  5421. return enabled;
  5422. }
  5423. @Override
  5424. public void setEnabled(boolean enabled) {
  5425. if (enabled == this.enabled) {
  5426. return;
  5427. }
  5428. this.enabled = enabled;
  5429. getElement().setTabIndex(enabled ? 0 : -1);
  5430. // Editor save and cancel buttons need to be disabled.
  5431. boolean editorOpen = editor.getState() != State.INACTIVE;
  5432. if (editorOpen) {
  5433. editor.setGridEnabled(enabled);
  5434. }
  5435. sidebar.setEnabled(enabled);
  5436. getEscalator().setScrollLocked(Direction.VERTICAL,
  5437. !enabled || editorOpen);
  5438. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  5439. fireEvent(new GridEnabledEvent(enabled));
  5440. }
  5441. @Override
  5442. public void setStylePrimaryName(String style) {
  5443. super.setStylePrimaryName(style);
  5444. escalator.setStylePrimaryName(style);
  5445. editor.setStylePrimaryName(style);
  5446. sidebar.setStylePrimaryName(style + "-sidebar");
  5447. sidebar.addStyleName("v-contextmenu");
  5448. String rowStyle = getStylePrimaryName() + "-row";
  5449. rowHasDataStyleName = rowStyle + "-has-data";
  5450. rowSelectedStyleName = rowStyle + "-selected";
  5451. rowStripeStyleName = rowStyle + "-stripe";
  5452. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  5453. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  5454. if (isAttached()) {
  5455. refreshHeader();
  5456. refreshBody();
  5457. refreshFooter();
  5458. }
  5459. }
  5460. /**
  5461. * Sets the column resize mode to use. The default mode is
  5462. * {@link ColumnResizeMode.ANIMATED}.
  5463. *
  5464. * @param mode
  5465. * a ColumnResizeMode value
  5466. * @since 7.7.5
  5467. */
  5468. public void setColumnResizeMode(ColumnResizeMode mode) {
  5469. columnResizeMode = mode;
  5470. }
  5471. /**
  5472. * Returns the current column resize mode. The default mode is
  5473. * {@link ColumnResizeMode.ANIMATED}.
  5474. *
  5475. * @return a ColumnResizeMode value
  5476. * @since 7.7.5
  5477. */
  5478. public ColumnResizeMode getColumnResizeMode() {
  5479. return columnResizeMode;
  5480. }
  5481. /**
  5482. * Creates the escalator updater used to update the header rows in this
  5483. * grid. The updater is invoked when header rows or columns are added or
  5484. * removed, or the content of existing header cells is changed.
  5485. *
  5486. * @return the new header updater instance
  5487. *
  5488. * @see GridHeader
  5489. * @see Grid#getHeader()
  5490. */
  5491. protected EscalatorUpdater createHeaderUpdater() {
  5492. return new StaticSectionUpdater(header, escalator.getHeader());
  5493. }
  5494. /**
  5495. * Creates the escalator updater used to update the body rows in this grid.
  5496. * The updater is invoked when body rows or columns are added or removed,
  5497. * the content of body cells is changed, or the body is scrolled to expose
  5498. * previously hidden content.
  5499. *
  5500. * @return the new body updater instance
  5501. */
  5502. protected EscalatorUpdater createBodyUpdater() {
  5503. return new BodyUpdater();
  5504. }
  5505. /**
  5506. * Creates the escalator updater used to update the footer rows in this
  5507. * grid. The updater is invoked when header rows or columns are added or
  5508. * removed, or the content of existing header cells is changed.
  5509. *
  5510. * @return the new footer updater instance
  5511. *
  5512. * @see GridFooter
  5513. * @see #getFooter()
  5514. */
  5515. protected EscalatorUpdater createFooterUpdater() {
  5516. return new StaticSectionUpdater(footer, escalator.getFooter());
  5517. }
  5518. /**
  5519. * Refreshes header or footer rows on demand
  5520. *
  5521. * @param rows
  5522. * The row container
  5523. * @param firstRowIsVisible
  5524. * is the first row visible
  5525. * @param isHeader
  5526. * <code>true</code> if we refreshing the header, else assumed
  5527. * the footer
  5528. */
  5529. private void refreshRowContainer(RowContainer rows,
  5530. StaticSection<?> section) {
  5531. // Add or Remove rows on demand
  5532. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  5533. if (rowDiff > 0) {
  5534. rows.insertRows(0, rowDiff);
  5535. } else if (rowDiff < 0) {
  5536. rows.removeRows(0, -rowDiff);
  5537. }
  5538. // Refresh all the rows
  5539. if (rows.getRowCount() > 0) {
  5540. rows.refreshRows(0, rows.getRowCount());
  5541. }
  5542. }
  5543. /**
  5544. * Focus a body cell by row and column index.
  5545. *
  5546. * @param rowIndex
  5547. * index of row to focus
  5548. * @param columnIndexDOM
  5549. * index (excluding hidden columns) of cell to focus
  5550. */
  5551. void focusCell(int rowIndex, int columnIndexDOM) {
  5552. final Range rowRange = Range.between(0, dataSource.size());
  5553. final Range columnRange = Range.between(0, getVisibleColumns().size());
  5554. assert rowRange.contains(
  5555. rowIndex) : "Illegal row index. Should be in range " + rowRange;
  5556. assert columnRange.contains(
  5557. columnIndexDOM) : "Illegal column index. Should be in range "
  5558. + columnRange;
  5559. if (rowRange.contains(rowIndex)
  5560. && columnRange.contains(columnIndexDOM)) {
  5561. cellFocusHandler.setCellFocus(rowIndex, columnIndexDOM,
  5562. escalator.getBody());
  5563. WidgetUtil.focus(getElement());
  5564. }
  5565. }
  5566. /**
  5567. * Refreshes all header rows
  5568. */
  5569. void refreshHeader() {
  5570. refreshRowContainer(escalator.getHeader(), header);
  5571. }
  5572. /**
  5573. * Refreshes all body rows
  5574. */
  5575. private void refreshBody() {
  5576. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  5577. }
  5578. /**
  5579. * Refreshes all footer rows
  5580. */
  5581. void refreshFooter() {
  5582. refreshRowContainer(escalator.getFooter(), footer);
  5583. }
  5584. /**
  5585. * Adds columns as the last columns in the grid.
  5586. *
  5587. * @param columns
  5588. * the columns to add
  5589. */
  5590. public void addColumns(Column<?, T>... columns) {
  5591. int count = getColumnCount();
  5592. for (Column<?, T> column : columns) {
  5593. addColumn(column, count++);
  5594. }
  5595. }
  5596. /**
  5597. * Adds a column as the last column in the grid.
  5598. *
  5599. * @param column
  5600. * the column to add
  5601. * @return given column
  5602. */
  5603. public <C extends Column<?, T>> C addColumn(C column) {
  5604. addColumn(column, getColumnCount());
  5605. return column;
  5606. }
  5607. /**
  5608. * Inserts a column into a specific position in the grid.
  5609. *
  5610. * @param index
  5611. * the index where the column should be inserted into
  5612. * @param column
  5613. * the column to add
  5614. * @return given column
  5615. *
  5616. * @throws IllegalStateException
  5617. * if Grid's current selection model renders a selection column,
  5618. * and {@code index} is 0.
  5619. */
  5620. public <C extends Column<?, T>> C addColumn(C column, int index) {
  5621. if (column == selectionColumn) {
  5622. throw new IllegalArgumentException(
  5623. "The selection column many " + "not be added manually");
  5624. } else if (selectionColumn != null && index == 0) {
  5625. throw new IllegalStateException("A column cannot be inserted "
  5626. + "before the selection column");
  5627. }
  5628. addColumnSkipSelectionColumnCheck(column, index);
  5629. return column;
  5630. }
  5631. private void addColumnSkipSelectionColumnCheck(Column<?, T> column,
  5632. int index) {
  5633. // Register column with grid
  5634. columns.add(index, column);
  5635. header.addColumn(column);
  5636. footer.addColumn(column);
  5637. // Register this grid instance with the column
  5638. ((Column<?, T>) column).setGrid(this);
  5639. // Grid knows about hidden columns, Escalator only knows about what is
  5640. // visible so column indexes do not match
  5641. if (!column.isHidden()) {
  5642. int escalatorIndex = index;
  5643. for (int existingColumn = 0; existingColumn < index; existingColumn++) {
  5644. if (getColumn(existingColumn).isHidden()) {
  5645. escalatorIndex--;
  5646. }
  5647. }
  5648. escalator.getColumnConfiguration().insertColumns(escalatorIndex, 1);
  5649. }
  5650. // Reapply column width
  5651. column.reapplyWidth();
  5652. // Sink all renderer events
  5653. Set<String> events = new HashSet<String>();
  5654. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  5655. if (column.isHidable()) {
  5656. columnHider.updateColumnHidable(column);
  5657. }
  5658. sinkEvents(events);
  5659. }
  5660. private void sinkEvents(Collection<String> events) {
  5661. assert events != null;
  5662. int eventsToSink = 0;
  5663. for (String typeName : events) {
  5664. int typeInt = Event.getTypeInt(typeName);
  5665. if (typeInt < 0) {
  5666. // Type not recognized by typeInt
  5667. sinkBitlessEvent(typeName);
  5668. } else {
  5669. eventsToSink |= typeInt;
  5670. }
  5671. }
  5672. if (eventsToSink > 0) {
  5673. sinkEvents(eventsToSink);
  5674. }
  5675. }
  5676. private Renderer<?> findRenderer(FlyweightCell cell) {
  5677. Column<?, T> column = getVisibleColumn(cell.getColumn());
  5678. assert column != null : "Could not find column at index:"
  5679. + cell.getColumn();
  5680. return column.getRenderer();
  5681. }
  5682. /**
  5683. * Removes a column from the grid.
  5684. *
  5685. * @param column
  5686. * the column to remove
  5687. */
  5688. public void removeColumn(Column<?, T> column) {
  5689. if (column != null && column.equals(selectionColumn)) {
  5690. throw new IllegalArgumentException(
  5691. "The selection column may not be removed manually.");
  5692. }
  5693. removeColumnSkipSelectionColumnCheck(column);
  5694. }
  5695. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  5696. int columnIndex = columns.indexOf(column);
  5697. // Remove from column configuration
  5698. int visibleColumnIndex = getVisibleColumns().indexOf(column);
  5699. if (visibleColumnIndex < 0) {
  5700. assert column.isHidden();
  5701. // Hidden columns are not included in Escalator
  5702. } else {
  5703. getEscalator().getColumnConfiguration()
  5704. .removeColumns(visibleColumnIndex, 1);
  5705. }
  5706. updateFrozenColumns();
  5707. header.removeColumn(column);
  5708. footer.removeColumn(column);
  5709. // de-register column with grid
  5710. ((Column<?, T>) column).setGrid(null);
  5711. columns.remove(columnIndex);
  5712. if (column.isHidable()) {
  5713. columnHider.removeColumnHidingToggle(column);
  5714. }
  5715. }
  5716. /**
  5717. * Returns the amount of columns in the grid.
  5718. * <p>
  5719. * <em>NOTE:</em> this includes the hidden columns in the count.
  5720. *
  5721. * @return The number of columns in the grid
  5722. */
  5723. public int getColumnCount() {
  5724. return columns.size();
  5725. }
  5726. /**
  5727. * Returns a list columns in the grid, including hidden columns.
  5728. * <p>
  5729. * For currently visible columns, use {@link #getVisibleColumns()}.
  5730. *
  5731. * @return A unmodifiable list of the columns in the grid
  5732. */
  5733. public List<Column<?, T>> getColumns() {
  5734. return Collections
  5735. .unmodifiableList(new ArrayList<Column<?, T>>(columns));
  5736. }
  5737. /**
  5738. * Returns a list of the currently visible columns in the grid.
  5739. * <p>
  5740. * No {@link Column#isHidden() hidden} columns included.
  5741. *
  5742. * @since 7.5.0
  5743. * @return A unmodifiable list of the currently visible columns in the grid
  5744. */
  5745. public List<Column<?, T>> getVisibleColumns() {
  5746. ArrayList<Column<?, T>> visible = new ArrayList<Column<?, T>>();
  5747. for (Column<?, T> c : columns) {
  5748. if (!c.isHidden()) {
  5749. visible.add(c);
  5750. }
  5751. }
  5752. return Collections.unmodifiableList(visible);
  5753. }
  5754. /**
  5755. * Returns a column by its index in the grid.
  5756. * <p>
  5757. * <em>NOTE:</em> The indexing includes hidden columns.
  5758. *
  5759. * @param index
  5760. * the index of the column
  5761. * @return The column in the given index
  5762. * @throws IllegalArgumentException
  5763. * if the column index does not exist in the grid
  5764. */
  5765. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  5766. if (index < 0 || index >= columns.size()) {
  5767. throw new IllegalStateException("Column not found.");
  5768. }
  5769. return columns.get(index);
  5770. }
  5771. private Column<?, T> getVisibleColumn(int columnIndexDOM)
  5772. throws IllegalArgumentException {
  5773. List<Column<?, T>> visibleColumns = getVisibleColumns();
  5774. if (columnIndexDOM < 0 || columnIndexDOM >= visibleColumns.size()) {
  5775. throw new IllegalStateException("Column not found.");
  5776. }
  5777. return visibleColumns.get(columnIndexDOM);
  5778. }
  5779. /**
  5780. * Returns the header section of this grid. The default header contains a
  5781. * single row displaying the column captions.
  5782. *
  5783. * @return the header
  5784. */
  5785. protected Header getHeader() {
  5786. return header;
  5787. }
  5788. /**
  5789. * Gets the header row at given index.
  5790. *
  5791. * @param rowIndex
  5792. * 0 based index for row. Counted from top to bottom
  5793. * @return header row at given index
  5794. * @throws IllegalArgumentException
  5795. * if no row exists at given index
  5796. */
  5797. public HeaderRow getHeaderRow(int rowIndex) {
  5798. return header.getRow(rowIndex);
  5799. }
  5800. /**
  5801. * Inserts a new row at the given position to the header section. Shifts the
  5802. * row currently at that position and any subsequent rows down (adds one to
  5803. * their indices).
  5804. *
  5805. * @param index
  5806. * the position at which to insert the row
  5807. * @return the new row
  5808. *
  5809. * @throws IllegalArgumentException
  5810. * if the index is less than 0 or greater than row count
  5811. * @see #appendHeaderRow()
  5812. * @see #prependHeaderRow()
  5813. * @see #removeHeaderRow(HeaderRow)
  5814. * @see #removeHeaderRow(int)
  5815. */
  5816. public HeaderRow addHeaderRowAt(int index) {
  5817. return header.addRowAt(index);
  5818. }
  5819. /**
  5820. * Adds a new row at the bottom of the header section.
  5821. *
  5822. * @return the new row
  5823. * @see #prependHeaderRow()
  5824. * @see #addHeaderRowAt(int)
  5825. * @see #removeHeaderRow(HeaderRow)
  5826. * @see #removeHeaderRow(int)
  5827. */
  5828. public HeaderRow appendHeaderRow() {
  5829. return header.appendRow();
  5830. }
  5831. /**
  5832. * Returns the current default row of the header section. The default row is
  5833. * a special header row providing a user interface for sorting columns.
  5834. * Setting a header caption for column updates cells in the default header.
  5835. *
  5836. * @return the default row or null if no default row set
  5837. */
  5838. public HeaderRow getDefaultHeaderRow() {
  5839. return header.getDefaultRow();
  5840. }
  5841. /**
  5842. * Gets the row count for the header section.
  5843. *
  5844. * @return row count
  5845. */
  5846. public int getHeaderRowCount() {
  5847. return header.getRowCount();
  5848. }
  5849. /**
  5850. * Adds a new row at the top of the header section.
  5851. *
  5852. * @return the new row
  5853. * @see #appendHeaderRow()
  5854. * @see #addHeaderRowAt(int)
  5855. * @see #removeHeaderRow(HeaderRow)
  5856. * @see #removeHeaderRow(int)
  5857. */
  5858. public HeaderRow prependHeaderRow() {
  5859. return header.prependRow();
  5860. }
  5861. /**
  5862. * Removes the given row from the header section.
  5863. *
  5864. * @param row
  5865. * the row to be removed
  5866. *
  5867. * @throws IllegalArgumentException
  5868. * if the row does not exist in this section
  5869. * @see #removeHeaderRow(int)
  5870. * @see #addHeaderRowAt(int)
  5871. * @see #appendHeaderRow()
  5872. * @see #prependHeaderRow()
  5873. */
  5874. public void removeHeaderRow(HeaderRow row) {
  5875. header.removeRow(row);
  5876. }
  5877. /**
  5878. * Removes the row at the given position from the header section.
  5879. *
  5880. * @param index
  5881. * the position of the row
  5882. *
  5883. * @throws IllegalArgumentException
  5884. * if no row exists at given index
  5885. * @see #removeHeaderRow(HeaderRow)
  5886. * @see #addHeaderRowAt(int)
  5887. * @see #appendHeaderRow()
  5888. * @see #prependHeaderRow()
  5889. */
  5890. public void removeHeaderRow(int rowIndex) {
  5891. header.removeRow(rowIndex);
  5892. }
  5893. /**
  5894. * Sets the default row of the header. The default row is a special header
  5895. * row providing a user interface for sorting columns.
  5896. * <p>
  5897. * Note: Setting the default header row will reset all cell contents to
  5898. * Column defaults.
  5899. *
  5900. * @param row
  5901. * the new default row, or null for no default row
  5902. *
  5903. * @throws IllegalArgumentException
  5904. * header does not contain the row
  5905. */
  5906. public void setDefaultHeaderRow(HeaderRow row) {
  5907. header.setDefaultRow(row);
  5908. }
  5909. /**
  5910. * Sets the visibility of the header section.
  5911. *
  5912. * @param visible
  5913. * true to show header section, false to hide
  5914. */
  5915. public void setHeaderVisible(boolean visible) {
  5916. header.setVisible(visible);
  5917. }
  5918. /**
  5919. * Returns the visibility of the header section.
  5920. *
  5921. * @return true if visible, false otherwise.
  5922. */
  5923. public boolean isHeaderVisible() {
  5924. return header.isVisible();
  5925. }
  5926. /* Grid Footers */
  5927. /**
  5928. * Returns the footer section of this grid. The default footer is empty.
  5929. *
  5930. * @return the footer
  5931. */
  5932. protected Footer getFooter() {
  5933. return footer;
  5934. }
  5935. /**
  5936. * Gets the footer row at given index.
  5937. *
  5938. * @param rowIndex
  5939. * 0 based index for row. Counted from top to bottom
  5940. * @return footer row at given index
  5941. * @throws IllegalArgumentException
  5942. * if no row exists at given index
  5943. */
  5944. public FooterRow getFooterRow(int rowIndex) {
  5945. return footer.getRow(rowIndex);
  5946. }
  5947. /**
  5948. * Inserts a new row at the given position to the footer section. Shifts the
  5949. * row currently at that position and any subsequent rows down (adds one to
  5950. * their indices).
  5951. *
  5952. * @param index
  5953. * the position at which to insert the row
  5954. * @return the new row
  5955. *
  5956. * @throws IllegalArgumentException
  5957. * if the index is less than 0 or greater than row count
  5958. * @see #appendFooterRow()
  5959. * @see #prependFooterRow()
  5960. * @see #removeFooterRow(FooterRow)
  5961. * @see #removeFooterRow(int)
  5962. */
  5963. public FooterRow addFooterRowAt(int index) {
  5964. return footer.addRowAt(index);
  5965. }
  5966. /**
  5967. * Adds a new row at the bottom of the footer section.
  5968. *
  5969. * @return the new row
  5970. * @see #prependFooterRow()
  5971. * @see #addFooterRowAt(int)
  5972. * @see #removeFooterRow(FooterRow)
  5973. * @see #removeFooterRow(int)
  5974. */
  5975. public FooterRow appendFooterRow() {
  5976. return footer.appendRow();
  5977. }
  5978. /**
  5979. * Gets the row count for the footer.
  5980. *
  5981. * @return row count
  5982. */
  5983. public int getFooterRowCount() {
  5984. return footer.getRowCount();
  5985. }
  5986. /**
  5987. * Adds a new row at the top of the footer section.
  5988. *
  5989. * @return the new row
  5990. * @see #appendFooterRow()
  5991. * @see #addFooterRowAt(int)
  5992. * @see #removeFooterRow(FooterRow)
  5993. * @see #removeFooterRow(int)
  5994. */
  5995. public FooterRow prependFooterRow() {
  5996. return footer.prependRow();
  5997. }
  5998. /**
  5999. * Removes the given row from the footer section.
  6000. *
  6001. * @param row
  6002. * the row to be removed
  6003. *
  6004. * @throws IllegalArgumentException
  6005. * if the row does not exist in this section
  6006. * @see #removeFooterRow(int)
  6007. * @see #addFooterRowAt(int)
  6008. * @see #appendFooterRow()
  6009. * @see #prependFooterRow()
  6010. */
  6011. public void removeFooterRow(FooterRow row) {
  6012. footer.removeRow(row);
  6013. }
  6014. /**
  6015. * Removes the row at the given position from the footer section.
  6016. *
  6017. * @param index
  6018. * the position of the row
  6019. *
  6020. * @throws IllegalArgumentException
  6021. * if no row exists at given index
  6022. * @see #removeFooterRow(FooterRow)
  6023. * @see #addFooterRowAt(int)
  6024. * @see #appendFooterRow()
  6025. * @see #prependFooterRow()
  6026. */
  6027. public void removeFooterRow(int rowIndex) {
  6028. footer.removeRow(rowIndex);
  6029. }
  6030. /**
  6031. * Sets the visibility of the footer section.
  6032. *
  6033. * @param visible
  6034. * true to show footer section, false to hide
  6035. */
  6036. public void setFooterVisible(boolean visible) {
  6037. footer.setVisible(visible);
  6038. }
  6039. /**
  6040. * Returns the visibility of the footer section.
  6041. *
  6042. * @return true if visible, false otherwise.
  6043. */
  6044. public boolean isFooterVisible() {
  6045. return footer.isVisible();
  6046. }
  6047. public Editor<T> getEditor() {
  6048. return editor;
  6049. }
  6050. /**
  6051. * Gets the {@link Escalator} used by this Grid instnace.
  6052. *
  6053. * @return the escalator instance, never <code>null</code>
  6054. */
  6055. public Escalator getEscalator() {
  6056. return escalator;
  6057. }
  6058. /**
  6059. * {@inheritDoc}
  6060. * <p>
  6061. * <em>Note:</em> This method will change the widget's size in the browser
  6062. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  6063. *
  6064. * @see #setHeightMode(HeightMode)
  6065. */
  6066. @Override
  6067. public void setHeight(String height) {
  6068. escalator.setHeight(height);
  6069. }
  6070. @Override
  6071. public void setWidth(String width) {
  6072. escalator.setWidth(width);
  6073. }
  6074. /**
  6075. * Sets the data source used by this grid.
  6076. *
  6077. * @param dataSource
  6078. * the data source to use, not null
  6079. * @throws IllegalArgumentException
  6080. * if <code>dataSource</code> is <code>null</code>
  6081. */
  6082. public void setDataSource(final DataSource<T> dataSource)
  6083. throws IllegalArgumentException {
  6084. if (dataSource == null) {
  6085. throw new IllegalArgumentException("dataSource can't be null.");
  6086. }
  6087. selectionModel.reset();
  6088. if (changeHandler != null) {
  6089. changeHandler.remove();
  6090. changeHandler = null;
  6091. }
  6092. this.dataSource = dataSource;
  6093. changeHandler = dataSource
  6094. .addDataChangeHandler(new DataChangeHandler() {
  6095. @Override
  6096. public void dataUpdated(int firstIndex, int numberOfItems) {
  6097. escalator.getBody().refreshRows(firstIndex,
  6098. numberOfItems);
  6099. }
  6100. @Override
  6101. public void dataRemoved(int firstIndex, int numberOfItems) {
  6102. escalator.getBody().removeRows(firstIndex,
  6103. numberOfItems);
  6104. Range removed = Range.withLength(firstIndex,
  6105. numberOfItems);
  6106. cellFocusHandler.rowsRemovedFromBody(removed);
  6107. }
  6108. @Override
  6109. public void dataAdded(int firstIndex, int numberOfItems) {
  6110. escalator.getBody().insertRows(firstIndex,
  6111. numberOfItems);
  6112. Range added = Range.withLength(firstIndex,
  6113. numberOfItems);
  6114. cellFocusHandler.rowsAddedToBody(added);
  6115. }
  6116. @Override
  6117. public void dataAvailable(int firstIndex,
  6118. int numberOfItems) {
  6119. currentDataAvailable = Range.withLength(firstIndex,
  6120. numberOfItems);
  6121. fireEvent(new DataAvailableEvent(currentDataAvailable));
  6122. }
  6123. @Override
  6124. public void resetDataAndSize(int newSize) {
  6125. RowContainer body = escalator.getBody();
  6126. int oldSize = body.getRowCount();
  6127. // Hide all details.
  6128. Set<Integer> oldDetails = new HashSet<Integer>(
  6129. visibleDetails);
  6130. for (int i : oldDetails) {
  6131. setDetailsVisible(i, false);
  6132. }
  6133. if (newSize > oldSize) {
  6134. body.insertRows(oldSize, newSize - oldSize);
  6135. cellFocusHandler.rowsAddedToBody(Range
  6136. .withLength(oldSize, newSize - oldSize));
  6137. } else if (newSize < oldSize) {
  6138. body.removeRows(newSize, oldSize - newSize);
  6139. cellFocusHandler.rowsRemovedFromBody(Range
  6140. .withLength(newSize, oldSize - newSize));
  6141. }
  6142. if (newSize > 0) {
  6143. Range visibleRowRange = escalator
  6144. .getVisibleRowRange();
  6145. dataSource.ensureAvailability(
  6146. visibleRowRange.getStart(),
  6147. visibleRowRange.length());
  6148. } else {
  6149. // We won't expect any data more data updates, so
  6150. // just make
  6151. // the bookkeeping happy
  6152. dataAvailable(0, 0);
  6153. }
  6154. assert body.getRowCount() == newSize;
  6155. }
  6156. });
  6157. int previousRowCount = escalator.getBody().getRowCount();
  6158. if (previousRowCount != 0) {
  6159. escalator.getBody().removeRows(0, previousRowCount);
  6160. }
  6161. setEscalatorSizeFromDataSource();
  6162. }
  6163. private void setEscalatorSizeFromDataSource() {
  6164. assert escalator.getBody().getRowCount() == 0;
  6165. int size = dataSource.size();
  6166. if (size == -1 && isAttached()) {
  6167. // Exact size is not yet known, start with some reasonable guess
  6168. // just to get an initial backend request going
  6169. size = getEscalator().getMaxVisibleRowCount();
  6170. }
  6171. if (size > 0) {
  6172. escalator.getBody().insertRows(0, size);
  6173. }
  6174. }
  6175. /**
  6176. * Gets the {@Link DataSource} for this Grid.
  6177. *
  6178. * @return the data source used by this grid
  6179. */
  6180. public DataSource<T> getDataSource() {
  6181. return dataSource;
  6182. }
  6183. /**
  6184. * Sets the number of frozen columns in this grid. Setting the count to 0
  6185. * means that no data columns will be frozen, but the built-in selection
  6186. * checkbox column will still be frozen if it's in use. Setting the count to
  6187. * -1 will also disable the selection column.
  6188. * <p>
  6189. * The default value is 0.
  6190. *
  6191. * @param numberOfColumns
  6192. * the number of columns that should be frozen
  6193. *
  6194. * @throws IllegalArgumentException
  6195. * if the column count is < -1 or > the number of visible
  6196. * columns
  6197. */
  6198. public void setFrozenColumnCount(int numberOfColumns) {
  6199. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  6200. throw new IllegalArgumentException(
  6201. "count must be between -1 and the current number of columns ("
  6202. + getColumnCount() + ")");
  6203. }
  6204. frozenColumnCount = numberOfColumns;
  6205. updateFrozenColumns();
  6206. }
  6207. private void updateFrozenColumns() {
  6208. escalator.getColumnConfiguration()
  6209. .setFrozenColumnCount(getVisibleFrozenColumnCount());
  6210. }
  6211. private int getVisibleFrozenColumnCount() {
  6212. int numberOfColumns = getFrozenColumnCount();
  6213. // for the escalator the hidden columns are not in the frozen column
  6214. // count, but for grid they are. thus need to convert the index
  6215. for (int i = 0; i < frozenColumnCount; i++) {
  6216. if (getColumn(i).isHidden()) {
  6217. numberOfColumns--;
  6218. }
  6219. }
  6220. if (numberOfColumns == -1) {
  6221. numberOfColumns = 0;
  6222. } else if (selectionColumn != null) {
  6223. numberOfColumns++;
  6224. }
  6225. return numberOfColumns;
  6226. }
  6227. /**
  6228. * Gets the number of frozen columns in this grid. 0 means that no data
  6229. * columns will be frozen, but the built-in selection checkbox column will
  6230. * still be frozen if it's in use. -1 means that not even the selection
  6231. * column is frozen.
  6232. * <p>
  6233. * <em>NOTE:</em> This includes {@link Column#isHidden() hidden columns} in
  6234. * the count.
  6235. *
  6236. * @return the number of frozen columns
  6237. */
  6238. public int getFrozenColumnCount() {
  6239. return frozenColumnCount;
  6240. }
  6241. public HandlerRegistration addRowVisibilityChangeHandler(
  6242. RowVisibilityChangeHandler handler) {
  6243. /*
  6244. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  6245. * concept is too abstract. e.g. the event needs to be re-sent when the
  6246. * widget is resized.
  6247. */
  6248. return escalator.addRowVisibilityChangeHandler(handler);
  6249. }
  6250. /**
  6251. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  6252. * <p>
  6253. * If the details for that row are visible, those will be taken into account
  6254. * as well.
  6255. *
  6256. * @param rowIndex
  6257. * zero-based index of the row to scroll to.
  6258. * @throws IllegalArgumentException
  6259. * if rowIndex is below zero, or above the maximum value
  6260. * supported by the data source.
  6261. */
  6262. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  6263. scrollToRow(rowIndex, ScrollDestination.ANY,
  6264. GridConstants.DEFAULT_PADDING);
  6265. }
  6266. /**
  6267. * Scrolls to a certain row, using user-specified scroll destination.
  6268. * <p>
  6269. * If the details for that row are visible, those will be taken into account
  6270. * as well.
  6271. *
  6272. * @param rowIndex
  6273. * zero-based index of the row to scroll to.
  6274. * @param destination
  6275. * desired destination placement of scrolled-to-row. See
  6276. * {@link ScrollDestination} for more information.
  6277. * @throws IllegalArgumentException
  6278. * if rowIndex is below zero, or above the maximum value
  6279. * supported by the data source.
  6280. */
  6281. public void scrollToRow(int rowIndex, ScrollDestination destination)
  6282. throws IllegalArgumentException {
  6283. scrollToRow(rowIndex, destination,
  6284. destination == ScrollDestination.MIDDLE ? 0
  6285. : GridConstants.DEFAULT_PADDING);
  6286. }
  6287. /**
  6288. * Scrolls to a certain row using only user-specified parameters.
  6289. * <p>
  6290. * If the details for that row are visible, those will be taken into account
  6291. * as well.
  6292. *
  6293. * @param rowIndex
  6294. * zero-based index of the row to scroll to.
  6295. * @param destination
  6296. * desired destination placement of scrolled-to-row. See
  6297. * {@link ScrollDestination} for more information.
  6298. * @param paddingPx
  6299. * number of pixels to overscroll. Behavior depends on
  6300. * destination.
  6301. * @throws IllegalArgumentException
  6302. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6303. * and padding is nonzero, because having a padding on a
  6304. * centered row is undefined behavior, or if rowIndex is below
  6305. * zero or above the row count of the data source.
  6306. */
  6307. private void scrollToRow(int rowIndex, ScrollDestination destination,
  6308. int paddingPx) throws IllegalArgumentException {
  6309. int maxsize = escalator.getBody().getRowCount() - 1;
  6310. if (rowIndex < 0) {
  6311. throw new IllegalArgumentException(
  6312. "Row index (" + rowIndex + ") is below zero!");
  6313. }
  6314. if (rowIndex > maxsize) {
  6315. throw new IllegalArgumentException("Row index (" + rowIndex
  6316. + ") is above maximum (" + maxsize + ")!");
  6317. }
  6318. escalator.scrollToRowAndSpacer(rowIndex, destination, paddingPx);
  6319. }
  6320. /**
  6321. * Scrolls to the beginning of the very first row.
  6322. */
  6323. public void scrollToStart() {
  6324. scrollToRow(0, ScrollDestination.START);
  6325. }
  6326. /**
  6327. * Scrolls to the end of the very last row.
  6328. */
  6329. public void scrollToEnd() {
  6330. scrollToRow(escalator.getBody().getRowCount() - 1,
  6331. ScrollDestination.END);
  6332. }
  6333. /**
  6334. * Sets the vertical scroll offset.
  6335. *
  6336. * @param px
  6337. * the number of pixels this grid should be scrolled down
  6338. */
  6339. public void setScrollTop(double px) {
  6340. escalator.setScrollTop(px);
  6341. }
  6342. /**
  6343. * Gets the vertical scroll offset
  6344. *
  6345. * @return the number of pixels this grid is scrolled down
  6346. */
  6347. public double getScrollTop() {
  6348. return escalator.getScrollTop();
  6349. }
  6350. /**
  6351. * Sets the horizontal scroll offset
  6352. *
  6353. * @since 7.5.0
  6354. * @param px
  6355. * the number of pixels this grid should be scrolled right
  6356. */
  6357. public void setScrollLeft(double px) {
  6358. escalator.setScrollLeft(px);
  6359. }
  6360. /**
  6361. * Gets the horizontal scroll offset
  6362. *
  6363. * @return the number of pixels this grid is scrolled to the right
  6364. */
  6365. public double getScrollLeft() {
  6366. return escalator.getScrollLeft();
  6367. }
  6368. /**
  6369. * Returns the height of the scrollable area in pixels.
  6370. *
  6371. * @since 7.5.0
  6372. * @return the height of the scrollable area in pixels
  6373. */
  6374. public double getScrollHeight() {
  6375. return escalator.getScrollHeight();
  6376. }
  6377. /**
  6378. * Returns the width of the scrollable area in pixels.
  6379. *
  6380. * @since 7.5.0
  6381. * @return the width of the scrollable area in pixels.
  6382. */
  6383. public double getScrollWidth() {
  6384. return escalator.getScrollWidth();
  6385. }
  6386. private static final Logger getLogger() {
  6387. return Logger.getLogger(Grid.class.getName());
  6388. }
  6389. /**
  6390. * Sets the number of rows that should be visible in Grid's body, while
  6391. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6392. * <p>
  6393. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  6394. * remembered, and applied once the mode is applied.
  6395. *
  6396. * @param rows
  6397. * The height in terms of number of rows displayed in Grid's
  6398. * body. If Grid doesn't contain enough rows, white space is
  6399. * displayed instead.
  6400. * @throws IllegalArgumentException
  6401. * if {@code rows} is zero or less
  6402. * @throws IllegalArgumentException
  6403. * if {@code rows} is {@link Double#isInifinite(double)
  6404. * infinite}
  6405. * @throws IllegalArgumentException
  6406. * if {@code rows} is {@link Double#isNaN(double) NaN}
  6407. *
  6408. * @see #setHeightMode(HeightMode)
  6409. */
  6410. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6411. escalator.setHeightByRows(rows);
  6412. }
  6413. /**
  6414. * Gets the amount of rows in Grid's body that are shown, while
  6415. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6416. * <p>
  6417. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  6418. *
  6419. * @return the amount of rows that should be shown in Grid's body, while in
  6420. * {@link HeightMode#ROW}.
  6421. * @see #setHeightByRows(double)
  6422. */
  6423. public double getHeightByRows() {
  6424. return escalator.getHeightByRows();
  6425. }
  6426. /**
  6427. * Defines the mode in which the Grid widget's height is calculated.
  6428. * <p>
  6429. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  6430. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  6431. * <p>
  6432. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  6433. * will display as many rows as {@link #getHeightByRows()} defines.
  6434. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  6435. * will resize itself to still display the required amount of rows in its
  6436. * body. It also takes the horizontal scrollbar into account.
  6437. *
  6438. * @param heightMode
  6439. * the mode in to which Grid should be set
  6440. */
  6441. public void setHeightMode(HeightMode heightMode) {
  6442. /*
  6443. * This method is a workaround for the fact that Vaadin re-applies
  6444. * widget dimensions (height/width) on each state change event. The
  6445. * original design was to have setHeight an setHeightByRow be equals,
  6446. * and whichever was called the latest was considered in effect.
  6447. *
  6448. * But, because of Vaadin always calling setHeight on the widget, this
  6449. * approach doesn't work.
  6450. */
  6451. escalator.setHeightMode(heightMode);
  6452. }
  6453. /**
  6454. * Returns the current {@link HeightMode} the Grid is in.
  6455. * <p>
  6456. * Defaults to {@link HeightMode#CSS}.
  6457. *
  6458. * @return the current HeightMode
  6459. */
  6460. public HeightMode getHeightMode() {
  6461. return escalator.getHeightMode();
  6462. }
  6463. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  6464. Set<String> events = new HashSet<String>();
  6465. if (renderer instanceof ComplexRenderer) {
  6466. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  6467. .getConsumedEvents();
  6468. if (consumedEvents != null) {
  6469. events.addAll(consumedEvents);
  6470. }
  6471. }
  6472. return events;
  6473. }
  6474. @Override
  6475. public void onBrowserEvent(Event event) {
  6476. if (!isEnabled()) {
  6477. return;
  6478. }
  6479. String eventType = event.getType();
  6480. if (eventType.equals(BrowserEvents.FOCUS)
  6481. || eventType.equals(BrowserEvents.BLUR)) {
  6482. super.onBrowserEvent(event);
  6483. return;
  6484. }
  6485. EventTarget target = event.getEventTarget();
  6486. if (!Element.is(target) || isOrContainsInSpacer(Element.as(target))) {
  6487. return;
  6488. }
  6489. Element e = Element.as(target);
  6490. RowContainer container = escalator.findRowContainer(e);
  6491. Cell cell;
  6492. if (container == null) {
  6493. if (eventType.equals(BrowserEvents.KEYDOWN)
  6494. || eventType.equals(BrowserEvents.KEYUP)
  6495. || eventType.equals(BrowserEvents.KEYPRESS)) {
  6496. cell = cellFocusHandler.getFocusedCell();
  6497. container = cellFocusHandler.containerWithFocus;
  6498. } else {
  6499. // Click might be in an editor cell, should still map.
  6500. if (editor.editorOverlay != null
  6501. && editor.editorOverlay.isOrHasChild(e)) {
  6502. container = escalator.getBody();
  6503. int rowIndex = editor.getRow();
  6504. int colIndex = editor.getElementColumn(e);
  6505. if (colIndex < 0) {
  6506. // Click in editor, but not for any column.
  6507. return;
  6508. }
  6509. TableCellElement cellElement = container
  6510. .getRowElement(rowIndex).getCells()
  6511. .getItem(colIndex);
  6512. cell = new Cell(rowIndex, colIndex, cellElement);
  6513. } else {
  6514. if (escalator.getElement().isOrHasChild(e)) {
  6515. eventCell.set(new Cell(-1, -1, null), Section.BODY);
  6516. // Fire native events.
  6517. super.onBrowserEvent(event);
  6518. }
  6519. return;
  6520. }
  6521. }
  6522. } else {
  6523. cell = container.getCell(e);
  6524. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  6525. cellOnPrevMouseDown = cell;
  6526. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  6527. /*
  6528. * Chrome has an interesting idea on click targets (see
  6529. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  6530. * the mousedown target as the click target.
  6531. */
  6532. cell = cellOnPrevMouseDown;
  6533. }
  6534. }
  6535. assert cell != null : "received " + eventType
  6536. + "-event with a null cell target";
  6537. eventCell.set(cell, getSectionFromContainer(container));
  6538. GridEvent<T> gridEvent = new GridEvent<T>(event, eventCell);
  6539. for (GridEventHandler<T> handler : browserEventHandlers) {
  6540. handler.onEvent(gridEvent);
  6541. }
  6542. }
  6543. private Section getSectionFromContainer(RowContainer container) {
  6544. assert container != null : "RowContainer should not be null";
  6545. if (container == escalator.getBody()) {
  6546. return Section.BODY;
  6547. } else if (container == escalator.getFooter()) {
  6548. return Section.FOOTER;
  6549. } else if (container == escalator.getHeader()) {
  6550. return Section.HEADER;
  6551. }
  6552. assert false : "RowContainer was not header, footer or body.";
  6553. return null;
  6554. }
  6555. private boolean isOrContainsInSpacer(Node node) {
  6556. Node n = node;
  6557. while (n != null && n != getElement()) {
  6558. boolean isElement = Element.is(n);
  6559. if (isElement) {
  6560. String className = Element.as(n).getClassName();
  6561. if (className.contains(getStylePrimaryName() + "-spacer")) {
  6562. return true;
  6563. }
  6564. }
  6565. n = n.getParentNode();
  6566. }
  6567. return false;
  6568. }
  6569. private boolean isElementInChildWidget(Element e) {
  6570. Widget w = WidgetUtil.findWidget(e, null);
  6571. if (w == this) {
  6572. return false;
  6573. }
  6574. /*
  6575. * If e is directly inside this grid, but the grid is wrapped in a
  6576. * Composite, findWidget is not going to find this, only the wrapper.
  6577. * Thus we need to check its parents to see if we encounter this; if we
  6578. * don't, the found widget is actually a parent of this, so we should
  6579. * return false.
  6580. */
  6581. while (w != null && w != this) {
  6582. w = w.getParent();
  6583. }
  6584. return w != null;
  6585. }
  6586. private class EditorEventHandler implements GridEventHandler<T> {
  6587. @Override
  6588. public void onEvent(GridEvent<T> event) {
  6589. if (!isEditorEnabled()) {
  6590. return;
  6591. }
  6592. Widget widget;
  6593. if (editor.focusedColumnIndexDOM < 0) {
  6594. widget = null;
  6595. } else {
  6596. widget = editor.getWidget(
  6597. getVisibleColumn(editor.focusedColumnIndexDOM));
  6598. }
  6599. EditorDomEvent<T> editorEvent = new EditorDomEvent<T>(
  6600. event.getDomEvent(), event.getCell(), widget);
  6601. event.setHandled(
  6602. getEditor().getEventHandler().handleEvent(editorEvent));
  6603. }
  6604. };
  6605. private class SuperEventHandler implements GridEventHandler<T> {
  6606. @Override
  6607. public void onEvent(GridEvent<T> event) {
  6608. if (event.isHandled()) {
  6609. return;
  6610. }
  6611. Grid.super.onBrowserEvent(event.getDomEvent());
  6612. }
  6613. };
  6614. private abstract class AbstractGridEventHandler
  6615. implements GridEventHandler<T> {
  6616. @Override
  6617. public void onEvent(GridEvent<T> event) {
  6618. if (event.isHandled()) {
  6619. return;
  6620. }
  6621. event.setHandled(isElementInChildWidget(
  6622. Element.as(event.getDomEvent().getEventTarget())));
  6623. }
  6624. };
  6625. private class RendererEventHandler extends AbstractGridEventHandler {
  6626. @Override
  6627. public void onEvent(GridEvent<T> event) {
  6628. super.onEvent(event);
  6629. if (event.isHandled()) {
  6630. return;
  6631. }
  6632. if (!event.getCell().isBody()) {
  6633. return;
  6634. }
  6635. Column<?, T> gridColumn = event.getCell().getColumn();
  6636. boolean enterKey = event.getDomEvent().getType()
  6637. .equals(BrowserEvents.KEYDOWN)
  6638. && event.getDomEvent().getKeyCode() == KeyCodes.KEY_ENTER;
  6639. boolean doubleClick = event.getDomEvent().getType()
  6640. .equals(BrowserEvents.DBLCLICK);
  6641. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  6642. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  6643. .getRenderer();
  6644. if (cplxRenderer.getConsumedEvents()
  6645. .contains(event.getDomEvent().getType())) {
  6646. if (cplxRenderer.onBrowserEvent(event.getCell(),
  6647. event.getDomEvent())) {
  6648. event.setHandled(true);
  6649. }
  6650. }
  6651. // Calls onActivate if KeyDown and Enter or double click
  6652. if ((enterKey || doubleClick)
  6653. && cplxRenderer.onActivate(event.getCell())) {
  6654. event.setHandled(true);
  6655. }
  6656. }
  6657. }
  6658. };
  6659. private class CellFocusEventHandler extends AbstractGridEventHandler {
  6660. @Override
  6661. public void onEvent(GridEvent<T> event) {
  6662. super.onEvent(event);
  6663. if (event.isHandled()) {
  6664. return;
  6665. }
  6666. Collection<String> navigation = cellFocusHandler
  6667. .getNavigationEvents();
  6668. if (navigation.contains(event.getDomEvent().getType())) {
  6669. cellFocusHandler.handleNavigationEvent(event.getDomEvent(),
  6670. event.getCell());
  6671. }
  6672. }
  6673. };
  6674. private class HeaderCellDragStartHandler extends AbstractGridEventHandler {
  6675. @Override
  6676. public void onEvent(GridEvent<T> event) {
  6677. super.onEvent(event);
  6678. if (event.isHandled()) {
  6679. return;
  6680. }
  6681. if (!isColumnReorderingAllowed()) {
  6682. return;
  6683. }
  6684. if (!event.getCell().isHeader()) {
  6685. return;
  6686. }
  6687. if (event.getCell().getColumnIndex() < getFrozenColumnCount()) {
  6688. return;
  6689. }
  6690. if (event.getDomEvent().getTypeInt() == Event.ONMOUSEDOWN
  6691. && event.getDomEvent()
  6692. .getButton() == NativeEvent.BUTTON_LEFT
  6693. || event.getDomEvent().getTypeInt() == Event.ONTOUCHSTART) {
  6694. dndHandler.onDragStartOnDraggableElement(event.getDomEvent(),
  6695. headerCellDndCallback);
  6696. event.getDomEvent().preventDefault();
  6697. event.getDomEvent().stopPropagation();
  6698. event.setHandled(true);
  6699. }
  6700. }
  6701. };
  6702. private class HeaderDefaultRowEventHandler
  6703. extends AbstractGridEventHandler {
  6704. private Point rowEventTouchStartingPoint;
  6705. @Override
  6706. public void onEvent(GridEvent<T> event) {
  6707. super.onEvent(event);
  6708. if (event.isHandled()) {
  6709. return;
  6710. }
  6711. if (!event.getCell().isHeader()) {
  6712. return;
  6713. }
  6714. if (!getHeader().getRow(event.getCell().getRowIndex())
  6715. .isDefault()) {
  6716. return;
  6717. }
  6718. if (!event.getCell().getColumn().isSortable()) {
  6719. // Only handle sorting events if the column is sortable
  6720. return;
  6721. }
  6722. if (BrowserEvents.MOUSEDOWN.equals(event.getDomEvent().getType())
  6723. && event.getDomEvent().getShiftKey()) {
  6724. // Don't select text when shift clicking on a header.
  6725. event.getDomEvent().preventDefault();
  6726. }
  6727. if (BrowserEvents.TOUCHSTART
  6728. .equals(event.getDomEvent().getType())) {
  6729. if (event.getDomEvent().getTouches().length() > 1) {
  6730. return;
  6731. }
  6732. event.getDomEvent().preventDefault();
  6733. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  6734. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  6735. touch.getClientY());
  6736. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, true);
  6737. event.setHandled(true);
  6738. } else if (BrowserEvents.TOUCHMOVE
  6739. .equals(event.getDomEvent().getType())) {
  6740. if (event.getDomEvent().getTouches().length() > 1) {
  6741. return;
  6742. }
  6743. event.getDomEvent().preventDefault();
  6744. Touch touch = event.getDomEvent().getChangedTouches().get(0);
  6745. double diffX = Math.abs(
  6746. touch.getClientX() - rowEventTouchStartingPoint.getX());
  6747. double diffY = Math.abs(
  6748. touch.getClientY() - rowEventTouchStartingPoint.getY());
  6749. // Cancel long tap if finger strays too far from
  6750. // starting point
  6751. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  6752. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  6753. sorter.cancelDelayedSort();
  6754. }
  6755. event.setHandled(true);
  6756. } else if (BrowserEvents.TOUCHEND
  6757. .equals(event.getDomEvent().getType())) {
  6758. if (event.getDomEvent().getTouches().length() > 1) {
  6759. return;
  6760. }
  6761. if (sorter.isDelayedSortScheduled()) {
  6762. // Not a long tap yet, perform single sort
  6763. sorter.cancelDelayedSort();
  6764. sorter.sort(event.getCell().getColumn(), false);
  6765. }
  6766. event.setHandled(true);
  6767. } else if (BrowserEvents.TOUCHCANCEL
  6768. .equals(event.getDomEvent().getType())) {
  6769. if (event.getDomEvent().getTouches().length() > 1) {
  6770. return;
  6771. }
  6772. sorter.cancelDelayedSort();
  6773. event.setHandled(true);
  6774. } else if (BrowserEvents.CLICK
  6775. .equals(event.getDomEvent().getType())) {
  6776. sorter.sort(event.getCell().getColumn(),
  6777. event.getDomEvent().getShiftKey());
  6778. }
  6779. }
  6780. };
  6781. @Override
  6782. @SuppressWarnings("deprecation")
  6783. public com.google.gwt.user.client.Element getSubPartElement(
  6784. String subPart) {
  6785. /*
  6786. * handles details[] (translated to spacer[] for Escalator), cell[],
  6787. * header[] and footer[]
  6788. */
  6789. // "#header[0][0]/DRAGhANDLE"
  6790. Element escalatorElement = escalator.getSubPartElement(
  6791. subPart.replaceFirst("^details\\[", "spacer["));
  6792. if (escalatorElement != null) {
  6793. int detailIdx = subPart.indexOf("/");
  6794. if (detailIdx > 0) {
  6795. String detail = subPart.substring(detailIdx + 1);
  6796. getLogger().severe("Looking up detail from index " + detailIdx
  6797. + " onward: \"" + detail + "\"");
  6798. if (detail.equalsIgnoreCase("content")) {
  6799. // XXX: Fix this to look up by class name!
  6800. return DOM.asOld(Element.as(escalatorElement.getChild(0)));
  6801. }
  6802. if (detail.equalsIgnoreCase("draghandle")) {
  6803. // XXX: Fix this to look up by class name!
  6804. return DOM.asOld(Element.as(escalatorElement.getChild(1)));
  6805. }
  6806. }
  6807. return DOM.asOld(escalatorElement);
  6808. }
  6809. SubPartArguments args = SubPartArguments.create(subPart);
  6810. Element editor = getSubPartElementEditor(args);
  6811. if (editor != null) {
  6812. return DOM.asOld(editor);
  6813. }
  6814. return null;
  6815. }
  6816. private Element getSubPartElementEditor(SubPartArguments args) {
  6817. if (!args.getType().equalsIgnoreCase("editor")
  6818. || editor.getState() != State.ACTIVE) {
  6819. return null;
  6820. }
  6821. if (args.getIndicesLength() == 0) {
  6822. return editor.editorOverlay;
  6823. } else if (args.getIndicesLength() == 1) {
  6824. int index = args.getIndex(0);
  6825. if (index >= columns.size()) {
  6826. return null;
  6827. }
  6828. escalator.scrollToColumn(index, ScrollDestination.ANY, 0);
  6829. Widget widget = editor.getWidget(columns.get(index));
  6830. if (widget != null) {
  6831. return widget.getElement();
  6832. }
  6833. // No widget for the column.
  6834. return null;
  6835. }
  6836. return null;
  6837. }
  6838. @Override
  6839. @SuppressWarnings("deprecation")
  6840. public String getSubPartName(
  6841. com.google.gwt.user.client.Element subElement) {
  6842. String escalatorStructureName = escalator.getSubPartName(subElement);
  6843. if (escalatorStructureName != null) {
  6844. return escalatorStructureName.replaceFirst("^spacer", "details");
  6845. }
  6846. String editorName = getSubPartNameEditor(subElement);
  6847. if (editorName != null) {
  6848. return editorName;
  6849. }
  6850. return null;
  6851. }
  6852. private String getSubPartNameEditor(Element subElement) {
  6853. if (editor.getState() != State.ACTIVE
  6854. || !editor.editorOverlay.isOrHasChild(subElement)) {
  6855. return null;
  6856. }
  6857. int i = 0;
  6858. for (Column<?, T> column : columns) {
  6859. if (editor.getWidget(column).getElement()
  6860. .isOrHasChild(subElement)) {
  6861. return "editor[" + i + "]";
  6862. }
  6863. ++i;
  6864. }
  6865. return "editor";
  6866. }
  6867. private void setSelectColumnRenderer(
  6868. final Renderer<Boolean> selectColumnRenderer) {
  6869. if (this.selectColumnRenderer == selectColumnRenderer) {
  6870. return;
  6871. }
  6872. if (this.selectColumnRenderer != null) {
  6873. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  6874. // End of Life for the old selection column renderer.
  6875. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  6876. }
  6877. // Clear field so frozen column logic in the remove method knows
  6878. // what to do
  6879. Column<?, T> colToRemove = selectionColumn;
  6880. selectionColumn = null;
  6881. removeColumnSkipSelectionColumnCheck(colToRemove);
  6882. cellFocusHandler.offsetRangeBy(-1);
  6883. }
  6884. this.selectColumnRenderer = selectColumnRenderer;
  6885. if (selectColumnRenderer != null) {
  6886. cellFocusHandler.offsetRangeBy(1);
  6887. selectionColumn = new SelectionColumn(selectColumnRenderer);
  6888. addColumnSkipSelectionColumnCheck(selectionColumn, 0);
  6889. selectionColumn.setEnabled(isEnabled());
  6890. selectionColumn.initDone();
  6891. } else {
  6892. selectionColumn = null;
  6893. refreshBody();
  6894. }
  6895. updateFrozenColumns();
  6896. }
  6897. /**
  6898. * Sets the current selection model.
  6899. * <p>
  6900. * This function will call {@link SelectionModel#setGrid(Grid)}.
  6901. *
  6902. * @param selectionModel
  6903. * a selection model implementation.
  6904. * @throws IllegalArgumentException
  6905. * if selection model argument is null
  6906. */
  6907. public void setSelectionModel(SelectionModel<T> selectionModel) {
  6908. if (selectionModel == null) {
  6909. throw new IllegalArgumentException("Selection model can't be null");
  6910. }
  6911. if (this.selectionModel != null) {
  6912. // Detach selection model from Grid.
  6913. this.selectionModel.setGrid(null);
  6914. }
  6915. this.selectionModel = selectionModel;
  6916. selectionModel.setGrid(this);
  6917. setSelectColumnRenderer(
  6918. this.selectionModel.getSelectionColumnRenderer());
  6919. // Refresh rendered rows to update selection, if it has changed
  6920. refreshBody();
  6921. }
  6922. /**
  6923. * Gets a reference to the current selection model.
  6924. *
  6925. * @return the currently used SelectionModel instance.
  6926. */
  6927. public SelectionModel<T> getSelectionModel() {
  6928. return selectionModel;
  6929. }
  6930. /**
  6931. * Sets current selection mode.
  6932. * <p>
  6933. * This is a shorthand method for {@link Grid#setSelectionModel}.
  6934. *
  6935. * @param mode
  6936. * a selection mode value
  6937. * @see SelectionMode
  6938. */
  6939. public void setSelectionMode(SelectionMode mode) {
  6940. SelectionModel<T> model = mode.createModel();
  6941. setSelectionModel(model);
  6942. }
  6943. /**
  6944. * Test if a row is selected.
  6945. *
  6946. * @param row
  6947. * a row object
  6948. * @return true, if the current selection model considers the provided row
  6949. * object selected.
  6950. */
  6951. public boolean isSelected(T row) {
  6952. return selectionModel.isSelected(row);
  6953. }
  6954. /**
  6955. * Select a row using the current selection model.
  6956. * <p>
  6957. * Only selection models implementing {@link SelectionModel.Single} and
  6958. * {@link SelectionModel.Multi} are supported; for anything else, an
  6959. * exception will be thrown.
  6960. *
  6961. * @param row
  6962. * a row object
  6963. * @return <code>true</code> iff the current selection changed
  6964. * @throws IllegalStateException
  6965. * if the current selection model is not an instance of
  6966. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6967. */
  6968. public boolean select(T row) {
  6969. if (selectionModel instanceof SelectionModel.Single<?>) {
  6970. return ((SelectionModel.Single<T>) selectionModel).select(row);
  6971. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6972. return ((SelectionModel.Multi<T>) selectionModel)
  6973. .select(Collections.singleton(row));
  6974. } else {
  6975. throw new IllegalStateException("Unsupported selection model");
  6976. }
  6977. }
  6978. /**
  6979. * Deselect a row using the current selection model.
  6980. * <p>
  6981. * Only selection models implementing {@link SelectionModel.Single} and
  6982. * {@link SelectionModel.Multi} are supported; for anything else, an
  6983. * exception will be thrown.
  6984. *
  6985. * @param row
  6986. * a row object
  6987. * @return <code>true</code> iff the current selection changed
  6988. * @throws IllegalStateException
  6989. * if the current selection model is not an instance of
  6990. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6991. */
  6992. public boolean deselect(T row) {
  6993. if (selectionModel instanceof SelectionModel.Single<?>) {
  6994. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  6995. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6996. return ((SelectionModel.Multi<T>) selectionModel)
  6997. .deselect(Collections.singleton(row));
  6998. } else {
  6999. throw new IllegalStateException("Unsupported selection model");
  7000. }
  7001. }
  7002. /**
  7003. * Deselect all rows using the current selection model.
  7004. *
  7005. * @return <code>true</code> iff the current selection changed
  7006. * @throws IllegalStateException
  7007. * if the current selection model is not an instance of
  7008. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  7009. */
  7010. public boolean deselectAll() {
  7011. if (selectionModel instanceof SelectionModel.Single<?>) {
  7012. Single<T> single = (SelectionModel.Single<T>) selectionModel;
  7013. if (single.getSelectedRow() != null) {
  7014. return single.deselect(single.getSelectedRow());
  7015. } else {
  7016. return false;
  7017. }
  7018. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  7019. return ((SelectionModel.Multi<T>) selectionModel).deselectAll();
  7020. } else {
  7021. throw new IllegalStateException("Unsupported selection model");
  7022. }
  7023. }
  7024. /**
  7025. * Gets last selected row from the current SelectionModel.
  7026. * <p>
  7027. * Only selection models implementing {@link SelectionModel.Single} are
  7028. * valid for this method; for anything else, use the
  7029. * {@link Grid#getSelectedRows()} method.
  7030. *
  7031. * @return a selected row reference, or null, if no row is selected
  7032. * @throws IllegalStateException
  7033. * if the current selection model is not an instance of
  7034. * {@link SelectionModel.Single}
  7035. */
  7036. public T getSelectedRow() {
  7037. if (selectionModel instanceof SelectionModel.Single<?>) {
  7038. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  7039. } else {
  7040. throw new IllegalStateException(
  7041. "Unsupported selection model; can not get single selected row");
  7042. }
  7043. }
  7044. /**
  7045. * Gets currently selected rows from the current selection model.
  7046. *
  7047. * @return a non-null collection containing all currently selected rows.
  7048. */
  7049. public Collection<T> getSelectedRows() {
  7050. return selectionModel.getSelectedRows();
  7051. }
  7052. @Override
  7053. public HandlerRegistration addSelectionHandler(
  7054. final SelectionHandler<T> handler) {
  7055. return addHandler(handler, SelectionEvent.getType());
  7056. }
  7057. /**
  7058. * Sets the current sort order using the fluid Sort API. Read the
  7059. * documentation for {@link Sort} for more information.
  7060. *
  7061. * @param s
  7062. * a sort instance
  7063. */
  7064. public void sort(Sort s) {
  7065. setSortOrder(s.build());
  7066. }
  7067. /**
  7068. * Sorts the Grid data in ascending order along one column.
  7069. *
  7070. * @param column
  7071. * a grid column reference
  7072. */
  7073. public <C> void sort(Column<C, T> column) {
  7074. sort(column, SortDirection.ASCENDING);
  7075. }
  7076. /**
  7077. * Sorts the Grid data along one column.
  7078. *
  7079. * @param column
  7080. * a grid column reference
  7081. * @param direction
  7082. * a sort direction value
  7083. */
  7084. public <C> void sort(Column<C, T> column, SortDirection direction) {
  7085. sort(Sort.by(column, direction));
  7086. }
  7087. /**
  7088. * Sets the sort order to use. Setting this causes the Grid to re-sort
  7089. * itself.
  7090. *
  7091. * @param order
  7092. * a sort order list. If set to null, the sort order is cleared.
  7093. */
  7094. public void setSortOrder(List<SortOrder> order) {
  7095. setSortOrder(order, false);
  7096. }
  7097. /**
  7098. * Clears the sort order and indicators without re-sorting.
  7099. */
  7100. private void clearSortOrder() {
  7101. sortOrder.clear();
  7102. refreshHeader();
  7103. }
  7104. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  7105. if (order != sortOrder) {
  7106. sortOrder.clear();
  7107. if (order != null) {
  7108. sortOrder.addAll(order);
  7109. }
  7110. }
  7111. sort(userOriginated);
  7112. }
  7113. /**
  7114. * Get a copy of the current sort order array.
  7115. *
  7116. * @return a copy of the current sort order array
  7117. */
  7118. public List<SortOrder> getSortOrder() {
  7119. return Collections.unmodifiableList(sortOrder);
  7120. }
  7121. /**
  7122. * Finds the sorting order for this column
  7123. */
  7124. private SortOrder getSortOrder(Column<?, ?> column) {
  7125. for (SortOrder order : getSortOrder()) {
  7126. if (order.getColumn() == column) {
  7127. return order;
  7128. }
  7129. }
  7130. return null;
  7131. }
  7132. /**
  7133. * Register a GWT event handler for a sorting event. This handler gets
  7134. * called whenever this Grid needs its data source to provide data sorted in
  7135. * a specific order.
  7136. *
  7137. * @param handler
  7138. * a sort event handler
  7139. * @return the registration for the event
  7140. */
  7141. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  7142. return addHandler(handler, SortEvent.getType());
  7143. }
  7144. /**
  7145. * Register a GWT event handler for a select all event. This handler gets
  7146. * called whenever Grid needs all rows selected.
  7147. *
  7148. * @param handler
  7149. * a select all event handler
  7150. */
  7151. public HandlerRegistration addSelectAllHandler(
  7152. SelectAllHandler<T> handler) {
  7153. return addHandler(handler, SelectAllEvent.getType());
  7154. }
  7155. /**
  7156. * Register a GWT event handler for a data available event. This handler
  7157. * gets called whenever the {@link DataSource} for this Grid has new data
  7158. * available.
  7159. * <p>
  7160. * This handle will be fired with the current available data after
  7161. * registration is done.
  7162. *
  7163. * @param handler
  7164. * a data available event handler
  7165. * @return the registartion for the event
  7166. */
  7167. public HandlerRegistration addDataAvailableHandler(
  7168. final DataAvailableHandler handler) {
  7169. // Deferred call to handler with current row range
  7170. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7171. @Override
  7172. public void execute() {
  7173. if (!dataSource.isWaitingForData()) {
  7174. handler.onDataAvailable(
  7175. new DataAvailableEvent(currentDataAvailable));
  7176. }
  7177. }
  7178. });
  7179. return addHandler(handler, DataAvailableEvent.TYPE);
  7180. }
  7181. /**
  7182. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  7183. * fired when a KeyDown event occurs while cell focus is in the Body of this
  7184. * Grid.
  7185. *
  7186. * @param handler
  7187. * the key handler to register
  7188. * @return the registration for the event
  7189. */
  7190. public HandlerRegistration addBodyKeyDownHandler(
  7191. BodyKeyDownHandler handler) {
  7192. return addHandler(handler, GridKeyDownEvent.TYPE);
  7193. }
  7194. /**
  7195. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  7196. * fired when a KeyUp event occurs while cell focus is in the Body of this
  7197. * Grid.
  7198. *
  7199. * @param handler
  7200. * the key handler to register
  7201. * @return the registration for the event
  7202. */
  7203. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  7204. return addHandler(handler, GridKeyUpEvent.TYPE);
  7205. }
  7206. /**
  7207. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  7208. * is fired when a KeyPress event occurs while cell focus is in the Body of
  7209. * this Grid.
  7210. *
  7211. * @param handler
  7212. * the key handler to register
  7213. * @return the registration for the event
  7214. */
  7215. public HandlerRegistration addBodyKeyPressHandler(
  7216. BodyKeyPressHandler handler) {
  7217. return addHandler(handler, GridKeyPressEvent.TYPE);
  7218. }
  7219. /**
  7220. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  7221. * is fired when a KeyDown event occurs while cell focus is in the Header of
  7222. * this Grid.
  7223. *
  7224. * @param handler
  7225. * the key handler to register
  7226. * @return the registration for the event
  7227. */
  7228. public HandlerRegistration addHeaderKeyDownHandler(
  7229. HeaderKeyDownHandler handler) {
  7230. return addHandler(handler, GridKeyDownEvent.TYPE);
  7231. }
  7232. /**
  7233. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  7234. * fired when a KeyUp event occurs while cell focus is in the Header of this
  7235. * Grid.
  7236. *
  7237. * @param handler
  7238. * the key handler to register
  7239. * @return the registration for the event
  7240. */
  7241. public HandlerRegistration addHeaderKeyUpHandler(
  7242. HeaderKeyUpHandler handler) {
  7243. return addHandler(handler, GridKeyUpEvent.TYPE);
  7244. }
  7245. /**
  7246. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  7247. * is fired when a KeyPress event occurs while cell focus is in the Header
  7248. * of this Grid.
  7249. *
  7250. * @param handler
  7251. * the key handler to register
  7252. * @return the registration for the event
  7253. */
  7254. public HandlerRegistration addHeaderKeyPressHandler(
  7255. HeaderKeyPressHandler handler) {
  7256. return addHandler(handler, GridKeyPressEvent.TYPE);
  7257. }
  7258. /**
  7259. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  7260. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  7261. * this Grid.
  7262. *
  7263. * @param handler
  7264. * the key handler to register
  7265. * @return the registration for the event
  7266. */
  7267. public HandlerRegistration addFooterKeyDownHandler(
  7268. FooterKeyDownHandler handler) {
  7269. return addHandler(handler, GridKeyDownEvent.TYPE);
  7270. }
  7271. /**
  7272. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  7273. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  7274. * Grid.
  7275. *
  7276. * @param handler
  7277. * the key handler to register
  7278. * @return the registration for the event
  7279. */
  7280. public HandlerRegistration addFooterKeyUpHandler(
  7281. FooterKeyUpHandler handler) {
  7282. return addHandler(handler, GridKeyUpEvent.TYPE);
  7283. }
  7284. /**
  7285. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  7286. * is fired when a KeyPress event occurs while cell focus is in the Footer
  7287. * of this Grid.
  7288. *
  7289. * @param handler
  7290. * the key handler to register
  7291. * @return the registration for the event
  7292. */
  7293. public HandlerRegistration addFooterKeyPressHandler(
  7294. FooterKeyPressHandler handler) {
  7295. return addHandler(handler, GridKeyPressEvent.TYPE);
  7296. }
  7297. /**
  7298. * Register a BodyClickHandler to this Grid. The event for this handler is
  7299. * fired when a Click event occurs in the Body of this Grid.
  7300. *
  7301. * @param handler
  7302. * the click handler to register
  7303. * @return the registration for the event
  7304. */
  7305. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  7306. return addHandler(handler, GridClickEvent.TYPE);
  7307. }
  7308. /**
  7309. * Register a HeaderClickHandler to this Grid. The event for this handler is
  7310. * fired when a Click event occurs in the Header of this Grid.
  7311. *
  7312. * @param handler
  7313. * the click handler to register
  7314. * @return the registration for the event
  7315. */
  7316. public HandlerRegistration addHeaderClickHandler(
  7317. HeaderClickHandler handler) {
  7318. return addHandler(handler, GridClickEvent.TYPE);
  7319. }
  7320. /**
  7321. * Register a FooterClickHandler to this Grid. The event for this handler is
  7322. * fired when a Click event occurs in the Footer of this Grid.
  7323. *
  7324. * @param handler
  7325. * the click handler to register
  7326. * @return the registration for the event
  7327. */
  7328. public HandlerRegistration addFooterClickHandler(
  7329. FooterClickHandler handler) {
  7330. return addHandler(handler, GridClickEvent.TYPE);
  7331. }
  7332. /**
  7333. * Register a BodyDoubleClickHandler to this Grid. The event for this
  7334. * handler is fired when a double click event occurs in the Body of this
  7335. * Grid.
  7336. *
  7337. * @param handler
  7338. * the double click handler to register
  7339. * @return the registration for the event
  7340. */
  7341. public HandlerRegistration addBodyDoubleClickHandler(
  7342. BodyDoubleClickHandler handler) {
  7343. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7344. }
  7345. /**
  7346. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  7347. * handler is fired when a double click event occurs in the Header of this
  7348. * Grid.
  7349. *
  7350. * @param handler
  7351. * the double click handler to register
  7352. * @return the registration for the event
  7353. */
  7354. public HandlerRegistration addHeaderDoubleClickHandler(
  7355. HeaderDoubleClickHandler handler) {
  7356. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7357. }
  7358. /**
  7359. * Register a FooterDoubleClickHandler to this Grid. The event for this
  7360. * handler is fired when a double click event occurs in the Footer of this
  7361. * Grid.
  7362. *
  7363. * @param handler
  7364. * the double click handler to register
  7365. * @return the registration for the event
  7366. */
  7367. public HandlerRegistration addFooterDoubleClickHandler(
  7368. FooterDoubleClickHandler handler) {
  7369. return addHandler(handler, GridDoubleClickEvent.TYPE);
  7370. }
  7371. /**
  7372. * Register a column reorder handler to this Grid. The event for this
  7373. * handler is fired when the Grid's columns are reordered.
  7374. *
  7375. * @since 7.5.0
  7376. * @param handler
  7377. * the handler for the event
  7378. * @return the registration for the event
  7379. */
  7380. public HandlerRegistration addColumnReorderHandler(
  7381. ColumnReorderHandler<T> handler) {
  7382. return addHandler(handler, ColumnReorderEvent.getType());
  7383. }
  7384. /**
  7385. * Register a column visibility change handler to this Grid. The event for
  7386. * this handler is fired when the Grid's columns change visibility.
  7387. *
  7388. * @since 7.5.0
  7389. * @param handler
  7390. * the handler for the event
  7391. * @return the registration for the event
  7392. */
  7393. public HandlerRegistration addColumnVisibilityChangeHandler(
  7394. ColumnVisibilityChangeHandler<T> handler) {
  7395. return addHandler(handler, ColumnVisibilityChangeEvent.getType());
  7396. }
  7397. /**
  7398. * Register a column resize handler to this Grid. The event for this handler
  7399. * is fired when the Grid's columns are resized.
  7400. *
  7401. * @since 7.6
  7402. * @param handler
  7403. * the handler for the event
  7404. * @return the registration for the event
  7405. */
  7406. public HandlerRegistration addColumnResizeHandler(
  7407. ColumnResizeHandler<T> handler) {
  7408. return addHandler(handler, ColumnResizeEvent.getType());
  7409. }
  7410. /**
  7411. * Register a enabled status change handler to this Grid. The event for this
  7412. * handler is fired when the Grid changes from disabled to enabled and
  7413. * vice-versa.
  7414. *
  7415. * @param handler
  7416. * the handler for the event
  7417. * @return the registration for the event
  7418. */
  7419. public HandlerRegistration addEnabledHandler(GridEnabledHandler handler) {
  7420. return addHandler(handler, GridEnabledEvent.TYPE);
  7421. }
  7422. public HandlerRegistration addRowHeightChangedHandler(
  7423. RowHeightChangedHandler handler) {
  7424. return escalator.addHandler(handler, RowHeightChangedEvent.TYPE);
  7425. }
  7426. /**
  7427. * Adds a low-level DOM event handler to this Grid. The handler is inserted
  7428. * into the given position in the list of handlers. The handlers are invoked
  7429. * in order. If the
  7430. * {@link GridEventHandler#onEvent(Event, EventCellReference) onEvent}
  7431. * method of a handler returns true, subsequent handlers are not invoked.
  7432. *
  7433. * @param index
  7434. * the index to insert the handler to
  7435. * @param handler
  7436. * the handler to add
  7437. */
  7438. public void addBrowserEventHandler(int index, GridEventHandler<T> handler) {
  7439. browserEventHandlers.add(index, handler);
  7440. }
  7441. /**
  7442. * Apply sorting to data source.
  7443. */
  7444. private void sort(boolean userOriginated) {
  7445. refreshHeader();
  7446. fireEvent(new SortEvent<T>(this,
  7447. Collections.unmodifiableList(sortOrder), userOriginated));
  7448. }
  7449. private int getLastVisibleRowIndex() {
  7450. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  7451. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  7452. Element lastRow;
  7453. do {
  7454. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  7455. } while (lastRow.getAbsoluteTop() > footerTop);
  7456. return lastRowIndex;
  7457. }
  7458. private int getFirstVisibleRowIndex() {
  7459. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  7460. int headerBottom = escalator.getHeader().getElement()
  7461. .getAbsoluteBottom();
  7462. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  7463. while (firstRow.getAbsoluteBottom() < headerBottom) {
  7464. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  7465. }
  7466. return firstRowIndex;
  7467. }
  7468. /**
  7469. * Adds a scroll handler to this grid
  7470. *
  7471. * @param handler
  7472. * the scroll handler to add
  7473. * @return a handler registration for the registered scroll handler
  7474. */
  7475. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7476. return addHandler(handler, ScrollEvent.TYPE);
  7477. }
  7478. @Override
  7479. public boolean isWorkPending() {
  7480. return escalator.isWorkPending() || dataSource.isWaitingForData()
  7481. || autoColumnWidthsRecalculator.isScheduled()
  7482. || editor.isWorkPending();
  7483. }
  7484. /**
  7485. * Returns whether columns can be reordered with drag and drop.
  7486. *
  7487. * @since 7.5.0
  7488. * @return <code>true</code> if columns can be reordered, false otherwise
  7489. */
  7490. public boolean isColumnReorderingAllowed() {
  7491. return columnReorderingAllowed;
  7492. }
  7493. /**
  7494. * Sets whether column reordering with drag and drop is allowed or not.
  7495. *
  7496. * @since 7.5.0
  7497. * @param columnReorderingAllowed
  7498. * specifies whether column reordering is allowed
  7499. */
  7500. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  7501. this.columnReorderingAllowed = columnReorderingAllowed;
  7502. }
  7503. /**
  7504. * Sets a new column order for the grid. All columns which are not ordered
  7505. * here will remain in the order they were before as the last columns of
  7506. * grid.
  7507. *
  7508. * @param orderedColumns
  7509. * array of columns in wanted order
  7510. */
  7511. public void setColumnOrder(Column<?, T>... orderedColumns) {
  7512. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  7513. // Trigger ComplexRenderer.destroy for old content
  7514. conf.removeColumns(0, conf.getColumnCount());
  7515. List<Column<?, T>> newOrder = new ArrayList<Column<?, T>>();
  7516. if (selectionColumn != null) {
  7517. newOrder.add(selectionColumn);
  7518. }
  7519. int i = 0;
  7520. for (Column<?, T> column : orderedColumns) {
  7521. if (columns.contains(column)) {
  7522. newOrder.add(column);
  7523. ++i;
  7524. } else {
  7525. throw new IllegalArgumentException("Given column at index " + i
  7526. + " does not exist in Grid");
  7527. }
  7528. }
  7529. if (columns.size() != newOrder.size()) {
  7530. columns.removeAll(newOrder);
  7531. newOrder.addAll(columns);
  7532. }
  7533. columns = newOrder;
  7534. List<Column<?, T>> visibleColumns = getVisibleColumns();
  7535. // Do ComplexRenderer.init and render new content
  7536. conf.insertColumns(0, visibleColumns.size());
  7537. // Number of frozen columns should be kept same #16901
  7538. updateFrozenColumns();
  7539. // Update column widths.
  7540. for (Column<?, T> column : columns) {
  7541. column.reapplyWidth();
  7542. }
  7543. // Recalculate all the colspans
  7544. for (HeaderRow row : header.getRows()) {
  7545. row.calculateColspans();
  7546. }
  7547. for (FooterRow row : footer.getRows()) {
  7548. row.calculateColspans();
  7549. }
  7550. columnHider.updateTogglesOrder();
  7551. fireEvent(new ColumnReorderEvent<T>());
  7552. }
  7553. /**
  7554. * Sets the style generator that is used for generating styles for cells
  7555. *
  7556. * @param cellStyleGenerator
  7557. * the cell style generator to set, or <code>null</code> to
  7558. * remove a previously set generator
  7559. */
  7560. public void setCellStyleGenerator(
  7561. CellStyleGenerator<T> cellStyleGenerator) {
  7562. this.cellStyleGenerator = cellStyleGenerator;
  7563. refreshBody();
  7564. }
  7565. /**
  7566. * Gets the style generator that is used for generating styles for cells
  7567. *
  7568. * @return the cell style generator, or <code>null</code> if no generator is
  7569. * set
  7570. */
  7571. public CellStyleGenerator<T> getCellStyleGenerator() {
  7572. return cellStyleGenerator;
  7573. }
  7574. /**
  7575. * Sets the style generator that is used for generating styles for rows
  7576. *
  7577. * @param rowStyleGenerator
  7578. * the row style generator to set, or <code>null</code> to remove
  7579. * a previously set generator
  7580. */
  7581. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  7582. this.rowStyleGenerator = rowStyleGenerator;
  7583. refreshBody();
  7584. }
  7585. /**
  7586. * Gets the style generator that is used for generating styles for rows
  7587. *
  7588. * @return the row style generator, or <code>null</code> if no generator is
  7589. * set
  7590. */
  7591. public RowStyleGenerator<T> getRowStyleGenerator() {
  7592. return rowStyleGenerator;
  7593. }
  7594. private static void setCustomStyleName(Element element, String styleName) {
  7595. assert element != null;
  7596. String oldStyleName = element
  7597. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  7598. if (!SharedUtil.equals(oldStyleName, styleName)) {
  7599. if (oldStyleName != null && !oldStyleName.isEmpty()) {
  7600. element.removeClassName(oldStyleName);
  7601. }
  7602. if (styleName != null && !styleName.isEmpty()) {
  7603. element.addClassName(styleName);
  7604. }
  7605. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  7606. }
  7607. }
  7608. /**
  7609. * Opens the editor over the row with the given index.
  7610. *
  7611. * @param rowIndex
  7612. * the index of the row to be edited
  7613. *
  7614. * @throws IllegalStateException
  7615. * if the editor is not enabled
  7616. * @throws IllegalStateException
  7617. * if the editor is already in edit mode
  7618. */
  7619. public void editRow(int rowIndex) {
  7620. editor.editRow(rowIndex);
  7621. }
  7622. /**
  7623. * Returns whether the editor is currently open on some row.
  7624. *
  7625. * @return {@code true} if the editor is active, {@code false} otherwise.
  7626. */
  7627. public boolean isEditorActive() {
  7628. return editor.getState() != State.INACTIVE;
  7629. }
  7630. /**
  7631. * Saves any unsaved changes in the editor to the data source.
  7632. *
  7633. * @throws IllegalStateException
  7634. * if the editor is not enabled
  7635. * @throws IllegalStateException
  7636. * if the editor is not in edit mode
  7637. */
  7638. public void saveEditor() {
  7639. editor.save();
  7640. }
  7641. /**
  7642. * Cancels the currently active edit and hides the editor. Any changes that
  7643. * are not {@link #saveEditor() saved} are lost.
  7644. *
  7645. * @throws IllegalStateException
  7646. * if the editor is not enabled
  7647. * @throws IllegalStateException
  7648. * if the editor is not in edit mode
  7649. */
  7650. public void cancelEditor() {
  7651. editor.cancel();
  7652. }
  7653. /**
  7654. * Returns the handler responsible for binding data and editor widgets to
  7655. * the editor.
  7656. *
  7657. * @return the editor handler or null if not set
  7658. */
  7659. public EditorHandler<T> getEditorHandler() {
  7660. return editor.getHandler();
  7661. }
  7662. /**
  7663. * Sets the handler responsible for binding data and editor widgets to the
  7664. * editor.
  7665. *
  7666. * @param rowHandler
  7667. * the new editor handler
  7668. *
  7669. * @throws IllegalStateException
  7670. * if the editor is currently in edit mode
  7671. */
  7672. public void setEditorHandler(EditorHandler<T> handler) {
  7673. editor.setHandler(handler);
  7674. }
  7675. /**
  7676. * Returns the enabled state of the editor.
  7677. *
  7678. * @return true if editing is enabled, false otherwise
  7679. */
  7680. public boolean isEditorEnabled() {
  7681. return editor.isEnabled();
  7682. }
  7683. /**
  7684. * Sets the enabled state of the editor.
  7685. *
  7686. * @param enabled
  7687. * true to enable editing, false to disable
  7688. *
  7689. * @throws IllegalStateException
  7690. * if in edit mode and trying to disable
  7691. * @throws IllegalStateException
  7692. * if the editor handler is not set
  7693. */
  7694. public void setEditorEnabled(boolean enabled) {
  7695. editor.setEnabled(enabled);
  7696. }
  7697. /**
  7698. * Returns the editor widget associated with the given column. If the editor
  7699. * is not active, returns null.
  7700. *
  7701. * @param column
  7702. * the column
  7703. * @return the widget if the editor is open, null otherwise
  7704. */
  7705. public Widget getEditorWidget(Column<?, T> column) {
  7706. return editor.getWidget(column);
  7707. }
  7708. /**
  7709. * Sets the caption on the save button in the Grid editor.
  7710. *
  7711. * @param saveCaption
  7712. * the caption to set
  7713. * @throws IllegalArgumentException
  7714. * if {@code saveCaption} is {@code null}
  7715. */
  7716. public void setEditorSaveCaption(String saveCaption)
  7717. throws IllegalArgumentException {
  7718. editor.setSaveCaption(saveCaption);
  7719. }
  7720. /**
  7721. * Gets the current caption on the save button in the Grid editor.
  7722. *
  7723. * @return the current caption on the save button
  7724. */
  7725. public String getEditorSaveCaption() {
  7726. return editor.getSaveCaption();
  7727. }
  7728. /**
  7729. * Sets the caption on the cancel button in the Grid editor.
  7730. *
  7731. * @param cancelCaption
  7732. * the caption to set
  7733. * @throws IllegalArgumentException
  7734. * if {@code cancelCaption} is {@code null}
  7735. */
  7736. public void setEditorCancelCaption(String cancelCaption)
  7737. throws IllegalArgumentException {
  7738. editor.setCancelCaption(cancelCaption);
  7739. }
  7740. /**
  7741. * Gets the caption on the cancel button in the Grid editor.
  7742. *
  7743. * @return the current caption on the cancel button
  7744. */
  7745. public String getEditorCancelCaption() {
  7746. return editor.getCancelCaption();
  7747. }
  7748. @Override
  7749. protected void onAttach() {
  7750. super.onAttach();
  7751. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  7752. setEscalatorSizeFromDataSource();
  7753. }
  7754. // Grid was just attached to DOM. Column widths should be calculated.
  7755. recalculateColumnWidths();
  7756. for (int row : reattachVisibleDetails) {
  7757. setDetailsVisible(row, true);
  7758. }
  7759. reattachVisibleDetails.clear();
  7760. }
  7761. @Override
  7762. protected void onDetach() {
  7763. Set<Integer> details = new HashSet<Integer>(visibleDetails);
  7764. reattachVisibleDetails.clear();
  7765. reattachVisibleDetails.addAll(details);
  7766. for (int row : details) {
  7767. setDetailsVisible(row, false);
  7768. }
  7769. super.onDetach();
  7770. }
  7771. @Override
  7772. public void onResize() {
  7773. super.onResize();
  7774. /*
  7775. * Delay calculation to be deferred so Escalator can do it's magic.
  7776. */
  7777. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7778. @Override
  7779. public void execute() {
  7780. if (escalator
  7781. .getInnerWidth() != autoColumnWidthsRecalculator.lastCalculatedInnerWidth) {
  7782. recalculateColumnWidths();
  7783. }
  7784. // Vertical resizing could make editor positioning invalid so it
  7785. // needs to be recalculated on resize
  7786. if (isEditorActive()) {
  7787. editor.updateVerticalScrollPosition();
  7788. }
  7789. // if there is a resize, we need to refresh the body to avoid an
  7790. // off-by-one error which occurs when the user scrolls all the
  7791. // way to the bottom.
  7792. refreshBody();
  7793. }
  7794. });
  7795. }
  7796. /**
  7797. * Grid does not support adding Widgets this way.
  7798. * <p>
  7799. * This method is implemented only because removing widgets from Grid (added
  7800. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7801. *
  7802. * @param w
  7803. * irrelevant
  7804. * @throws UnsupportedOperationException
  7805. * always
  7806. */
  7807. @Override
  7808. @Deprecated
  7809. public void add(Widget w) {
  7810. throw new UnsupportedOperationException(
  7811. "Cannot add widgets to Grid with this method");
  7812. }
  7813. /**
  7814. * Grid does not support clearing Widgets this way.
  7815. * <p>
  7816. * This method is implemented only because removing widgets from Grid (added
  7817. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7818. *
  7819. * @throws UnsupportedOperationException
  7820. * always
  7821. */
  7822. @Override
  7823. @Deprecated
  7824. public void clear() {
  7825. throw new UnsupportedOperationException(
  7826. "Cannot clear widgets from Grid this way");
  7827. }
  7828. /**
  7829. * Grid does not support iterating through Widgets this way.
  7830. * <p>
  7831. * This method is implemented only because removing widgets from Grid (added
  7832. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7833. *
  7834. * @return never
  7835. * @throws UnsupportedOperationException
  7836. * always
  7837. */
  7838. @Override
  7839. @Deprecated
  7840. public Iterator<Widget> iterator() {
  7841. throw new UnsupportedOperationException(
  7842. "Cannot iterate through widgets in Grid this way");
  7843. }
  7844. /**
  7845. * Grid does not support removing Widgets this way.
  7846. * <p>
  7847. * This method is implemented only because removing widgets from Grid (added
  7848. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7849. *
  7850. * @return always <code>false</code>
  7851. */
  7852. @Override
  7853. @Deprecated
  7854. public boolean remove(Widget w) {
  7855. /*
  7856. * This is the method that is the sole reason to have Grid implement
  7857. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  7858. * corresponding Widget will call removeFromParent() on itself. GWT will
  7859. * check there that its parent (i.e. Grid) implements HasWidgets, and
  7860. * will call this remove(Widget) method.
  7861. *
  7862. * tl;dr: all this song and dance to make sure GWT's sanity checks
  7863. * aren't triggered, even though they effectively do nothing interesting
  7864. * from Grid's perspective.
  7865. */
  7866. return false;
  7867. }
  7868. /**
  7869. * Accesses the package private method Widget#setParent()
  7870. *
  7871. * @param widget
  7872. * The widget to access
  7873. * @param parent
  7874. * The parent to set
  7875. */
  7876. private static final native void setParent(Widget widget, Grid<?> parent)
  7877. /*-{
  7878. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  7879. }-*/;
  7880. private static final native void onAttach(Widget widget)
  7881. /*-{
  7882. widget.@Widget::onAttach()();
  7883. }-*/;
  7884. private static final native void onDetach(Widget widget)
  7885. /*-{
  7886. widget.@Widget::onDetach()();
  7887. }-*/;
  7888. @Override
  7889. protected void doAttachChildren() {
  7890. if (sidebar.getParent() == this) {
  7891. onAttach(sidebar);
  7892. }
  7893. }
  7894. @Override
  7895. protected void doDetachChildren() {
  7896. if (sidebar.getParent() == this) {
  7897. onDetach(sidebar);
  7898. }
  7899. }
  7900. private void attachWidget(Widget w, Element parent) {
  7901. assert w.getParent() == null;
  7902. parent.appendChild(w.getElement());
  7903. setParent(w, this);
  7904. }
  7905. private void detachWidget(Widget w) {
  7906. assert w.getParent() == this;
  7907. setParent(w, null);
  7908. w.getElement().removeFromParent();
  7909. }
  7910. /**
  7911. * Resets all cached pixel sizes and reads new values from the DOM. This
  7912. * methods should be used e.g. when styles affecting the dimensions of
  7913. * elements in this grid have been changed.
  7914. */
  7915. public void resetSizesFromDom() {
  7916. getEscalator().resetSizesFromDom();
  7917. }
  7918. /**
  7919. * Sets a new details generator for row details.
  7920. * <p>
  7921. * The currently opened row details will be re-rendered.
  7922. *
  7923. * @since 7.5.0
  7924. * @param detailsGenerator
  7925. * the details generator to set
  7926. * @throws IllegalArgumentException
  7927. * if detailsGenerator is <code>null</code>;
  7928. */
  7929. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  7930. throws IllegalArgumentException {
  7931. if (detailsGenerator == null) {
  7932. throw new IllegalArgumentException(
  7933. "Details generator may not be null");
  7934. }
  7935. for (Integer index : visibleDetails) {
  7936. setDetailsVisible(index, false);
  7937. }
  7938. this.detailsGenerator = detailsGenerator;
  7939. // this will refresh all visible spacers
  7940. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  7941. }
  7942. /**
  7943. * Gets the current details generator for row details.
  7944. *
  7945. * @since 7.5.0
  7946. * @return the detailsGenerator the current details generator
  7947. */
  7948. public DetailsGenerator getDetailsGenerator() {
  7949. return detailsGenerator;
  7950. }
  7951. /**
  7952. * Shows or hides the details for a specific row.
  7953. * <p>
  7954. * This method does nothing if trying to set show already-visible details,
  7955. * or hide already-hidden details.
  7956. *
  7957. * @since 7.5.0
  7958. * @param rowIndex
  7959. * the index of the affected row
  7960. * @param visible
  7961. * <code>true</code> to show the details, or <code>false</code>
  7962. * to hide them
  7963. * @see #isDetailsVisible(int)
  7964. */
  7965. public void setDetailsVisible(int rowIndex, boolean visible) {
  7966. if (DetailsGenerator.NULL.equals(detailsGenerator)) {
  7967. return;
  7968. }
  7969. Integer rowIndexInteger = Integer.valueOf(rowIndex);
  7970. /*
  7971. * We want to prevent opening a details row twice, so any subsequent
  7972. * openings (or closings) of details is a NOOP.
  7973. *
  7974. * When a details row is opened, it is given an arbitrary height
  7975. * (because Escalator requires a height upon opening). Only when it's
  7976. * opened, Escalator will ask the generator to generate a widget, which
  7977. * we then can measure. When measured, we correct the initial height by
  7978. * the original height.
  7979. *
  7980. * Without this check, we would override the measured height, and revert
  7981. * back to the initial, arbitrary, height which would most probably be
  7982. * wrong.
  7983. *
  7984. * see GridSpacerUpdater.init for implementation details.
  7985. */
  7986. boolean isVisible = isDetailsVisible(rowIndex);
  7987. if (visible && !isVisible) {
  7988. escalator.getBody().setSpacer(rowIndex, DETAILS_ROW_INITIAL_HEIGHT);
  7989. visibleDetails.add(rowIndexInteger);
  7990. }
  7991. else if (!visible && isVisible) {
  7992. escalator.getBody().setSpacer(rowIndex, -1);
  7993. visibleDetails.remove(rowIndexInteger);
  7994. }
  7995. }
  7996. /**
  7997. * Check whether the details for a row is visible or not.
  7998. *
  7999. * @since 7.5.0
  8000. * @param rowIndex
  8001. * the index of the row for which to check details
  8002. * @return <code>true</code> iff the details for the given row is visible
  8003. * @see #setDetailsVisible(int, boolean)
  8004. */
  8005. public boolean isDetailsVisible(int rowIndex) {
  8006. return visibleDetails.contains(Integer.valueOf(rowIndex));
  8007. }
  8008. /**
  8009. * Update details row height.
  8010. *
  8011. * @since 7.7.11
  8012. * @param rowIndex
  8013. * the index of the row for which to update details height
  8014. * @param height
  8015. * new height of the details row
  8016. */
  8017. public void setDetailsHeight(int rowIndex, double height) {
  8018. escalator.getBody().setSpacer(rowIndex, height);
  8019. }
  8020. /**
  8021. * Requests that the column widths should be recalculated.
  8022. * <p>
  8023. * The actual recalculation is not necessarily done immediately so you
  8024. * cannot rely on the columns being the correct width after the call
  8025. * returns.
  8026. *
  8027. * @since 7.4.1
  8028. */
  8029. public void recalculateColumnWidths() {
  8030. autoColumnWidthsRecalculator.schedule();
  8031. }
  8032. /**
  8033. * Gets the customizable menu bar that is by default used for toggling
  8034. * column hidability. The application developer is allowed to add their
  8035. * custom items to the end of the menu, but should try to avoid modifying
  8036. * the items in the beginning of the menu that control the column hiding if
  8037. * any columns are marked as hidable. A toggle for opening the menu will be
  8038. * displayed whenever the menu contains at least one item.
  8039. *
  8040. * @since 7.5.0
  8041. * @return the menu bar
  8042. */
  8043. public MenuBar getSidebarMenu() {
  8044. return sidebar.menuBar;
  8045. }
  8046. /**
  8047. * Tests whether the sidebar menu is currently open.
  8048. *
  8049. * @since 7.5.0
  8050. * @see #getSidebarMenu()
  8051. * @return <code>true</code> if the sidebar is open; <code>false</code> if
  8052. * it is closed
  8053. */
  8054. public boolean isSidebarOpen() {
  8055. return sidebar.isOpen();
  8056. }
  8057. /**
  8058. * Sets whether the sidebar menu is open.
  8059. *
  8060. *
  8061. * @since 7.5.0
  8062. * @see #getSidebarMenu()
  8063. * @see #isSidebarOpen()
  8064. * @param sidebarOpen
  8065. * <code>true</code> to open the sidebar; <code>false</code> to
  8066. * close it
  8067. */
  8068. public void setSidebarOpen(boolean sidebarOpen) {
  8069. if (sidebarOpen) {
  8070. sidebar.open();
  8071. } else {
  8072. sidebar.close();
  8073. }
  8074. }
  8075. @Override
  8076. public int getTabIndex() {
  8077. return FocusUtil.getTabIndex(this);
  8078. }
  8079. @Override
  8080. public void setAccessKey(char key) {
  8081. FocusUtil.setAccessKey(this, key);
  8082. }
  8083. @Override
  8084. public void setFocus(boolean focused) {
  8085. FocusUtil.setFocus(this, focused);
  8086. }
  8087. @Override
  8088. public void setTabIndex(int index) {
  8089. FocusUtil.setTabIndex(this, index);
  8090. }
  8091. @Override
  8092. public void focus() {
  8093. setFocus(true);
  8094. }
  8095. /**
  8096. * Sets the buffered editor mode.
  8097. *
  8098. * @since 7.6
  8099. * @param editorUnbuffered
  8100. * <code>true</code> to enable buffered editor,
  8101. * <code>false</code> to disable it
  8102. */
  8103. public void setEditorBuffered(boolean editorBuffered) {
  8104. editor.setBuffered(editorBuffered);
  8105. }
  8106. /**
  8107. * Gets the buffered editor mode.
  8108. *
  8109. * @since 7.6
  8110. * @return <code>true</code> if buffered editor is enabled,
  8111. * <code>false</code> otherwise
  8112. */
  8113. public boolean isEditorBuffered() {
  8114. return editor.isBuffered();
  8115. }
  8116. /**
  8117. * Returns the {@link EventCellReference} for the latest event fired from
  8118. * this Grid.
  8119. * <p>
  8120. * Note: This cell reference will be updated when firing the next event.
  8121. *
  8122. * @since 7.5
  8123. * @return event cell reference
  8124. */
  8125. public EventCellReference<T> getEventCell() {
  8126. return eventCell;
  8127. }
  8128. /**
  8129. * Returns a CellReference for the cell to which the given element belongs
  8130. * to.
  8131. *
  8132. * @since 7.6
  8133. * @param element
  8134. * Element to find from the cell's content.
  8135. * @return CellReference or <code>null</code> if cell was not found.
  8136. */
  8137. public CellReference<T> getCellReference(Element element) {
  8138. RowContainer container = getEscalator().findRowContainer(element);
  8139. if (container != null) {
  8140. Cell cell = container.getCell(element);
  8141. if (cell != null) {
  8142. EventCellReference<T> cellRef = new EventCellReference<T>(this);
  8143. cellRef.set(cell, getSectionFromContainer(container));
  8144. return cellRef;
  8145. }
  8146. }
  8147. return null;
  8148. }
  8149. /**
  8150. * Checks if selection by the user is allowed in the grid.
  8151. *
  8152. * @return <code>true</code> if selection by the user is allowed by the
  8153. * selection model (the default), <code>false</code> otherwise
  8154. * @since 7.7.7
  8155. */
  8156. public boolean isUserSelectionAllowed() {
  8157. if (!(getSelectionModel() instanceof HasUserSelectionAllowed)) {
  8158. // Selection model does not support toggling user selection allowed
  8159. // - old default is to always allow selection
  8160. return true;
  8161. }
  8162. return ((HasUserSelectionAllowed) getSelectionModel())
  8163. .isUserSelectionAllowed();
  8164. }
  8165. }