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

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