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

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