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

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