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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920
  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 (rowIndex == rowWithFocus
  2217. && cellFocusRange.contains(columnIndexDOM)
  2218. && container == this.containerWithFocus) {
  2219. return;
  2220. }
  2221. int oldRow = rowWithFocus;
  2222. rowWithFocus = rowIndex;
  2223. Range oldRange = cellFocusRange;
  2224. if (container == escalator.getBody()) {
  2225. scrollToRow(rowWithFocus);
  2226. cellFocusRange = Range.withLength(columnIndexDOM, 1);
  2227. } else {
  2228. int i = 0;
  2229. Element cell = container.getRowElement(rowWithFocus)
  2230. .getFirstChildElement();
  2231. do {
  2232. int colSpan = cell
  2233. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  2234. Range cellRange = Range.withLength(i, colSpan);
  2235. if (cellRange.contains(columnIndexDOM)) {
  2236. cellFocusRange = cellRange;
  2237. break;
  2238. }
  2239. cell = cell.getNextSiblingElement();
  2240. ++i;
  2241. } while (cell != null);
  2242. }
  2243. int columnIndex = getColumns().indexOf(
  2244. getVisibleColumn(columnIndexDOM));
  2245. if (columnIndex >= escalator.getColumnConfiguration()
  2246. .getFrozenColumnCount()) {
  2247. escalator.scrollToColumn(columnIndexDOM, ScrollDestination.ANY,
  2248. 10);
  2249. }
  2250. if (this.containerWithFocus == container) {
  2251. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  2252. refreshRow(oldRow);
  2253. } else {
  2254. refreshHeader();
  2255. refreshFooter();
  2256. }
  2257. } else {
  2258. RowContainer oldContainer = this.containerWithFocus;
  2259. this.containerWithFocus = container;
  2260. if (oldContainer == escalator.getBody()) {
  2261. lastFocusedBodyRow = oldRow;
  2262. } else if (oldContainer == escalator.getHeader()) {
  2263. lastFocusedHeaderRow = oldRow;
  2264. } else {
  2265. lastFocusedFooterRow = oldRow;
  2266. }
  2267. if (!oldRange.equals(cellFocusRange)) {
  2268. refreshHeader();
  2269. refreshFooter();
  2270. if (oldContainer == escalator.getBody()) {
  2271. oldContainer.refreshRows(oldRow, 1);
  2272. }
  2273. } else {
  2274. oldContainer.refreshRows(oldRow, 1);
  2275. }
  2276. }
  2277. refreshRow(rowWithFocus);
  2278. }
  2279. /**
  2280. * Sets focus on a cell.
  2281. *
  2282. * <p>
  2283. * <em>Note</em>: cell focus is not the same as JavaScript's
  2284. * {@code document.activeElement}.
  2285. *
  2286. * @param cell
  2287. * a cell object
  2288. */
  2289. public void setCellFocus(CellReference<T> cell) {
  2290. setCellFocus(cell.getRowIndex(), cell.getColumnIndexDOM(),
  2291. escalator.findRowContainer(cell.getElement()));
  2292. }
  2293. /**
  2294. * Gets list of events that can be used for cell focusing.
  2295. *
  2296. * @return list of navigation related event types
  2297. */
  2298. public Collection<String> getNavigationEvents() {
  2299. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  2300. }
  2301. /**
  2302. * Handle events that can move the cell focus.
  2303. */
  2304. public void handleNavigationEvent(Event event, CellReference<T> cell) {
  2305. if (event.getType().equals(BrowserEvents.CLICK)) {
  2306. setCellFocus(cell);
  2307. // Grid should have focus when clicked.
  2308. getElement().focus();
  2309. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  2310. int newRow = rowWithFocus;
  2311. RowContainer newContainer = containerWithFocus;
  2312. int newColumn = cellFocusRange.getStart();
  2313. switch (event.getKeyCode()) {
  2314. case KeyCodes.KEY_DOWN:
  2315. ++newRow;
  2316. break;
  2317. case KeyCodes.KEY_UP:
  2318. --newRow;
  2319. break;
  2320. case KeyCodes.KEY_RIGHT:
  2321. if (cellFocusRange.getEnd() >= getVisibleColumns().size()) {
  2322. return;
  2323. }
  2324. newColumn = cellFocusRange.getEnd();
  2325. break;
  2326. case KeyCodes.KEY_LEFT:
  2327. if (newColumn == 0) {
  2328. return;
  2329. }
  2330. --newColumn;
  2331. break;
  2332. case KeyCodes.KEY_TAB:
  2333. if (event.getShiftKey()) {
  2334. newContainer = getPreviousContainer(containerWithFocus);
  2335. } else {
  2336. newContainer = getNextContainer(containerWithFocus);
  2337. }
  2338. if (newContainer == containerWithFocus) {
  2339. return;
  2340. }
  2341. break;
  2342. case KeyCodes.KEY_HOME:
  2343. if (newContainer.getRowCount() > 0) {
  2344. newRow = 0;
  2345. }
  2346. break;
  2347. case KeyCodes.KEY_END:
  2348. if (newContainer.getRowCount() > 0) {
  2349. newRow = newContainer.getRowCount() - 1;
  2350. }
  2351. break;
  2352. case KeyCodes.KEY_PAGEDOWN:
  2353. case KeyCodes.KEY_PAGEUP:
  2354. if (newContainer.getRowCount() > 0) {
  2355. boolean down = event.getKeyCode() == KeyCodes.KEY_PAGEDOWN;
  2356. // If there is a visible focused cell, scroll by one
  2357. // page from its position. Otherwise, use the first or
  2358. // the last visible row as the scroll start position.
  2359. // This avoids jumping when using both keyboard and the
  2360. // scroll bar for scrolling.
  2361. int firstVisible = getFirstVisibleRowIndex();
  2362. int lastVisible = getLastVisibleRowIndex();
  2363. if (newRow < firstVisible || newRow > lastVisible) {
  2364. newRow = down ? lastVisible : firstVisible;
  2365. }
  2366. // Scroll by a little less than the visible area to
  2367. // account for the possibility that the top and the
  2368. // bottom row are only partially visible.
  2369. int moveFocusBy = Math.max(1, lastVisible
  2370. - firstVisible - 1);
  2371. moveFocusBy *= down ? 1 : -1;
  2372. newRow += moveFocusBy;
  2373. newRow = Math.max(0, Math.min(
  2374. newContainer.getRowCount() - 1, newRow));
  2375. }
  2376. break;
  2377. default:
  2378. return;
  2379. }
  2380. if (newContainer != containerWithFocus) {
  2381. if (newContainer == escalator.getBody()) {
  2382. newRow = lastFocusedBodyRow;
  2383. } else if (newContainer == escalator.getHeader()) {
  2384. newRow = lastFocusedHeaderRow;
  2385. } else {
  2386. newRow = lastFocusedFooterRow;
  2387. }
  2388. } else if (newRow < 0) {
  2389. newContainer = getPreviousContainer(newContainer);
  2390. if (newContainer == containerWithFocus) {
  2391. newRow = 0;
  2392. } else if (newContainer == escalator.getBody()) {
  2393. newRow = getLastVisibleRowIndex();
  2394. } else {
  2395. newRow = newContainer.getRowCount() - 1;
  2396. }
  2397. } else if (newRow >= containerWithFocus.getRowCount()) {
  2398. newContainer = getNextContainer(newContainer);
  2399. if (newContainer == containerWithFocus) {
  2400. newRow = containerWithFocus.getRowCount() - 1;
  2401. } else if (newContainer == escalator.getBody()) {
  2402. newRow = getFirstVisibleRowIndex();
  2403. } else {
  2404. newRow = 0;
  2405. }
  2406. }
  2407. if (newContainer.getRowCount() == 0) {
  2408. /*
  2409. * There are no rows in the container. Can't change the
  2410. * focused cell.
  2411. */
  2412. return;
  2413. }
  2414. event.preventDefault();
  2415. event.stopPropagation();
  2416. setCellFocus(newRow, newColumn, newContainer);
  2417. }
  2418. }
  2419. private RowContainer getPreviousContainer(RowContainer current) {
  2420. if (current == escalator.getFooter()) {
  2421. current = escalator.getBody();
  2422. } else if (current == escalator.getBody()) {
  2423. current = escalator.getHeader();
  2424. } else {
  2425. return current;
  2426. }
  2427. if (current.getRowCount() == 0) {
  2428. return getPreviousContainer(current);
  2429. }
  2430. return current;
  2431. }
  2432. private RowContainer getNextContainer(RowContainer current) {
  2433. if (current == escalator.getHeader()) {
  2434. current = escalator.getBody();
  2435. } else if (current == escalator.getBody()) {
  2436. current = escalator.getFooter();
  2437. } else {
  2438. return current;
  2439. }
  2440. if (current.getRowCount() == 0) {
  2441. return getNextContainer(current);
  2442. }
  2443. return current;
  2444. }
  2445. private void refreshRow(int row) {
  2446. containerWithFocus.refreshRows(row, 1);
  2447. }
  2448. /**
  2449. * Offsets the focused cell's range.
  2450. *
  2451. * @param offset
  2452. * offset for fixing focused cell's range
  2453. */
  2454. public void offsetRangeBy(int offset) {
  2455. cellFocusRange = cellFocusRange.offsetBy(offset);
  2456. }
  2457. /**
  2458. * Informs {@link CellFocusHandler} that certain range of rows has been
  2459. * added to the Grid body. {@link CellFocusHandler} will fix indices
  2460. * accordingly.
  2461. *
  2462. * @param added
  2463. * a range of added rows
  2464. */
  2465. public void rowsAddedToBody(Range added) {
  2466. boolean bodyHasFocus = (containerWithFocus == escalator.getBody());
  2467. boolean insertionIsAboveFocusedCell = (added.getStart() <= rowWithFocus);
  2468. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  2469. rowWithFocus += added.length();
  2470. rowWithFocus = Math.min(rowWithFocus, escalator.getBody()
  2471. .getRowCount() - 1);
  2472. refreshRow(rowWithFocus);
  2473. }
  2474. }
  2475. /**
  2476. * Informs {@link CellFocusHandler} that certain range of rows has been
  2477. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  2478. * accordingly.
  2479. *
  2480. * @param removed
  2481. * a range of removed rows
  2482. */
  2483. public void rowsRemovedFromBody(Range removed) {
  2484. if (containerWithFocus != escalator.getBody()) {
  2485. return;
  2486. } else if (!removed.contains(rowWithFocus)) {
  2487. if (removed.getStart() > rowWithFocus) {
  2488. return;
  2489. }
  2490. rowWithFocus = rowWithFocus - removed.length();
  2491. } else {
  2492. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  2493. rowWithFocus = removed.getStart();
  2494. } else if (removed.getStart() > 0) {
  2495. rowWithFocus = removed.getStart() - 1;
  2496. } else {
  2497. if (escalator.getHeader().getRowCount() > 0) {
  2498. rowWithFocus = Math.min(lastFocusedHeaderRow, escalator
  2499. .getHeader().getRowCount() - 1);
  2500. containerWithFocus = escalator.getHeader();
  2501. } else if (escalator.getFooter().getRowCount() > 0) {
  2502. rowWithFocus = Math.min(lastFocusedFooterRow, escalator
  2503. .getFooter().getRowCount() - 1);
  2504. containerWithFocus = escalator.getFooter();
  2505. }
  2506. }
  2507. }
  2508. refreshRow(rowWithFocus);
  2509. }
  2510. }
  2511. public final class SelectionColumn extends Column<Boolean, T>
  2512. implements GridEnabledHandler {
  2513. private boolean initDone = false;
  2514. private boolean selected = false;
  2515. private CheckBox selectAllCheckBox;
  2516. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  2517. super(selectColumnRenderer);
  2518. addEnabledHandler(this);
  2519. }
  2520. void initDone() {
  2521. setWidth(-1);
  2522. setEditable(false);
  2523. setResizable(false);
  2524. initDone = true;
  2525. }
  2526. @Override
  2527. protected void setDefaultHeaderContent(HeaderCell selectionCell) {
  2528. /*
  2529. * TODO: Currently the select all check box is shown when multi
  2530. * selection is in use. This might result in malfunctions if no
  2531. * SelectAllHandlers are present.
  2532. *
  2533. * Later on this could be fixed so that it check such handlers
  2534. * exist.
  2535. */
  2536. final SelectionModel.Multi<T> model = (Multi<T>) getSelectionModel();
  2537. if (selectAllCheckBox == null) {
  2538. selectAllCheckBox = GWT.create(CheckBox.class);
  2539. selectAllCheckBox.setStylePrimaryName(getStylePrimaryName()
  2540. + SELECT_ALL_CHECKBOX_CLASSNAME);
  2541. selectAllCheckBox
  2542. .addValueChangeHandler(new ValueChangeHandler<Boolean>() {
  2543. @Override
  2544. public void onValueChange(
  2545. ValueChangeEvent<Boolean> event) {
  2546. if (event.getValue()) {
  2547. fireEvent(new SelectAllEvent<T>(model));
  2548. selected = true;
  2549. } else {
  2550. model.deselectAll();
  2551. selected = false;
  2552. }
  2553. }
  2554. });
  2555. selectAllCheckBox.setValue(selected);
  2556. addHeaderClickHandler(new HeaderClickHandler() {
  2557. @Override
  2558. public void onClick(GridClickEvent event) {
  2559. CellReference<?> targetCell = event.getTargetCell();
  2560. int defaultRowIndex = getHeader().getRows().indexOf(
  2561. getDefaultHeaderRow());
  2562. if (targetCell.getColumnIndex() == 0
  2563. && targetCell.getRowIndex() == defaultRowIndex) {
  2564. selectAllCheckBox.setValue(
  2565. !selectAllCheckBox.getValue(), true);
  2566. }
  2567. }
  2568. });
  2569. // Select all with space when "select all" cell is active
  2570. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  2571. @Override
  2572. public void onKeyUp(GridKeyUpEvent event) {
  2573. if (event.getNativeKeyCode() != KeyCodes.KEY_SPACE) {
  2574. return;
  2575. }
  2576. HeaderRow targetHeaderRow = getHeader().getRow(
  2577. event.getFocusedCell().getRowIndex());
  2578. if (!targetHeaderRow.isDefault()) {
  2579. return;
  2580. }
  2581. if (event.getFocusedCell().getColumn() == SelectionColumn.this) {
  2582. // Send events to ensure state is updated
  2583. selectAllCheckBox.setValue(
  2584. !selectAllCheckBox.getValue(), true);
  2585. }
  2586. }
  2587. });
  2588. } else {
  2589. for (HeaderRow row : header.getRows()) {
  2590. if (row.getCell(this).getType() == GridStaticCellType.WIDGET) {
  2591. // Detach from old header.
  2592. row.getCell(this).setText("");
  2593. }
  2594. }
  2595. }
  2596. selectionCell.setWidget(selectAllCheckBox);
  2597. }
  2598. @Override
  2599. public Column<Boolean, T> setWidth(double pixels) {
  2600. if (pixels != getWidth() && initDone) {
  2601. throw new UnsupportedOperationException("The selection "
  2602. + "column cannot be modified after init");
  2603. } else {
  2604. super.setWidth(pixels);
  2605. }
  2606. return this;
  2607. }
  2608. @Override
  2609. public Boolean getValue(T row) {
  2610. return Boolean.valueOf(isSelected(row));
  2611. }
  2612. @Override
  2613. public Column<Boolean, T> setExpandRatio(int ratio) {
  2614. throw new UnsupportedOperationException(
  2615. "can't change the expand ratio of the selection column");
  2616. }
  2617. @Override
  2618. public int getExpandRatio() {
  2619. return 0;
  2620. }
  2621. @Override
  2622. public Column<Boolean, T> setMaximumWidth(double pixels) {
  2623. throw new UnsupportedOperationException(
  2624. "can't change the maximum width of the selection column");
  2625. }
  2626. @Override
  2627. public double getMaximumWidth() {
  2628. return -1;
  2629. }
  2630. @Override
  2631. public Column<Boolean, T> setMinimumWidth(double pixels) {
  2632. throw new UnsupportedOperationException(
  2633. "can't change the minimum width of the selection column");
  2634. }
  2635. @Override
  2636. public double getMinimumWidth() {
  2637. return -1;
  2638. }
  2639. @Override
  2640. public Column<Boolean, T> setEditable(boolean editable) {
  2641. if (initDone) {
  2642. throw new UnsupportedOperationException(
  2643. "can't set the selection column editable");
  2644. }
  2645. super.setEditable(editable);
  2646. return this;
  2647. }
  2648. /**
  2649. * Sets whether the selection column is enabled.
  2650. *
  2651. * @since 7.7
  2652. * @param enabled <code>true</code> to enable the column,
  2653. * <code>false</code> to disable it.
  2654. */
  2655. public void setEnabled(boolean enabled) {
  2656. if(selectAllCheckBox != null) {
  2657. selectAllCheckBox.setEnabled(enabled);
  2658. }
  2659. }
  2660. @Override
  2661. public void onEnabled(boolean enabled) {
  2662. setEnabled(enabled);
  2663. }
  2664. }
  2665. /**
  2666. * Helper class for performing sorting through the user interface. Controls
  2667. * the sort() method, reporting USER as the event originator. This is a
  2668. * completely internal class, and is, as such, safe to re-name should a more
  2669. * descriptive name come to mind.
  2670. */
  2671. private final class UserSorter {
  2672. private final Timer timer;
  2673. private boolean scheduledMultisort;
  2674. private Column<?, T> column;
  2675. private UserSorter() {
  2676. timer = new Timer() {
  2677. @Override
  2678. public void run() {
  2679. UserSorter.this.sort(column, scheduledMultisort);
  2680. }
  2681. };
  2682. }
  2683. /**
  2684. * Toggle sorting for a cell. If the multisort parameter is set to true,
  2685. * the cell's sort order is modified as a natural part of a multi-sort
  2686. * chain. If false, the sorting order is set to ASCENDING for that
  2687. * cell's column. If that column was already the only sorted column in
  2688. * the Grid, the sort direction is flipped.
  2689. *
  2690. * @param cell
  2691. * a valid cell reference
  2692. * @param multisort
  2693. * whether the sort command should act as a multi-sort stack
  2694. * or not
  2695. */
  2696. public void sort(Column<?, ?> column, boolean multisort) {
  2697. if (!columns.contains(column)) {
  2698. throw new IllegalArgumentException(
  2699. "Given column is not a column in this grid. "
  2700. + column.toString());
  2701. }
  2702. if (!column.isSortable()) {
  2703. return;
  2704. }
  2705. final SortOrder so = getSortOrder(column);
  2706. if (multisort) {
  2707. // If the sort order exists, replace existing value with its
  2708. // opposite
  2709. if (so != null) {
  2710. final int idx = sortOrder.indexOf(so);
  2711. sortOrder.set(idx, so.getOpposite());
  2712. } else {
  2713. // If it doesn't, just add a new sort order to the end of
  2714. // the list
  2715. sortOrder.add(new SortOrder(column));
  2716. }
  2717. } else {
  2718. // Since we're doing single column sorting, first clear the
  2719. // list. Then, if the sort order existed, add its opposite,
  2720. // otherwise just add a new sort value
  2721. int items = sortOrder.size();
  2722. sortOrder.clear();
  2723. if (so != null && items == 1) {
  2724. sortOrder.add(so.getOpposite());
  2725. } else {
  2726. sortOrder.add(new SortOrder(column));
  2727. }
  2728. }
  2729. // sortOrder has been changed; tell the Grid to re-sort itself by
  2730. // user request.
  2731. Grid.this.sort(true);
  2732. }
  2733. /**
  2734. * Perform a sort after a delay.
  2735. *
  2736. * @param delay
  2737. * delay, in milliseconds
  2738. */
  2739. public void sortAfterDelay(int delay, boolean multisort) {
  2740. column = eventCell.getColumn();
  2741. scheduledMultisort = multisort;
  2742. timer.schedule(delay);
  2743. }
  2744. /**
  2745. * Check if a delayed sort command has been issued but not yet carried
  2746. * out.
  2747. *
  2748. * @return a boolean value
  2749. */
  2750. public boolean isDelayedSortScheduled() {
  2751. return timer.isRunning();
  2752. }
  2753. /**
  2754. * Cancel a scheduled sort.
  2755. */
  2756. public void cancelDelayedSort() {
  2757. timer.cancel();
  2758. }
  2759. }
  2760. /**
  2761. * @see Grid#autoColumnWidthsRecalculator
  2762. */
  2763. private class AutoColumnWidthsRecalculator {
  2764. private double lastCalculatedInnerWidth = -1;
  2765. private final ScheduledCommand calculateCommand = new ScheduledCommand() {
  2766. @Override
  2767. public void execute() {
  2768. if (!isScheduled) {
  2769. // something cancelled running this.
  2770. return;
  2771. }
  2772. if (header.markAsDirty || footer.markAsDirty) {
  2773. if (rescheduleCount < 10) {
  2774. /*
  2775. * Headers and footers are rendered as finally, this way
  2776. * we re-schedule this loop as finally, at the end of
  2777. * the queue, so that the headers have a chance to
  2778. * render themselves.
  2779. */
  2780. Scheduler.get().scheduleFinally(this);
  2781. rescheduleCount++;
  2782. } else {
  2783. /*
  2784. * We've tried too many times reschedule finally. Seems
  2785. * like something is being deferred. Let the queue
  2786. * execute and retry again.
  2787. */
  2788. rescheduleCount = 0;
  2789. Scheduler.get().scheduleDeferred(this);
  2790. }
  2791. } else if (dataIsBeingFetched) {
  2792. Scheduler.get().scheduleDeferred(this);
  2793. } else {
  2794. calculate();
  2795. }
  2796. }
  2797. };
  2798. private int rescheduleCount = 0;
  2799. private boolean isScheduled;
  2800. /**
  2801. * Calculates and applies column widths, taking into account fixed
  2802. * widths and column expand rules
  2803. *
  2804. * @param immediately
  2805. * <code>true</code> if the widths should be executed
  2806. * immediately (ignoring lazy loading completely), or
  2807. * <code>false</code> if the command should be run after a
  2808. * while (duplicate non-immediately invocations are ignored).
  2809. * @see Column#setWidth(double)
  2810. * @see Column#setExpandRatio(int)
  2811. * @see Column#setMinimumWidth(double)
  2812. * @see Column#setMaximumWidth(double)
  2813. */
  2814. public void schedule() {
  2815. if (!isScheduled && isAttached()) {
  2816. isScheduled = true;
  2817. Scheduler.get().scheduleFinally(calculateCommand);
  2818. }
  2819. }
  2820. private void calculate() {
  2821. isScheduled = false;
  2822. rescheduleCount = 0;
  2823. assert !dataIsBeingFetched : "Trying to calculate column widths even though data is still being fetched.";
  2824. if (columnsAreGuaranteedToBeWiderThanGrid()) {
  2825. applyColumnWidths();
  2826. } else {
  2827. applyColumnWidthsWithExpansion();
  2828. }
  2829. // Update latest width to prevent recalculate on height change.
  2830. lastCalculatedInnerWidth = escalator.getInnerWidth();
  2831. }
  2832. private boolean columnsAreGuaranteedToBeWiderThanGrid() {
  2833. double freeSpace = escalator.getInnerWidth();
  2834. for (Column<?, ?> column : getVisibleColumns()) {
  2835. if (column.getWidth() >= 0) {
  2836. freeSpace -= column.getWidth();
  2837. } else if (column.getMinimumWidth() >= 0) {
  2838. freeSpace -= column.getMinimumWidth();
  2839. }
  2840. }
  2841. return freeSpace < 0;
  2842. }
  2843. @SuppressWarnings("boxing")
  2844. private void applyColumnWidths() {
  2845. /* Step 1: Apply all column widths as they are. */
  2846. Map<Integer, Double> selfWidths = new LinkedHashMap<Integer, Double>();
  2847. List<Column<?, T>> columns = getVisibleColumns();
  2848. for (int index = 0; index < columns.size(); index++) {
  2849. selfWidths.put(index, columns.get(index).getWidth());
  2850. }
  2851. Grid.this.escalator.getColumnConfiguration().setColumnWidths(
  2852. selfWidths);
  2853. /*
  2854. * Step 2: Make sure that each column ends up obeying their min/max
  2855. * width constraints if defined as autowidth. If constraints are
  2856. * violated, fix it.
  2857. */
  2858. Map<Integer, Double> constrainedWidths = new LinkedHashMap<Integer, Double>();
  2859. for (int index = 0; index < columns.size(); index++) {
  2860. Column<?, T> column = columns.get(index);
  2861. boolean hasAutoWidth = column.getWidth() < 0;
  2862. if (!hasAutoWidth) {
  2863. continue;
  2864. }
  2865. // TODO: bug: these don't honor the CSS max/min. :(
  2866. double actualWidth = column.getWidthActual();
  2867. if (actualWidth < getMinWidth(column)) {
  2868. constrainedWidths.put(index, column.getMinimumWidth());
  2869. } else if (actualWidth > getMaxWidth(column)) {
  2870. constrainedWidths.put(index, column.getMaximumWidth());
  2871. }
  2872. }
  2873. Grid.this.escalator.getColumnConfiguration().setColumnWidths(
  2874. constrainedWidths);
  2875. }
  2876. private void applyColumnWidthsWithExpansion() {
  2877. boolean defaultExpandRatios = true;
  2878. int totalRatios = 0;
  2879. double reservedPixels = 0;
  2880. final Set<Column<?, T>> columnsToExpand = new HashSet<Column<?, T>>();
  2881. List<Column<?, T>> nonFixedColumns = new ArrayList<Column<?, T>>();
  2882. Map<Integer, Double> columnSizes = new HashMap<Integer, Double>();
  2883. final List<Column<?, T>> visibleColumns = getVisibleColumns();
  2884. /*
  2885. * Set all fixed widths and also calculate the size-to-fit widths
  2886. * for the autocalculated columns.
  2887. *
  2888. * This way we know with how many pixels we have left to expand the
  2889. * rest.
  2890. */
  2891. for (Column<?, T> column : visibleColumns) {
  2892. final double widthAsIs = column.getWidth();
  2893. final boolean isFixedWidth = widthAsIs >= 0;
  2894. // Check for max width just to be sure we don't break the limits
  2895. final double widthFixed = Math.max(
  2896. Math.min(getMaxWidth(column), widthAsIs),
  2897. column.getMinimumWidth());
  2898. defaultExpandRatios = defaultExpandRatios
  2899. && (column.getExpandRatio() == -1 || column == selectionColumn);
  2900. if (isFixedWidth) {
  2901. columnSizes.put(visibleColumns.indexOf(column), widthFixed);
  2902. reservedPixels += widthFixed;
  2903. } else {
  2904. nonFixedColumns.add(column);
  2905. columnSizes.put(visibleColumns.indexOf(column), -1.0d);
  2906. }
  2907. }
  2908. setColumnSizes(columnSizes);
  2909. for (Column<?, T> column : nonFixedColumns) {
  2910. final int expandRatio = (defaultExpandRatios ? 1 : column
  2911. .getExpandRatio());
  2912. final double maxWidth = getMaxWidth(column);
  2913. final double newWidth = Math.min(maxWidth,
  2914. column.getWidthActual());
  2915. boolean shouldExpand = newWidth < maxWidth && expandRatio > 0
  2916. && column != selectionColumn;
  2917. if (shouldExpand) {
  2918. totalRatios += expandRatio;
  2919. columnsToExpand.add(column);
  2920. }
  2921. reservedPixels += newWidth;
  2922. columnSizes.put(visibleColumns.indexOf(column), newWidth);
  2923. }
  2924. /*
  2925. * Now that we know how many pixels we need at the very least, we
  2926. * can distribute the remaining pixels to all columns according to
  2927. * their expand ratios.
  2928. */
  2929. double pixelsToDistribute = escalator.getInnerWidth()
  2930. - reservedPixels;
  2931. if (pixelsToDistribute <= 0 || totalRatios <= 0) {
  2932. if (pixelsToDistribute <= 0) {
  2933. // Set column sizes for expanding columns
  2934. setColumnSizes(columnSizes);
  2935. }
  2936. return;
  2937. }
  2938. /*
  2939. * Check for columns that hit their max width. Adjust
  2940. * pixelsToDistribute and totalRatios accordingly. Recheck. Stop
  2941. * when no new columns hit their max width
  2942. */
  2943. boolean aColumnHasMaxedOut;
  2944. do {
  2945. aColumnHasMaxedOut = false;
  2946. final double widthPerRatio = pixelsToDistribute / totalRatios;
  2947. final Iterator<Column<?, T>> i = columnsToExpand.iterator();
  2948. while (i.hasNext()) {
  2949. final Column<?, T> column = i.next();
  2950. final int expandRatio = getExpandRatio(column,
  2951. defaultExpandRatios);
  2952. final int columnIndex = visibleColumns.indexOf(column);
  2953. final double autoWidth = columnSizes.get(columnIndex);
  2954. final double maxWidth = getMaxWidth(column);
  2955. double expandedWidth = autoWidth + widthPerRatio
  2956. * expandRatio;
  2957. if (maxWidth <= expandedWidth) {
  2958. i.remove();
  2959. totalRatios -= expandRatio;
  2960. aColumnHasMaxedOut = true;
  2961. pixelsToDistribute -= maxWidth - autoWidth;
  2962. columnSizes.put(columnIndex, maxWidth);
  2963. }
  2964. }
  2965. } while (aColumnHasMaxedOut);
  2966. if (totalRatios <= 0 && columnsToExpand.isEmpty()) {
  2967. setColumnSizes(columnSizes);
  2968. return;
  2969. }
  2970. assert pixelsToDistribute > 0 : "We've run out of pixels to distribute ("
  2971. + pixelsToDistribute
  2972. + "px to "
  2973. + totalRatios
  2974. + " ratios between " + columnsToExpand.size() + " columns)";
  2975. assert totalRatios > 0 && !columnsToExpand.isEmpty() : "Bookkeeping out of sync. Ratios: "
  2976. + totalRatios + " Columns: " + columnsToExpand.size();
  2977. /*
  2978. * If we still have anything left, distribute the remaining pixels
  2979. * to the remaining columns.
  2980. */
  2981. final double widthPerRatio;
  2982. int leftOver = 0;
  2983. if (BrowserInfo.get().isIE8() || BrowserInfo.get().isIE9()
  2984. || BrowserInfo.getBrowserString().contains("PhantomJS")) {
  2985. // These browsers report subpixels as integers. this usually
  2986. // results into issues..
  2987. widthPerRatio = (int) (pixelsToDistribute / totalRatios);
  2988. leftOver = (int) (pixelsToDistribute - widthPerRatio
  2989. * totalRatios);
  2990. } else {
  2991. widthPerRatio = pixelsToDistribute / totalRatios;
  2992. }
  2993. for (Column<?, T> column : columnsToExpand) {
  2994. final int expandRatio = getExpandRatio(column,
  2995. defaultExpandRatios);
  2996. final int columnIndex = visibleColumns.indexOf(column);
  2997. final double autoWidth = columnSizes.get(columnIndex);
  2998. double totalWidth = autoWidth + widthPerRatio * expandRatio;
  2999. if (leftOver > 0) {
  3000. totalWidth += 1;
  3001. leftOver--;
  3002. }
  3003. columnSizes.put(columnIndex, totalWidth);
  3004. totalRatios -= expandRatio;
  3005. }
  3006. assert totalRatios == 0 : "Bookkeeping error: there were still some ratios left undistributed: "
  3007. + totalRatios;
  3008. /*
  3009. * Check the guarantees for minimum width and scoot back the columns
  3010. * that don't care.
  3011. */
  3012. boolean minWidthsCausedReflows;
  3013. do {
  3014. minWidthsCausedReflows = false;
  3015. /*
  3016. * First, let's check which columns were too cramped, and expand
  3017. * them. Also keep track on how many pixels we grew - we need to
  3018. * remove those pixels from other columns
  3019. */
  3020. double pixelsToRemoveFromOtherColumns = 0;
  3021. for (Column<?, T> column : visibleColumns) {
  3022. /*
  3023. * We can't iterate over columnsToExpand, even though that
  3024. * would be convenient. This is because some column without
  3025. * an expand ratio might still have a min width - those
  3026. * wouldn't show up in that set.
  3027. */
  3028. double minWidth = getMinWidth(column);
  3029. final int columnIndex = visibleColumns.indexOf(column);
  3030. double currentWidth = columnSizes.get(columnIndex);
  3031. boolean hasAutoWidth = column.getWidth() < 0;
  3032. if (hasAutoWidth && currentWidth < minWidth) {
  3033. columnSizes.put(columnIndex, minWidth);
  3034. pixelsToRemoveFromOtherColumns += (minWidth - currentWidth);
  3035. minWidthsCausedReflows = true;
  3036. /*
  3037. * Remove this column form the set if it exists. This
  3038. * way we make sure that it doesn't get shrunk in the
  3039. * next step.
  3040. */
  3041. columnsToExpand.remove(column);
  3042. }
  3043. }
  3044. /*
  3045. * Now we need to shrink the remaining columns according to
  3046. * their ratios. Recalculate the sum of remaining ratios.
  3047. */
  3048. totalRatios = 0;
  3049. for (Column<?, ?> column : columnsToExpand) {
  3050. totalRatios += getExpandRatio(column, defaultExpandRatios);
  3051. }
  3052. final double pixelsToRemovePerRatio = pixelsToRemoveFromOtherColumns
  3053. / totalRatios;
  3054. for (Column<?, T> column : columnsToExpand) {
  3055. final double pixelsToRemove = pixelsToRemovePerRatio
  3056. * getExpandRatio(column, defaultExpandRatios);
  3057. int colIndex = visibleColumns.indexOf(column);
  3058. columnSizes.put(colIndex, columnSizes.get(colIndex)
  3059. - pixelsToRemove);
  3060. }
  3061. } while (minWidthsCausedReflows);
  3062. // Finally set all the column sizes.
  3063. setColumnSizes(columnSizes);
  3064. }
  3065. private void setColumnSizes(Map<Integer, Double> columnSizes) {
  3066. // Set all widths at once
  3067. escalator.getColumnConfiguration().setColumnWidths(columnSizes);
  3068. }
  3069. private int getExpandRatio(Column<?, ?> column,
  3070. boolean defaultExpandRatios) {
  3071. int expandRatio = column.getExpandRatio();
  3072. if (expandRatio > 0) {
  3073. return expandRatio;
  3074. } else if (expandRatio < 0) {
  3075. assert defaultExpandRatios : "No columns should've expanded";
  3076. return 1;
  3077. } else {
  3078. assert false : "this method should've not been called at all if expandRatio is 0";
  3079. return 0;
  3080. }
  3081. }
  3082. /**
  3083. * Returns the maximum width of the column, or {@link Double#MAX_VALUE}
  3084. * if defined as negative.
  3085. */
  3086. private double getMaxWidth(Column<?, ?> column) {
  3087. double maxWidth = column.getMaximumWidth();
  3088. if (maxWidth >= 0) {
  3089. return maxWidth;
  3090. } else {
  3091. return Double.MAX_VALUE;
  3092. }
  3093. }
  3094. /**
  3095. * Returns the minimum width of the column, or {@link Double#MIN_VALUE}
  3096. * if defined as negative.
  3097. */
  3098. private double getMinWidth(Column<?, ?> column) {
  3099. double minWidth = column.getMinimumWidth();
  3100. if (minWidth >= 0) {
  3101. return minWidth;
  3102. } else {
  3103. return Double.MIN_VALUE;
  3104. }
  3105. }
  3106. /**
  3107. * Check whether the auto width calculation is currently scheduled.
  3108. *
  3109. * @return <code>true</code> if auto width calculation is currently
  3110. * scheduled
  3111. */
  3112. public boolean isScheduled() {
  3113. return isScheduled;
  3114. }
  3115. }
  3116. private class GridSpacerUpdater implements SpacerUpdater {
  3117. private static final String STRIPE_CLASSNAME = "stripe";
  3118. private final Map<Element, Widget> elementToWidgetMap = new HashMap<Element, Widget>();
  3119. @Override
  3120. public void init(Spacer spacer) {
  3121. initTheming(spacer);
  3122. int rowIndex = spacer.getRow();
  3123. Widget detailsWidget = null;
  3124. try {
  3125. detailsWidget = detailsGenerator.getDetails(rowIndex);
  3126. } catch (Throwable e) {
  3127. getLogger().log(
  3128. Level.SEVERE,
  3129. "Exception while generating details for row "
  3130. + rowIndex, e);
  3131. }
  3132. final double spacerHeight;
  3133. Element spacerElement = spacer.getElement();
  3134. if (detailsWidget == null) {
  3135. spacerElement.removeAllChildren();
  3136. spacerHeight = DETAILS_ROW_INITIAL_HEIGHT;
  3137. } else {
  3138. Element element = detailsWidget.getElement();
  3139. spacerElement.appendChild(element);
  3140. setParent(detailsWidget, Grid.this);
  3141. Widget previousWidget = elementToWidgetMap.put(element,
  3142. detailsWidget);
  3143. assert previousWidget == null : "Overwrote a pre-existing widget on row "
  3144. + rowIndex + " without proper removal first.";
  3145. /*
  3146. * Once we have the content properly inside the DOM, we should
  3147. * re-measure it to make sure that it's the correct height.
  3148. *
  3149. * This is rather tricky, since the row (tr) will get the
  3150. * height, but the spacer cell (td) has the borders, which
  3151. * should go on top of the previous row and next row.
  3152. */
  3153. double contentHeight;
  3154. if (detailsGenerator instanceof HeightAwareDetailsGenerator) {
  3155. HeightAwareDetailsGenerator sadg = (HeightAwareDetailsGenerator) detailsGenerator;
  3156. contentHeight = sadg.getDetailsHeight(rowIndex);
  3157. } else {
  3158. contentHeight = WidgetUtil
  3159. .getRequiredHeightBoundingClientRectDouble(element);
  3160. }
  3161. double borderTopAndBottomHeight = WidgetUtil
  3162. .getBorderTopAndBottomThickness(spacerElement);
  3163. double measuredHeight = contentHeight
  3164. + borderTopAndBottomHeight;
  3165. assert getElement().isOrHasChild(spacerElement) : "The spacer element wasn't in the DOM during measurement, but was assumed to be.";
  3166. spacerHeight = measuredHeight;
  3167. }
  3168. escalator.getBody().setSpacer(rowIndex, spacerHeight);
  3169. }
  3170. @Override
  3171. public void destroy(Spacer spacer) {
  3172. Element spacerElement = spacer.getElement();
  3173. assert getElement().isOrHasChild(spacerElement) : "Trying "
  3174. + "to destroy a spacer that is not connected to this "
  3175. + "Grid's DOM. (row: " + spacer.getRow() + ", element: "
  3176. + spacerElement + ")";
  3177. Widget detailsWidget = elementToWidgetMap.remove(spacerElement
  3178. .getFirstChildElement());
  3179. if (detailsWidget != null) {
  3180. /*
  3181. * The widget may be null here if the previous generator
  3182. * returned a null widget.
  3183. */
  3184. assert spacerElement.getFirstChild() != null : "The "
  3185. + "details row to destroy did not contain a widget - "
  3186. + "probably removed by something else without "
  3187. + "permission? (row: " + spacer.getRow()
  3188. + ", element: " + spacerElement + ")";
  3189. setParent(detailsWidget, null);
  3190. spacerElement.removeAllChildren();
  3191. }
  3192. }
  3193. private void initTheming(Spacer spacer) {
  3194. Element spacerRoot = spacer.getElement();
  3195. if (spacer.getRow() % 2 == 1) {
  3196. spacerRoot.getParentElement().addClassName(STRIPE_CLASSNAME);
  3197. } else {
  3198. spacerRoot.getParentElement().removeClassName(STRIPE_CLASSNAME);
  3199. }
  3200. }
  3201. }
  3202. /**
  3203. * Sidebar displaying toggles for hidable columns and custom widgets
  3204. * provided by the application.
  3205. * <p>
  3206. * The button for opening the sidebar is automatically visible inside the
  3207. * grid, if it contains any column hiding options or custom widgets. The
  3208. * column hiding toggles and custom widgets become visible once the sidebar
  3209. * has been opened.
  3210. *
  3211. * @since 7.5.0
  3212. */
  3213. private static class Sidebar extends Composite implements HasEnabled {
  3214. private final ClickHandler openCloseButtonHandler = new ClickHandler() {
  3215. @Override
  3216. public void onClick(ClickEvent event) {
  3217. if (!isOpen()) {
  3218. open();
  3219. } else {
  3220. close();
  3221. }
  3222. }
  3223. };
  3224. private final FlowPanel rootContainer;
  3225. private final FlowPanel content;
  3226. private final MenuBar menuBar;
  3227. private final Button openCloseButton;
  3228. private final Grid<?> grid;
  3229. private Overlay overlay;
  3230. private Sidebar(Grid<?> grid) {
  3231. this.grid = grid;
  3232. rootContainer = new FlowPanel();
  3233. initWidget(rootContainer);
  3234. openCloseButton = new Button();
  3235. openCloseButton.addClickHandler(openCloseButtonHandler);
  3236. rootContainer.add(openCloseButton);
  3237. content = new FlowPanel() {
  3238. @Override
  3239. public boolean remove(Widget w) {
  3240. // Check here to catch child.removeFromParent() calls
  3241. boolean removed = super.remove(w);
  3242. if (removed) {
  3243. updateVisibility();
  3244. }
  3245. return removed;
  3246. }
  3247. };
  3248. createOverlay();
  3249. menuBar = new MenuBar(true) {
  3250. @Override
  3251. public MenuItem insertItem(MenuItem item, int beforeIndex)
  3252. throws IndexOutOfBoundsException {
  3253. if (getParent() == null) {
  3254. content.insert(this, 0);
  3255. updateVisibility();
  3256. }
  3257. return super.insertItem(item, beforeIndex);
  3258. }
  3259. @Override
  3260. public void removeItem(MenuItem item) {
  3261. super.removeItem(item);
  3262. if (getItems().isEmpty()) {
  3263. menuBar.removeFromParent();
  3264. }
  3265. }
  3266. @Override
  3267. public void onBrowserEvent(Event event) {
  3268. // selecting a item with enter will lose the focus and
  3269. // selected item, which means that further keyboard
  3270. // selection won't work unless we do this:
  3271. if (event.getTypeInt() == Event.ONKEYDOWN
  3272. && event.getKeyCode() == KeyCodes.KEY_ENTER) {
  3273. final MenuItem item = getSelectedItem();
  3274. super.onBrowserEvent(event);
  3275. Scheduler.get().scheduleDeferred(
  3276. new ScheduledCommand() {
  3277. @Override
  3278. public void execute() {
  3279. selectItem(item);
  3280. focus();
  3281. }
  3282. });
  3283. } else {
  3284. super.onBrowserEvent(event);
  3285. }
  3286. }
  3287. };
  3288. KeyDownHandler keyDownHandler = new KeyDownHandler() {
  3289. @Override
  3290. public void onKeyDown(KeyDownEvent event) {
  3291. if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
  3292. close();
  3293. }
  3294. }
  3295. };
  3296. openCloseButton.addDomHandler(keyDownHandler,
  3297. KeyDownEvent.getType());
  3298. menuBar.addDomHandler(keyDownHandler, KeyDownEvent.getType());
  3299. }
  3300. /**
  3301. * Creates and initializes the overlay.
  3302. */
  3303. private void createOverlay() {
  3304. overlay = GWT.create(Overlay.class);
  3305. overlay.setOwner(grid);
  3306. overlay.setAutoHideEnabled(true);
  3307. overlay.addStyleDependentName("popup");
  3308. overlay.add(content);
  3309. overlay.addAutoHidePartner(rootContainer.getElement());
  3310. overlay.addCloseHandler(new CloseHandler<PopupPanel>() {
  3311. @Override
  3312. public void onClose(CloseEvent<PopupPanel> event) {
  3313. removeStyleName("open");
  3314. addStyleName("closed");
  3315. }
  3316. });
  3317. overlay.setFitInWindow(true);
  3318. }
  3319. /**
  3320. * Opens the sidebar if not yet opened. Opening the sidebar has no
  3321. * effect if it is empty.
  3322. */
  3323. public void open() {
  3324. if (!isOpen() && isInDOM()) {
  3325. addStyleName("open");
  3326. removeStyleName("closed");
  3327. overlay.showRelativeTo(rootContainer);
  3328. }
  3329. }
  3330. /**
  3331. * Closes the sidebar if not yet closed.
  3332. */
  3333. public void close() {
  3334. overlay.hide();
  3335. }
  3336. /**
  3337. * Returns whether the sidebar is open or not.
  3338. *
  3339. * @return <code>true</code> if open, <code>false</code> if not
  3340. */
  3341. public boolean isOpen() {
  3342. return overlay != null && overlay.isShowing();
  3343. }
  3344. @Override
  3345. public void setStylePrimaryName(String styleName) {
  3346. super.setStylePrimaryName(styleName);
  3347. overlay.setStylePrimaryName(styleName);
  3348. content.setStylePrimaryName(styleName + "-content");
  3349. openCloseButton.setStylePrimaryName(styleName + "-button");
  3350. if (isOpen()) {
  3351. addStyleName("open");
  3352. removeStyleName("closed");
  3353. } else {
  3354. removeStyleName("open");
  3355. addStyleName("closed");
  3356. }
  3357. }
  3358. @Override
  3359. public void addStyleName(String style) {
  3360. super.addStyleName(style);
  3361. overlay.addStyleName(style);
  3362. }
  3363. @Override
  3364. public void removeStyleName(String style) {
  3365. super.removeStyleName(style);
  3366. overlay.removeStyleName(style);
  3367. }
  3368. private void setHeightToHeaderCellHeight() {
  3369. RowContainer header = grid.escalator.getHeader();
  3370. if (header.getRowCount() == 0
  3371. || !header.getRowElement(0).hasChildNodes()) {
  3372. getLogger()
  3373. .info("No header cell available when calculating sidebar button height");
  3374. openCloseButton.setHeight(header.getDefaultRowHeight() + "px");
  3375. return;
  3376. }
  3377. Element firstHeaderCell = header.getRowElement(0)
  3378. .getFirstChildElement();
  3379. double height = WidgetUtil
  3380. .getRequiredHeightBoundingClientRectDouble(firstHeaderCell)
  3381. - (WidgetUtil.measureVerticalBorder(getElement()) / 2);
  3382. openCloseButton.setHeight(height + "px");
  3383. }
  3384. private void updateVisibility() {
  3385. final boolean hasWidgets = content.getWidgetCount() > 0;
  3386. final boolean isVisible = isInDOM();
  3387. if (isVisible && !hasWidgets) {
  3388. Grid.setParent(this, null);
  3389. getElement().removeFromParent();
  3390. } else if (!isVisible && hasWidgets) {
  3391. close();
  3392. grid.getElement().appendChild(getElement());
  3393. Grid.setParent(this, grid);
  3394. // border calculation won't work until attached
  3395. setHeightToHeaderCellHeight();
  3396. }
  3397. }
  3398. private boolean isInDOM() {
  3399. return getParent() != null;
  3400. }
  3401. @Override
  3402. protected void onAttach() {
  3403. super.onAttach();
  3404. // make sure the button will get correct height if the button should
  3405. // be visible when the grid is rendered the first time.
  3406. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  3407. @Override
  3408. public void execute() {
  3409. setHeightToHeaderCellHeight();
  3410. }
  3411. });
  3412. }
  3413. @Override
  3414. public boolean isEnabled() {
  3415. return openCloseButton.isEnabled();
  3416. }
  3417. @Override
  3418. public void setEnabled(boolean enabled) {
  3419. if (!enabled && isOpen()) {
  3420. close();
  3421. }
  3422. openCloseButton.setEnabled(enabled);
  3423. }
  3424. }
  3425. /**
  3426. * UI and functionality related to hiding columns with toggles in the
  3427. * sidebar.
  3428. */
  3429. private final class ColumnHider {
  3430. /** Map from columns to their hiding toggles, component might change */
  3431. private HashMap<Column<?, T>, MenuItem> columnToHidingToggleMap = new HashMap<Grid.Column<?, T>, MenuItem>();
  3432. /**
  3433. * When column is being hidden with a toggle, do not refresh toggles for
  3434. * no reason. Also helps for keeping the keyboard navigation working.
  3435. */
  3436. private boolean hidingColumn;
  3437. private void updateColumnHidable(final Column<?, T> column) {
  3438. if (column.isHidable()) {
  3439. MenuItem toggle = columnToHidingToggleMap.get(column);
  3440. if (toggle == null) {
  3441. toggle = createToggle(column);
  3442. }
  3443. toggle.setStyleName("hidden", column.isHidden());
  3444. } else if (columnToHidingToggleMap.containsKey(column)) {
  3445. sidebar.menuBar.removeItem((columnToHidingToggleMap
  3446. .remove(column)));
  3447. }
  3448. updateTogglesOrder();
  3449. }
  3450. private MenuItem createToggle(final Column<?, T> column) {
  3451. MenuItem toggle = new MenuItem(createHTML(column), true,
  3452. new ScheduledCommand() {
  3453. @Override
  3454. public void execute() {
  3455. hidingColumn = true;
  3456. column.setHidden(!column.isHidden(), true);
  3457. hidingColumn = false;
  3458. }
  3459. });
  3460. toggle.addStyleName("column-hiding-toggle");
  3461. columnToHidingToggleMap.put(column, toggle);
  3462. return toggle;
  3463. }
  3464. private String createHTML(Column<?, T> column) {
  3465. final StringBuffer buf = new StringBuffer();
  3466. buf.append("<span class=\"");
  3467. if (column.isHidden()) {
  3468. buf.append("v-off");
  3469. } else {
  3470. buf.append("v-on");
  3471. }
  3472. buf.append("\"><div>");
  3473. String caption = column.getHidingToggleCaption();
  3474. if (caption == null) {
  3475. caption = column.headerCaption;
  3476. }
  3477. buf.append(caption);
  3478. buf.append("</div></span>");
  3479. return buf.toString();
  3480. }
  3481. private void updateTogglesOrder() {
  3482. if (!hidingColumn) {
  3483. int lastIndex = 0;
  3484. for (Column<?, T> column : getColumns()) {
  3485. if (column.isHidable()) {
  3486. final MenuItem menuItem = columnToHidingToggleMap
  3487. .get(column);
  3488. sidebar.menuBar.removeItem(menuItem);
  3489. sidebar.menuBar.insertItem(menuItem, lastIndex++);
  3490. }
  3491. }
  3492. }
  3493. }
  3494. private void updateHidingToggle(Column<?, T> column) {
  3495. if (column.isHidable()) {
  3496. MenuItem toggle = columnToHidingToggleMap.get(column);
  3497. toggle.setHTML(createHTML(column));
  3498. toggle.setStyleName("hidden", column.isHidden());
  3499. } // else we can just ignore
  3500. }
  3501. private void removeColumnHidingToggle(Column<?, T> column) {
  3502. sidebar.menuBar.removeItem(columnToHidingToggleMap.get(column));
  3503. }
  3504. }
  3505. /**
  3506. * Escalator used internally by grid to render the rows
  3507. */
  3508. private Escalator escalator = GWT.create(Escalator.class);
  3509. private final Header header = GWT.create(Header.class);
  3510. private final Footer footer = GWT.create(Footer.class);
  3511. private final Sidebar sidebar = new Sidebar(this);
  3512. /**
  3513. * List of columns in the grid. Order defines the visible order.
  3514. */
  3515. private List<Column<?, T>> columns = new ArrayList<Column<?, T>>();
  3516. /**
  3517. * The datasource currently in use. <em>Note:</em> it is <code>null</code>
  3518. * on initialization, but not after that.
  3519. */
  3520. private DataSource<T> dataSource;
  3521. /**
  3522. * Currently available row range in DataSource.
  3523. */
  3524. private Range currentDataAvailable = Range.withLength(0, 0);
  3525. /**
  3526. * The number of frozen columns, 0 freezes the selection column if
  3527. * displayed, -1 also prevents selection col from freezing.
  3528. */
  3529. private int frozenColumnCount = 0;
  3530. /**
  3531. * Current sort order. The (private) sort() method reads this list to
  3532. * determine the order in which to present rows.
  3533. */
  3534. private List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  3535. private Renderer<Boolean> selectColumnRenderer = null;
  3536. private SelectionColumn selectionColumn;
  3537. private String rowStripeStyleName;
  3538. private String rowHasDataStyleName;
  3539. private String rowSelectedStyleName;
  3540. private String cellFocusStyleName;
  3541. private String rowFocusStyleName;
  3542. /**
  3543. * Current selection model.
  3544. */
  3545. private SelectionModel<T> selectionModel;
  3546. protected final CellFocusHandler cellFocusHandler;
  3547. private final UserSorter sorter = new UserSorter();
  3548. private final Editor<T> editor = GWT.create(Editor.class);
  3549. private boolean dataIsBeingFetched = false;
  3550. /**
  3551. * The cell a click event originated from
  3552. * <p>
  3553. * This is a workaround to make Chrome work like Firefox. In Chrome,
  3554. * normally if you start a drag on one cell and release on:
  3555. * <ul>
  3556. * <li>that same cell, the click event is that {@code <td>}.
  3557. * <li>a cell on that same row, the click event is the parent {@code <tr>}.
  3558. * <li>a cell on another row, the click event is the table section ancestor
  3559. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  3560. * </ul>
  3561. *
  3562. * @see #onBrowserEvent(Event)
  3563. */
  3564. private Cell cellOnPrevMouseDown;
  3565. /**
  3566. * A scheduled command to re-evaluate the widths of <em>all columns</em>
  3567. * that have calculated widths. Most probably called because
  3568. * minwidth/maxwidth/expandratio has changed.
  3569. */
  3570. private final AutoColumnWidthsRecalculator autoColumnWidthsRecalculator = new AutoColumnWidthsRecalculator();
  3571. private boolean enabled = true;
  3572. private DetailsGenerator detailsGenerator = DetailsGenerator.NULL;
  3573. private GridSpacerUpdater gridSpacerUpdater = new GridSpacerUpdater();
  3574. /** A set keeping track of the indices of all currently open details */
  3575. private Set<Integer> visibleDetails = new HashSet<Integer>();
  3576. private boolean columnReorderingAllowed;
  3577. private ColumnHider columnHider = new ColumnHider();
  3578. private DragAndDropHandler dndHandler = new DragAndDropHandler();
  3579. private AutoScroller autoScroller = new AutoScroller(this);
  3580. private DragAndDropHandler.DragAndDropCallback headerCellDndCallback = new DragAndDropCallback() {
  3581. private final AutoScrollerCallback autoScrollerCallback = new AutoScrollerCallback() {
  3582. @Override
  3583. public void onAutoScroll(int scrollDiff) {
  3584. autoScrollX = scrollDiff;
  3585. onDragUpdate(null);
  3586. }
  3587. @Override
  3588. public void onAutoScrollReachedMin() {
  3589. // make sure the drop marker is visible on the left
  3590. autoScrollX = 0;
  3591. updateDragDropMarker(clientX);
  3592. }
  3593. @Override
  3594. public void onAutoScrollReachedMax() {
  3595. // make sure the drop marker is visible on the right
  3596. autoScrollX = 0;
  3597. updateDragDropMarker(clientX);
  3598. }
  3599. };
  3600. /**
  3601. * Elements for displaying the dragged column(s) and drop marker
  3602. * properly
  3603. */
  3604. private Element table;
  3605. private Element tableHeader;
  3606. /** Marks the column drop location */
  3607. private Element dropMarker;
  3608. /** A copy of the dragged column(s), moves with cursor. */
  3609. private Element dragElement;
  3610. /** Tracks index of the column whose left side the drop would occur */
  3611. private int latestColumnDropIndex;
  3612. /**
  3613. * Map of possible drop positions for the column and the corresponding
  3614. * column index.
  3615. */
  3616. private final TreeMap<Double, Integer> possibleDropPositions = new TreeMap<Double, Integer>();
  3617. /**
  3618. * Makes sure that drag cancel doesn't cause anything unwanted like sort
  3619. */
  3620. private HandlerRegistration columnSortPreventRegistration;
  3621. private int clientX;
  3622. /** How much the grid is being auto scrolled while dragging. */
  3623. private int autoScrollX;
  3624. /** Captures the value of the focused column before reordering */
  3625. private int focusedColumnIndex;
  3626. /** Offset caused by the drag and drop marker width */
  3627. private double dropMarkerWidthOffset;
  3628. private void initHeaderDragElementDOM() {
  3629. if (table == null) {
  3630. tableHeader = DOM.createTHead();
  3631. dropMarker = DOM.createDiv();
  3632. tableHeader.appendChild(dropMarker);
  3633. table = DOM.createTable();
  3634. table.appendChild(tableHeader);
  3635. table.setClassName("header-drag-table");
  3636. }
  3637. // update the style names on each run in case primary name has been
  3638. // modified
  3639. tableHeader.setClassName(escalator.getHeader().getElement()
  3640. .getClassName());
  3641. dropMarker.setClassName(getStylePrimaryName() + "-drop-marker");
  3642. int topOffset = 0;
  3643. for (int i = 0; i < eventCell.getRowIndex(); i++) {
  3644. topOffset += escalator.getHeader().getRowElement(i)
  3645. .getFirstChildElement().getOffsetHeight();
  3646. }
  3647. tableHeader.getStyle().setTop(topOffset, Unit.PX);
  3648. getElement().appendChild(table);
  3649. dropMarkerWidthOffset = WidgetUtil
  3650. .getRequiredWidthBoundingClientRectDouble(dropMarker) / 2;
  3651. }
  3652. @Override
  3653. public void onDragUpdate(Event e) {
  3654. if (e != null) {
  3655. clientX = WidgetUtil.getTouchOrMouseClientX(e);
  3656. autoScrollX = 0;
  3657. }
  3658. resolveDragElementHorizontalPosition(clientX);
  3659. updateDragDropMarker(clientX);
  3660. }
  3661. private void updateDragDropMarker(final int clientX) {
  3662. final double scrollLeft = getScrollLeft();
  3663. final double cursorXCoordinate = clientX
  3664. - escalator.getHeader().getElement().getAbsoluteLeft();
  3665. final Entry<Double, Integer> cellEdgeOnRight = possibleDropPositions
  3666. .ceilingEntry(cursorXCoordinate);
  3667. final Entry<Double, Integer> cellEdgeOnLeft = possibleDropPositions
  3668. .floorEntry(cursorXCoordinate);
  3669. final double diffToRightEdge = cellEdgeOnRight == null ? Double.MAX_VALUE
  3670. : cellEdgeOnRight.getKey() - cursorXCoordinate;
  3671. final double diffToLeftEdge = cellEdgeOnLeft == null ? Double.MAX_VALUE
  3672. : cursorXCoordinate - cellEdgeOnLeft.getKey();
  3673. double dropMarkerLeft = 0 - scrollLeft;
  3674. if (diffToRightEdge > diffToLeftEdge) {
  3675. latestColumnDropIndex = cellEdgeOnLeft.getValue();
  3676. dropMarkerLeft += cellEdgeOnLeft.getKey();
  3677. } else {
  3678. latestColumnDropIndex = cellEdgeOnRight.getValue();
  3679. dropMarkerLeft += cellEdgeOnRight.getKey();
  3680. }
  3681. dropMarkerLeft += autoScrollX;
  3682. final double frozenColumnsWidth = autoScroller
  3683. .getFrozenColumnsWidth();
  3684. final double rightBoundaryForDrag = getSidebarBoundaryComparedTo(dropMarkerLeft);
  3685. final int visibleColumns = getVisibleColumns().size();
  3686. // First check if the drop marker should move left because of the
  3687. // sidebar opening button. this only the case if the grid is
  3688. // scrolled to the right
  3689. if (latestColumnDropIndex == visibleColumns
  3690. && rightBoundaryForDrag < dropMarkerLeft
  3691. && dropMarkerLeft <= escalator.getInnerWidth()) {
  3692. dropMarkerLeft = rightBoundaryForDrag - dropMarkerWidthOffset;
  3693. }
  3694. // Check if the drop marker shouldn't be shown at all
  3695. else if (dropMarkerLeft < frozenColumnsWidth
  3696. || dropMarkerLeft > Math.min(rightBoundaryForDrag,
  3697. escalator.getInnerWidth()) || dropMarkerLeft < 0) {
  3698. dropMarkerLeft = -10000000;
  3699. }
  3700. dropMarker.getStyle().setLeft(dropMarkerLeft, Unit.PX);
  3701. }
  3702. private void resolveDragElementHorizontalPosition(final int clientX) {
  3703. double left = clientX - table.getAbsoluteLeft();
  3704. // Do not show the drag element beyond a spanned header cell
  3705. // limitation
  3706. final Double leftBound = possibleDropPositions.firstKey();
  3707. final Double rightBound = possibleDropPositions.lastKey();
  3708. final double scrollLeft = getScrollLeft();
  3709. if (left + scrollLeft < leftBound) {
  3710. left = leftBound - scrollLeft + autoScrollX;
  3711. } else if (left + scrollLeft > rightBound) {
  3712. left = rightBound - scrollLeft + autoScrollX;
  3713. }
  3714. // Do not show the drag element beyond the grid
  3715. final double sidebarBoundary = getSidebarBoundaryComparedTo(left);
  3716. final double gridBoundary = escalator.getInnerWidth();
  3717. final double rightBoundary = Math
  3718. .min(sidebarBoundary, gridBoundary);
  3719. // Do not show on left of the frozen columns (even if scrolled)
  3720. final int frozenColumnsWidth = (int) autoScroller
  3721. .getFrozenColumnsWidth();
  3722. left = Math.max(frozenColumnsWidth, Math.min(left, rightBoundary));
  3723. left -= dragElement.getClientWidth() / 2;
  3724. dragElement.getStyle().setLeft(left, Unit.PX);
  3725. }
  3726. private boolean isSidebarOnDraggedRow() {
  3727. return eventCell.getRowIndex() == 0 && sidebar.isInDOM()
  3728. && !sidebar.isOpen();
  3729. }
  3730. /**
  3731. * Returns the sidebar left coordinate, in relation to the grid. Or
  3732. * Double.MAX_VALUE if it doesn't cause a boundary.
  3733. */
  3734. private double getSidebarBoundaryComparedTo(double left) {
  3735. if (isSidebarOnDraggedRow()) {
  3736. double absoluteLeft = left + getElement().getAbsoluteLeft();
  3737. double sidebarLeft = sidebar.getElement().getAbsoluteLeft();
  3738. double diff = absoluteLeft - sidebarLeft;
  3739. if (diff > 0) {
  3740. return left - diff;
  3741. }
  3742. }
  3743. return Double.MAX_VALUE;
  3744. }
  3745. @Override
  3746. public boolean onDragStart(Event e) {
  3747. calculatePossibleDropPositions();
  3748. if (possibleDropPositions.isEmpty()) {
  3749. return false;
  3750. }
  3751. initHeaderDragElementDOM();
  3752. // needs to clone focus and sorting indicators too (UX)
  3753. dragElement = DOM.clone(eventCell.getElement(), true);
  3754. dragElement.getStyle().clearWidth();
  3755. dropMarker.getStyle().setProperty("height",
  3756. dragElement.getStyle().getHeight());
  3757. tableHeader.appendChild(dragElement);
  3758. // mark the column being dragged for styling
  3759. eventCell.getElement().addClassName("dragged");
  3760. // mark the floating cell, for styling & testing
  3761. dragElement.addClassName("dragged-column-header");
  3762. // start the auto scroll handler
  3763. autoScroller.setScrollArea(60);
  3764. autoScroller.start(e, ScrollAxis.HORIZONTAL, autoScrollerCallback);
  3765. return true;
  3766. }
  3767. @Override
  3768. public void onDragEnd() {
  3769. table.removeFromParent();
  3770. dragElement.removeFromParent();
  3771. eventCell.getElement().removeClassName("dragged");
  3772. }
  3773. @Override
  3774. public void onDrop() {
  3775. final int draggedColumnIndex = eventCell.getColumnIndex();
  3776. final int colspan = header.getRow(eventCell.getRowIndex())
  3777. .getCell(eventCell.getColumn()).getColspan();
  3778. if (latestColumnDropIndex != draggedColumnIndex
  3779. && latestColumnDropIndex != (draggedColumnIndex + colspan)) {
  3780. List<Column<?, T>> columns = getColumns();
  3781. List<Column<?, T>> reordered = new ArrayList<Column<?, T>>();
  3782. if (draggedColumnIndex < latestColumnDropIndex) {
  3783. reordered.addAll(columns.subList(0, draggedColumnIndex));
  3784. reordered.addAll(columns.subList(draggedColumnIndex
  3785. + colspan, latestColumnDropIndex));
  3786. reordered.addAll(columns.subList(draggedColumnIndex,
  3787. draggedColumnIndex + colspan));
  3788. reordered.addAll(columns.subList(latestColumnDropIndex,
  3789. columns.size()));
  3790. } else {
  3791. reordered.addAll(columns.subList(0, latestColumnDropIndex));
  3792. reordered.addAll(columns.subList(draggedColumnIndex,
  3793. draggedColumnIndex + colspan));
  3794. reordered.addAll(columns.subList(latestColumnDropIndex,
  3795. draggedColumnIndex));
  3796. reordered.addAll(columns.subList(draggedColumnIndex
  3797. + colspan, columns.size()));
  3798. }
  3799. reordered.remove(selectionColumn); // since setColumnOrder will
  3800. // add it anyway!
  3801. // capture focused cell column before reorder
  3802. Cell focusedCell = cellFocusHandler.getFocusedCell();
  3803. if (focusedCell != null) {
  3804. // take hidden columns into account
  3805. focusedColumnIndex = getColumns().indexOf(
  3806. getVisibleColumn(focusedCell.getColumn()));
  3807. }
  3808. Column<?, T>[] array = reordered.toArray(new Column[reordered
  3809. .size()]);
  3810. setColumnOrder(array);
  3811. transferCellFocusOnDrop();
  3812. } // else no reordering
  3813. }
  3814. private void transferCellFocusOnDrop() {
  3815. final Cell focusedCell = cellFocusHandler.getFocusedCell();
  3816. if (focusedCell != null) {
  3817. final int focusedColumnIndexDOM = focusedCell.getColumn();
  3818. final int focusedRowIndex = focusedCell.getRow();
  3819. final int draggedColumnIndex = eventCell.getColumnIndex();
  3820. // transfer focus if it was effected by the new column order
  3821. final RowContainer rowContainer = escalator
  3822. .findRowContainer(focusedCell.getElement());
  3823. if (focusedColumnIndex == draggedColumnIndex) {
  3824. // move with the dragged column
  3825. int adjustedDropIndex = latestColumnDropIndex > draggedColumnIndex ? latestColumnDropIndex - 1
  3826. : latestColumnDropIndex;
  3827. // remove hidden columns from indexing
  3828. adjustedDropIndex = getVisibleColumns().indexOf(
  3829. getColumn(adjustedDropIndex));
  3830. cellFocusHandler.setCellFocus(focusedRowIndex,
  3831. adjustedDropIndex, rowContainer);
  3832. } else if (latestColumnDropIndex <= focusedColumnIndex
  3833. && draggedColumnIndex > focusedColumnIndex) {
  3834. cellFocusHandler.setCellFocus(focusedRowIndex,
  3835. focusedColumnIndexDOM + 1, rowContainer);
  3836. } else if (latestColumnDropIndex > focusedColumnIndex
  3837. && draggedColumnIndex < focusedColumnIndex) {
  3838. cellFocusHandler.setCellFocus(focusedRowIndex,
  3839. focusedColumnIndexDOM - 1, rowContainer);
  3840. }
  3841. }
  3842. }
  3843. @Override
  3844. public void onDragCancel() {
  3845. // cancel next click so that we may prevent column sorting if
  3846. // mouse was released on top of the dragged cell
  3847. if (columnSortPreventRegistration == null) {
  3848. columnSortPreventRegistration = Event
  3849. .addNativePreviewHandler(new NativePreviewHandler() {
  3850. @Override
  3851. public void onPreviewNativeEvent(
  3852. NativePreviewEvent event) {
  3853. if (event.getTypeInt() == Event.ONCLICK) {
  3854. event.cancel();
  3855. event.getNativeEvent().preventDefault();
  3856. columnSortPreventRegistration
  3857. .removeHandler();
  3858. columnSortPreventRegistration = null;
  3859. }
  3860. }
  3861. });
  3862. }
  3863. autoScroller.stop();
  3864. }
  3865. /**
  3866. * Returns the amount of frozen columns. The selection column is always
  3867. * considered frozen, since it can't be moved.
  3868. */
  3869. private int getSelectionAndFrozenColumnCount() {
  3870. // no matter if selection column is frozen or not, it is considered
  3871. // frozen for column dnd reorder
  3872. if (getSelectionModel().getSelectionColumnRenderer() != null) {
  3873. return Math.max(0, getFrozenColumnCount()) + 1;
  3874. } else {
  3875. return Math.max(0, getFrozenColumnCount());
  3876. }
  3877. }
  3878. @SuppressWarnings("boxing")
  3879. private void calculatePossibleDropPositions() {
  3880. possibleDropPositions.clear();
  3881. final int draggedColumnIndex = eventCell.getColumnIndex();
  3882. final StaticRow<?> draggedCellRow = header.getRow(eventCell
  3883. .getRowIndex());
  3884. final int draggedColumnRightIndex = draggedColumnIndex
  3885. + draggedCellRow.getCell(eventCell.getColumn())
  3886. .getColspan();
  3887. final int frozenColumns = getSelectionAndFrozenColumnCount();
  3888. final Range draggedCellRange = Range.between(draggedColumnIndex,
  3889. draggedColumnRightIndex);
  3890. /*
  3891. * If the dragged cell intersects with a spanned cell in any other
  3892. * header or footer row, then the drag is limited inside that
  3893. * spanned cell. The same rules apply: the cell can't be dropped
  3894. * inside another spanned cell. The left and right bounds keep track
  3895. * of the edges of the most limiting spanned cell.
  3896. */
  3897. int leftBound = -1;
  3898. int rightBound = getColumnCount() + 1;
  3899. final HashSet<Integer> unavailableColumnDropIndices = new HashSet<Integer>();
  3900. final List<StaticRow<?>> rows = new ArrayList<StaticRow<?>>();
  3901. rows.addAll(header.getRows());
  3902. rows.addAll(footer.getRows());
  3903. for (StaticRow<?> row : rows) {
  3904. if (!row.hasSpannedCells()) {
  3905. continue;
  3906. }
  3907. final boolean isDraggedCellRow = row.equals(draggedCellRow);
  3908. for (int cellColumnIndex = frozenColumns; cellColumnIndex < getColumnCount(); cellColumnIndex++) {
  3909. StaticCell cell = row.getCell(getColumn(cellColumnIndex));
  3910. int colspan = cell.getColspan();
  3911. if (colspan <= 1) {
  3912. continue;
  3913. }
  3914. final int cellColumnRightIndex = cellColumnIndex + colspan;
  3915. final Range cellRange = Range.between(cellColumnIndex,
  3916. cellColumnRightIndex);
  3917. final boolean intersects = draggedCellRange
  3918. .intersects(cellRange);
  3919. if (intersects && !isDraggedCellRow) {
  3920. // if the currently iterated cell is inside or same as
  3921. // the dragged cell, then it doesn't restrict the drag
  3922. if (cellRange.isSubsetOf(draggedCellRange)) {
  3923. cellColumnIndex = cellColumnRightIndex - 1;
  3924. continue;
  3925. }
  3926. /*
  3927. * if the dragged cell is a spanned cell and it crosses
  3928. * with the currently iterated cell without sharing
  3929. * either start or end then not possible to drag the
  3930. * cell.
  3931. */
  3932. if (!draggedCellRange.isSubsetOf(cellRange)) {
  3933. return;
  3934. }
  3935. // the spanned cell overlaps the dragged cell (but is
  3936. // not the dragged cell)
  3937. if (cellColumnIndex <= draggedColumnIndex
  3938. && cellColumnIndex > leftBound) {
  3939. leftBound = cellColumnIndex;
  3940. }
  3941. if (cellColumnRightIndex < rightBound) {
  3942. rightBound = cellColumnRightIndex;
  3943. }
  3944. cellColumnIndex = cellColumnRightIndex - 1;
  3945. }
  3946. else { // can't drop inside a spanned cell, or this is the
  3947. // dragged cell
  3948. while (colspan > 1) {
  3949. cellColumnIndex++;
  3950. colspan--;
  3951. unavailableColumnDropIndices.add(cellColumnIndex);
  3952. }
  3953. }
  3954. }
  3955. }
  3956. if (leftBound == (rightBound - 1)) {
  3957. return;
  3958. }
  3959. double position = autoScroller.getFrozenColumnsWidth();
  3960. // iterate column indices and add possible drop positions
  3961. for (int i = frozenColumns; i < getColumnCount(); i++) {
  3962. Column<?, T> column = getColumn(i);
  3963. if (!unavailableColumnDropIndices.contains(i)
  3964. && !column.isHidden()) {
  3965. if (leftBound != -1) {
  3966. if (i >= leftBound && i <= rightBound) {
  3967. possibleDropPositions.put(position, i);
  3968. }
  3969. } else {
  3970. possibleDropPositions.put(position, i);
  3971. }
  3972. }
  3973. position += column.getWidthActual();
  3974. }
  3975. if (leftBound == -1) {
  3976. // add the right side of the last column as columns.size()
  3977. possibleDropPositions.put(position, getColumnCount());
  3978. }
  3979. }
  3980. };
  3981. /**
  3982. * Enumeration for easy setting of selection mode.
  3983. */
  3984. public enum SelectionMode {
  3985. /**
  3986. * Shortcut for {@link SelectionModelSingle}.
  3987. */
  3988. SINGLE {
  3989. @Override
  3990. protected <T> SelectionModel<T> createModel() {
  3991. return GWT.create(SelectionModelSingle.class);
  3992. }
  3993. },
  3994. /**
  3995. * Shortcut for {@link SelectionModelMulti}.
  3996. */
  3997. MULTI {
  3998. @Override
  3999. protected <T> SelectionModel<T> createModel() {
  4000. return GWT.create(SelectionModelMulti.class);
  4001. }
  4002. },
  4003. /**
  4004. * Shortcut for {@link SelectionModelNone}.
  4005. */
  4006. NONE {
  4007. @Override
  4008. protected <T> SelectionModel<T> createModel() {
  4009. return GWT.create(SelectionModelNone.class);
  4010. }
  4011. };
  4012. protected abstract <T> SelectionModel<T> createModel();
  4013. }
  4014. /**
  4015. * Base class for grid columns internally used by the Grid. The user should
  4016. * use {@link Column} when creating new columns.
  4017. *
  4018. * @param <C>
  4019. * the column type
  4020. *
  4021. * @param <T>
  4022. * the row type
  4023. */
  4024. public static abstract class Column<C, T> {
  4025. /**
  4026. * Default renderer for GridColumns. Renders everything into text
  4027. * through {@link Object#toString()}.
  4028. */
  4029. private final class DefaultTextRenderer implements Renderer<Object> {
  4030. boolean warned = false;
  4031. private final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  4032. + "A more suitable renderer should be set using the setRenderer() method.";
  4033. @Override
  4034. public void render(RendererCellReference cell, Object data) {
  4035. if (!warned && !(data instanceof String)) {
  4036. getLogger().warning(
  4037. Column.this.toString() + ": "
  4038. + DEFAULT_RENDERER_WARNING);
  4039. warned = true;
  4040. }
  4041. final String text;
  4042. if (data == null) {
  4043. text = "";
  4044. } else {
  4045. text = data.toString();
  4046. }
  4047. cell.getElement().setInnerText(text);
  4048. }
  4049. }
  4050. /**
  4051. * the column is associated with
  4052. */
  4053. private Grid<T> grid;
  4054. /**
  4055. * Width of column in pixels as {@link #setWidth(double)} has been
  4056. * called
  4057. */
  4058. private double widthUser = GridConstants.DEFAULT_COLUMN_WIDTH_PX;
  4059. /**
  4060. * Renderer for rendering a value into the cell
  4061. */
  4062. private Renderer<? super C> bodyRenderer;
  4063. private boolean sortable = false;
  4064. private boolean editable = true;
  4065. private boolean resizable = true;
  4066. private boolean hidden = false;
  4067. private boolean hidable = false;
  4068. private String headerCaption = "";
  4069. private String hidingToggleCaption = null;
  4070. private double minimumWidthPx = GridConstants.DEFAULT_MIN_WIDTH;
  4071. private double maximumWidthPx = GridConstants.DEFAULT_MAX_WIDTH;
  4072. private int expandRatio = GridConstants.DEFAULT_EXPAND_RATIO;
  4073. /**
  4074. * Constructs a new column with a simple TextRenderer.
  4075. */
  4076. public Column() {
  4077. setRenderer(new DefaultTextRenderer());
  4078. }
  4079. /**
  4080. * Constructs a new column with a simple TextRenderer.
  4081. *
  4082. * @param caption
  4083. * The header caption for this column
  4084. *
  4085. * @throws IllegalArgumentException
  4086. * if given header caption is null
  4087. */
  4088. public Column(String caption) throws IllegalArgumentException {
  4089. this();
  4090. setHeaderCaption(caption);
  4091. }
  4092. /**
  4093. * Constructs a new column with a custom renderer.
  4094. *
  4095. * @param renderer
  4096. * The renderer to use for rendering the cells
  4097. *
  4098. * @throws IllegalArgumentException
  4099. * if given Renderer is null
  4100. */
  4101. public Column(Renderer<? super C> renderer)
  4102. throws IllegalArgumentException {
  4103. setRenderer(renderer);
  4104. }
  4105. /**
  4106. * Constructs a new column with a custom renderer.
  4107. *
  4108. * @param renderer
  4109. * The renderer to use for rendering the cells
  4110. * @param caption
  4111. * The header caption for this column
  4112. *
  4113. * @throws IllegalArgumentException
  4114. * if given Renderer or header caption is null
  4115. */
  4116. public Column(String caption, Renderer<? super C> renderer)
  4117. throws IllegalArgumentException {
  4118. this(renderer);
  4119. setHeaderCaption(caption);
  4120. }
  4121. /**
  4122. * Internally used by the grid to set itself
  4123. *
  4124. * @param grid
  4125. */
  4126. private void setGrid(Grid<T> grid) {
  4127. if (this.grid != null && grid != null) {
  4128. // Trying to replace grid
  4129. throw new IllegalStateException("Column already is attached "
  4130. + "to a grid. Remove the column first from the grid "
  4131. + "and then add it. (in: " + toString() + ")");
  4132. }
  4133. if (this.grid != null) {
  4134. this.grid.recalculateColumnWidths();
  4135. }
  4136. this.grid = grid;
  4137. if (this.grid != null) {
  4138. this.grid.recalculateColumnWidths();
  4139. }
  4140. }
  4141. /**
  4142. * Sets a header caption for this column.
  4143. *
  4144. * @param caption
  4145. * The header caption for this column
  4146. * @return the column itself
  4147. *
  4148. */
  4149. public Column<C, T> setHeaderCaption(String caption) {
  4150. if (caption == null) {
  4151. caption = "";
  4152. }
  4153. if (!this.headerCaption.equals(caption)) {
  4154. this.headerCaption = caption;
  4155. if (grid != null) {
  4156. updateHeader();
  4157. }
  4158. }
  4159. return this;
  4160. }
  4161. /**
  4162. * Returns the current header caption for this column
  4163. *
  4164. * @since 7.6
  4165. * @return the header caption string
  4166. */
  4167. public String getHeaderCaption() {
  4168. return headerCaption;
  4169. }
  4170. private void updateHeader() {
  4171. HeaderRow row = grid.getHeader().getDefaultRow();
  4172. if (row != null) {
  4173. row.getCell(this).setText(headerCaption);
  4174. if (isHidable()) {
  4175. grid.columnHider.updateHidingToggle(this);
  4176. }
  4177. }
  4178. }
  4179. /**
  4180. * Returns the data that should be rendered into the cell. By default
  4181. * returning Strings and Widgets are supported. If the return type is a
  4182. * String then it will be treated as preformatted text.
  4183. * <p>
  4184. * To support other types you will need to pass a custom renderer to the
  4185. * column via the column constructor.
  4186. *
  4187. * @param row
  4188. * The row object that provides the cell content.
  4189. *
  4190. * @return The cell content
  4191. */
  4192. public abstract C getValue(T row);
  4193. /**
  4194. * The renderer to render the cell with. By default renders the data as
  4195. * a String or adds the widget into the cell if the column type is of
  4196. * widget type.
  4197. *
  4198. * @return The renderer to render the cell content with
  4199. */
  4200. public Renderer<? super C> getRenderer() {
  4201. return bodyRenderer;
  4202. }
  4203. /**
  4204. * Sets a custom {@link Renderer} for this column.
  4205. *
  4206. * @param renderer
  4207. * The renderer to use for rendering the cells
  4208. * @return the column itself
  4209. *
  4210. * @throws IllegalArgumentException
  4211. * if given Renderer is null
  4212. */
  4213. public Column<C, T> setRenderer(Renderer<? super C> renderer)
  4214. throws IllegalArgumentException {
  4215. if (renderer == null) {
  4216. throw new IllegalArgumentException("Renderer cannot be null.");
  4217. }
  4218. if (renderer != bodyRenderer) {
  4219. // Variables used to restore removed column.
  4220. boolean columnRemoved = false;
  4221. double widthInConfiguration = 0.0d;
  4222. ColumnConfiguration conf = null;
  4223. int index = 0;
  4224. if (grid != null
  4225. && (bodyRenderer instanceof WidgetRenderer || renderer instanceof WidgetRenderer)) {
  4226. // Column needs to be recreated.
  4227. index = grid.getColumns().indexOf(this);
  4228. conf = grid.escalator.getColumnConfiguration();
  4229. widthInConfiguration = conf.getColumnWidth(index);
  4230. conf.removeColumns(index, 1);
  4231. columnRemoved = true;
  4232. }
  4233. // Complex renderers need to be destroyed.
  4234. if (bodyRenderer instanceof ComplexRenderer) {
  4235. ((ComplexRenderer) bodyRenderer).destroy();
  4236. }
  4237. bodyRenderer = renderer;
  4238. if (columnRemoved) {
  4239. // Restore the column.
  4240. conf.insertColumns(index, 1);
  4241. conf.setColumnWidth(index, widthInConfiguration);
  4242. }
  4243. if (grid != null) {
  4244. grid.refreshBody();
  4245. }
  4246. }
  4247. return this;
  4248. }
  4249. /**
  4250. * Sets the pixel width of the column. Use a negative value for the grid
  4251. * to autosize column based on content and available space.
  4252. * <p>
  4253. * This action is done "finally", once the current execution loop
  4254. * returns. This is done to reduce overhead of unintentionally always
  4255. * recalculate all columns, when modifying several columns at once.
  4256. * <p>
  4257. * If the column is currently {@link #isHidden() hidden}, then this set
  4258. * width has effect only once the column has been made visible again.
  4259. *
  4260. * @param pixels
  4261. * the width in pixels or negative for auto sizing
  4262. */
  4263. public Column<C, T> setWidth(double pixels) {
  4264. if (!WidgetUtil.pixelValuesEqual(widthUser, pixels)) {
  4265. widthUser = pixels;
  4266. if (!isHidden()) {
  4267. scheduleColumnWidthRecalculator();
  4268. }
  4269. }
  4270. return this;
  4271. }
  4272. void doSetWidth(double pixels) {
  4273. assert !isHidden() : "applying width for a hidden column";
  4274. if (grid != null) {
  4275. int index = grid.getVisibleColumns().indexOf(this);
  4276. ColumnConfiguration conf = grid.escalator
  4277. .getColumnConfiguration();
  4278. conf.setColumnWidth(index, pixels);
  4279. }
  4280. }
  4281. /**
  4282. * Returns the pixel width of the column as given by the user.
  4283. * <p>
  4284. * <em>Note:</em> If a negative value was given to
  4285. * {@link #setWidth(double)}, that same negative value is returned here.
  4286. * <p>
  4287. * <em>Note:</em> Returns the value, even if the column is currently
  4288. * {@link #isHidden() hidden}.
  4289. *
  4290. * @return pixel width of the column, or a negative number if the column
  4291. * width has been automatically calculated.
  4292. * @see #setWidth(double)
  4293. * @see #getWidthActual()
  4294. */
  4295. public double getWidth() {
  4296. return widthUser;
  4297. }
  4298. /**
  4299. * Returns the effective pixel width of the column.
  4300. * <p>
  4301. * This differs from {@link #getWidth()} only when the column has been
  4302. * automatically resized, or when the column is currently
  4303. * {@link #isHidden() hidden}, when the value is 0.
  4304. *
  4305. * @return pixel width of the column.
  4306. */
  4307. public double getWidthActual() {
  4308. if (isHidden()) {
  4309. return 0;
  4310. }
  4311. return grid.escalator.getColumnConfiguration()
  4312. .getColumnWidthActual(
  4313. grid.getVisibleColumns().indexOf(this));
  4314. }
  4315. void reapplyWidth() {
  4316. scheduleColumnWidthRecalculator();
  4317. }
  4318. /**
  4319. * Sets whether the column should be sortable by the user. The grid can
  4320. * be sorted by a sortable column by clicking or tapping the column's
  4321. * default header. Programmatic sorting using the Grid#sort methods is
  4322. * not affected by this setting.
  4323. *
  4324. * @param sortable
  4325. * {@code true} if the user should be able to sort the
  4326. * column, {@code false} otherwise
  4327. * @return the column itself
  4328. */
  4329. public Column<C, T> setSortable(boolean sortable) {
  4330. if (this.sortable != sortable) {
  4331. this.sortable = sortable;
  4332. if (grid != null) {
  4333. grid.refreshHeader();
  4334. }
  4335. }
  4336. return this;
  4337. }
  4338. /**
  4339. * Returns whether the user can sort the grid by this column.
  4340. * <p>
  4341. * <em>Note:</em> it is possible to sort by this column programmatically
  4342. * using the Grid#sort methods regardless of the returned value.
  4343. *
  4344. * @return {@code true} if the column is sortable by the user,
  4345. * {@code false} otherwise
  4346. */
  4347. public boolean isSortable() {
  4348. return sortable;
  4349. }
  4350. /**
  4351. * Sets whether this column can be resized by the user.
  4352. *
  4353. * @since 7.6
  4354. *
  4355. * @param resizable
  4356. * {@code true} if this column should be resizable,
  4357. * {@code false} otherwise
  4358. */
  4359. public Column<C, T> setResizable(boolean resizable) {
  4360. if (this.resizable != resizable) {
  4361. this.resizable = resizable;
  4362. if (grid != null) {
  4363. grid.refreshHeader();
  4364. }
  4365. }
  4366. return this;
  4367. }
  4368. /**
  4369. * Returns whether this column can be resized by the user. Default is
  4370. * {@code true}.
  4371. * <p>
  4372. * <em>Note:</em> the column can be programmatically resized using
  4373. * {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
  4374. * of the returned value.
  4375. *
  4376. * @since 7.6
  4377. *
  4378. * @return {@code true} if this column is resizable, {@code false}
  4379. * otherwise
  4380. */
  4381. public boolean isResizable() {
  4382. return resizable;
  4383. }
  4384. /**
  4385. * Hides or shows the column. By default columns are visible before
  4386. * explicitly hiding them.
  4387. *
  4388. * @since 7.5.0
  4389. * @param hidden
  4390. * <code>true</code> to hide the column, <code>false</code>
  4391. * to show
  4392. */
  4393. public Column<C, T> setHidden(boolean hidden) {
  4394. setHidden(hidden, false);
  4395. return this;
  4396. }
  4397. private void setHidden(boolean hidden, boolean userOriginated) {
  4398. if (this.hidden != hidden) {
  4399. if (hidden) {
  4400. grid.escalator.getColumnConfiguration().removeColumns(
  4401. grid.getVisibleColumns().indexOf(this), 1);
  4402. this.hidden = hidden;
  4403. } else {
  4404. this.hidden = hidden;
  4405. final int columnIndex = grid.getVisibleColumns().indexOf(
  4406. this);
  4407. grid.escalator.getColumnConfiguration().insertColumns(
  4408. columnIndex, 1);
  4409. // make sure column is set to frozen if it needs to be,
  4410. // escalator doesn't handle situation where the added column
  4411. // would be the last frozen column
  4412. int gridFrozenColumns = grid.getFrozenColumnCount();
  4413. int escalatorFrozenColumns = grid.escalator
  4414. .getColumnConfiguration().getFrozenColumnCount();
  4415. if (gridFrozenColumns > escalatorFrozenColumns
  4416. && escalatorFrozenColumns == columnIndex) {
  4417. grid.escalator.getColumnConfiguration()
  4418. .setFrozenColumnCount(++escalatorFrozenColumns);
  4419. }
  4420. }
  4421. grid.columnHider.updateHidingToggle(this);
  4422. grid.header.updateColSpans();
  4423. grid.footer.updateColSpans();
  4424. scheduleColumnWidthRecalculator();
  4425. this.grid.fireEvent(new ColumnVisibilityChangeEvent<T>(this,
  4426. hidden, userOriginated));
  4427. }
  4428. }
  4429. /**
  4430. * Returns whether this column is hidden. Default is {@code false}.
  4431. *
  4432. * @since 7.5.0
  4433. * @return {@code true} if the column is currently hidden, {@code false}
  4434. * otherwise
  4435. */
  4436. public boolean isHidden() {
  4437. return hidden;
  4438. }
  4439. /**
  4440. * Set whether it is possible for the user to hide this column or not.
  4441. * Default is {@code false}.
  4442. * <p>
  4443. * <em>Note:</em> it is still possible to hide the column
  4444. * programmatically using {@link #setHidden(boolean)}.
  4445. *
  4446. * @since 7.5.0
  4447. * @param hidable
  4448. * {@code true} the user can hide this column, {@code false}
  4449. * otherwise
  4450. */
  4451. public Column<C, T> setHidable(boolean hidable) {
  4452. if (this.hidable != hidable) {
  4453. this.hidable = hidable;
  4454. grid.columnHider.updateColumnHidable(this);
  4455. }
  4456. return this;
  4457. }
  4458. /**
  4459. * Is it possible for the the user to hide this column. Default is
  4460. * {@code false}.
  4461. * <p>
  4462. * <em>Note:</em> the column can be programmatically hidden using
  4463. * {@link #setHidden(boolean)} regardless of the returned value.
  4464. *
  4465. * @since 7.5.0
  4466. * @return <code>true</code> if the user can hide the column,
  4467. * <code>false</code> if not
  4468. */
  4469. public boolean isHidable() {
  4470. return hidable;
  4471. }
  4472. /**
  4473. * Sets the hiding toggle's caption for this column. Shown in the toggle
  4474. * for this column in the grid's sidebar when the column is
  4475. * {@link #isHidable() hidable}.
  4476. * <p>
  4477. * The default value is <code>null</code>. In this case the header
  4478. * caption is used, see {@link #setHeaderCaption(String)}.
  4479. *
  4480. * @since 7.5.0
  4481. * @param hidingToggleCaption
  4482. * the caption for the hiding toggle for this column
  4483. */
  4484. public Column<C, T> setHidingToggleCaption(String hidingToggleCaption) {
  4485. this.hidingToggleCaption = hidingToggleCaption;
  4486. if (isHidable()) {
  4487. grid.columnHider.updateHidingToggle(this);
  4488. }
  4489. return this;
  4490. }
  4491. /**
  4492. * Gets the hiding toggle caption for this column.
  4493. *
  4494. * @since 7.5.0
  4495. * @see #setHidingToggleCaption(String)
  4496. * @return the hiding toggle's caption for this column
  4497. */
  4498. public String getHidingToggleCaption() {
  4499. return hidingToggleCaption;
  4500. }
  4501. @Override
  4502. public String toString() {
  4503. String details = "";
  4504. if (headerCaption != null && !headerCaption.isEmpty()) {
  4505. details += "header:\"" + headerCaption + "\" ";
  4506. } else {
  4507. details += "header:empty ";
  4508. }
  4509. if (grid != null) {
  4510. int index = grid.getColumns().indexOf(this);
  4511. if (index != -1) {
  4512. details += "attached:#" + index + " ";
  4513. } else {
  4514. details += "attached:unindexed ";
  4515. }
  4516. } else {
  4517. details += "detached ";
  4518. }
  4519. details += "sortable:" + sortable + " ";
  4520. return getClass().getSimpleName() + "[" + details.trim() + "]";
  4521. }
  4522. /**
  4523. * Sets the minimum width for this column.
  4524. * <p>
  4525. * This defines the minimum guaranteed pixel width of the column
  4526. * <em>when it is set to expand</em>.
  4527. * <p>
  4528. * This action is done "finally", once the current execution loop
  4529. * returns. This is done to reduce overhead of unintentionally always
  4530. * recalculate all columns, when modifying several columns at once.
  4531. *
  4532. * @param pixels
  4533. * the minimum width
  4534. * @return this column
  4535. */
  4536. public Column<C, T> setMinimumWidth(double pixels) {
  4537. final double maxwidth = getMaximumWidth();
  4538. if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
  4539. throw new IllegalArgumentException("New minimum width ("
  4540. + pixels + ") was greater than maximum width ("
  4541. + maxwidth + ")");
  4542. }
  4543. if (minimumWidthPx != pixels) {
  4544. minimumWidthPx = pixels;
  4545. scheduleColumnWidthRecalculator();
  4546. }
  4547. return this;
  4548. }
  4549. /**
  4550. * Sets the maximum width for this column.
  4551. * <p>
  4552. * This defines the maximum allowed pixel width of the column
  4553. * <em>when it is set to expand</em>.
  4554. * <p>
  4555. * This action is done "finally", once the current execution loop
  4556. * returns. This is done to reduce overhead of unintentionally always
  4557. * recalculate all columns, when modifying several columns at once.
  4558. *
  4559. * @param pixels
  4560. * the maximum width
  4561. * @param immediately
  4562. * <code>true</code> if the widths should be executed
  4563. * immediately (ignoring lazy loading completely), or
  4564. * <code>false</code> if the command should be run after a
  4565. * while (duplicate non-immediately invocations are ignored).
  4566. * @return this column
  4567. */
  4568. public Column<C, T> setMaximumWidth(double pixels) {
  4569. final double minwidth = getMinimumWidth();
  4570. if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
  4571. throw new IllegalArgumentException("New maximum width ("
  4572. + pixels + ") was less than minimum width (" + minwidth
  4573. + ")");
  4574. }
  4575. if (maximumWidthPx != pixels) {
  4576. maximumWidthPx = pixels;
  4577. scheduleColumnWidthRecalculator();
  4578. }
  4579. return this;
  4580. }
  4581. /**
  4582. * Sets the ratio with which the column expands.
  4583. * <p>
  4584. * By default, all columns expand equally (treated as if all of them had
  4585. * an expand ratio of 1). Once at least one column gets a defined expand
  4586. * ratio, the implicit expand ratio is removed, and only the defined
  4587. * expand ratios are taken into account.
  4588. * <p>
  4589. * If a column has a defined width ({@link #setWidth(double)}), it
  4590. * overrides this method's effects.
  4591. * <p>
  4592. * <em>Example:</em> A grid with three columns, with expand ratios 0, 1
  4593. * and 2, respectively. The column with a <strong>ratio of 0 is exactly
  4594. * as wide as its contents requires</strong>. The column with a ratio of
  4595. * 1 is as wide as it needs, <strong>plus a third of any excess
  4596. * space</strong>, bceause we have 3 parts total, and this column
  4597. * reservs only one of those. The column with a ratio of 2, is as wide
  4598. * as it needs to be, <strong>plus two thirds</strong> of the excess
  4599. * width.
  4600. * <p>
  4601. * This action is done "finally", once the current execution loop
  4602. * returns. This is done to reduce overhead of unintentionally always
  4603. * recalculate all columns, when modifying several columns at once.
  4604. *
  4605. * @param expandRatio
  4606. * the expand ratio of this column. {@code 0} to not have it
  4607. * expand at all. A negative number to clear the expand
  4608. * value.
  4609. * @return this column
  4610. */
  4611. public Column<C, T> setExpandRatio(int ratio) {
  4612. if (expandRatio != ratio) {
  4613. expandRatio = ratio;
  4614. scheduleColumnWidthRecalculator();
  4615. }
  4616. return this;
  4617. }
  4618. /**
  4619. * Clears the column's expand ratio.
  4620. * <p>
  4621. * Same as calling {@link #setExpandRatio(int) setExpandRatio(-1)}
  4622. *
  4623. * @return this column
  4624. */
  4625. public Column<C, T> clearExpandRatio() {
  4626. return setExpandRatio(-1);
  4627. }
  4628. /**
  4629. * Gets the minimum width for this column.
  4630. *
  4631. * @return the minimum width for this column
  4632. * @see #setMinimumWidth(double)
  4633. */
  4634. public double getMinimumWidth() {
  4635. return minimumWidthPx;
  4636. }
  4637. /**
  4638. * Gets the maximum width for this column.
  4639. *
  4640. * @return the maximum width for this column
  4641. * @see #setMaximumWidth(double)
  4642. */
  4643. public double getMaximumWidth() {
  4644. return maximumWidthPx;
  4645. }
  4646. /**
  4647. * Gets the expand ratio for this column.
  4648. *
  4649. * @return the expand ratio for this column
  4650. * @see #setExpandRatio(int)
  4651. */
  4652. public int getExpandRatio() {
  4653. return expandRatio;
  4654. }
  4655. /**
  4656. * Sets whether the values in this column should be editable by the user
  4657. * when the row editor is active. By default columns are editable.
  4658. *
  4659. * @param editable
  4660. * {@code true} to set this column editable, {@code false}
  4661. * otherwise
  4662. * @return this column
  4663. *
  4664. * @throws IllegalStateException
  4665. * if the editor is currently active
  4666. *
  4667. * @see Grid#editRow(int)
  4668. * @see Grid#isEditorActive()
  4669. */
  4670. public Column<C, T> setEditable(boolean editable) {
  4671. if (editable != this.editable && grid.isEditorActive()) {
  4672. throw new IllegalStateException(
  4673. "Cannot change column editable status while the editor is active");
  4674. }
  4675. this.editable = editable;
  4676. return this;
  4677. }
  4678. /**
  4679. * Returns whether the values in this column are editable by the user
  4680. * when the row editor is active.
  4681. *
  4682. * @return {@code true} if this column is editable, {@code false}
  4683. * otherwise
  4684. *
  4685. * @see #setEditable(boolean)
  4686. */
  4687. public boolean isEditable() {
  4688. return editable;
  4689. }
  4690. private void scheduleColumnWidthRecalculator() {
  4691. if (grid != null) {
  4692. grid.recalculateColumnWidths();
  4693. } else {
  4694. /*
  4695. * NOOP
  4696. *
  4697. * Since setGrid() will call reapplyWidths as the colum is
  4698. * attached to a grid, it will call setWidth, which, in turn,
  4699. * will call this method again. Therefore, it's guaranteed that
  4700. * the recalculation is scheduled eventually, once the column is
  4701. * attached to a grid.
  4702. */
  4703. }
  4704. }
  4705. /**
  4706. * Resets the default header cell contents to column header captions.
  4707. *
  4708. * @since 7.5.1
  4709. * @param cell
  4710. * default header cell for this column
  4711. */
  4712. protected void setDefaultHeaderContent(HeaderCell cell) {
  4713. cell.setText(headerCaption);
  4714. }
  4715. }
  4716. protected class BodyUpdater implements EscalatorUpdater {
  4717. @Override
  4718. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  4719. int rowIndex = row.getRow();
  4720. rowReference.set(rowIndex, getDataSource().getRow(rowIndex),
  4721. row.getElement());
  4722. for (FlyweightCell cell : cellsToAttach) {
  4723. Renderer<?> renderer = findRenderer(cell);
  4724. if (renderer instanceof ComplexRenderer) {
  4725. try {
  4726. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4727. rendererCellReference.set(cell,
  4728. getColumns().indexOf(column), column);
  4729. ((ComplexRenderer<?>) renderer)
  4730. .init(rendererCellReference);
  4731. } catch (RuntimeException e) {
  4732. getLogger().log(
  4733. Level.SEVERE,
  4734. "Error initing cell in column "
  4735. + cell.getColumn(), e);
  4736. }
  4737. }
  4738. }
  4739. }
  4740. @Override
  4741. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  4742. for (FlyweightCell cell : attachedCells) {
  4743. Renderer<?> renderer = findRenderer(cell);
  4744. if (renderer instanceof WidgetRenderer) {
  4745. try {
  4746. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  4747. Widget widget = widgetRenderer.createWidget();
  4748. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  4749. assert widget.getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  4750. assert cell.getElement().getChildCount() == 0 : "Cell content should be empty when adding Widget";
  4751. // Physical attach
  4752. cell.getElement().appendChild(widget.getElement());
  4753. // Logical attach
  4754. setParent(widget, Grid.this);
  4755. } catch (RuntimeException e) {
  4756. getLogger().log(
  4757. Level.SEVERE,
  4758. "Error attaching child widget in column "
  4759. + cell.getColumn(), e);
  4760. }
  4761. }
  4762. }
  4763. }
  4764. @Override
  4765. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4766. int rowIndex = row.getRow();
  4767. TableRowElement rowElement = row.getElement();
  4768. T rowData = dataSource.getRow(rowIndex);
  4769. boolean hasData = rowData != null;
  4770. /*
  4771. * TODO could be more efficient to build a list of all styles that
  4772. * should be used and update the element only once instead of
  4773. * attempting to update only the ones that have changed.
  4774. */
  4775. // Assign stylename for rows with data
  4776. boolean usedToHaveData = rowElement
  4777. .hasClassName(rowHasDataStyleName);
  4778. if (usedToHaveData != hasData) {
  4779. setStyleName(rowElement, rowHasDataStyleName, hasData);
  4780. }
  4781. boolean isEvenIndex = (row.getRow() % 2 == 0);
  4782. setStyleName(rowElement, rowStripeStyleName, !isEvenIndex);
  4783. rowReference.set(rowIndex, rowData, rowElement);
  4784. if (hasData) {
  4785. setStyleName(rowElement, rowSelectedStyleName,
  4786. isSelected(rowData));
  4787. if (rowStyleGenerator != null) {
  4788. try {
  4789. String rowStylename = rowStyleGenerator
  4790. .getStyle(rowReference);
  4791. setCustomStyleName(rowElement, rowStylename);
  4792. } catch (RuntimeException e) {
  4793. getLogger().log(
  4794. Level.SEVERE,
  4795. "Error generating styles for row "
  4796. + row.getRow(), e);
  4797. }
  4798. } else {
  4799. // Remove in case there was a generator previously
  4800. setCustomStyleName(rowElement, null);
  4801. }
  4802. } else if (usedToHaveData) {
  4803. setStyleName(rowElement, rowSelectedStyleName, false);
  4804. setCustomStyleName(rowElement, null);
  4805. }
  4806. cellFocusHandler.updateFocusedRowStyle(row);
  4807. for (FlyweightCell cell : cellsToUpdate) {
  4808. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4809. final int columnIndex = getColumns().indexOf(column);
  4810. assert column != null : "Column was not found from cell ("
  4811. + cell.getColumn() + "," + cell.getRow() + ")";
  4812. cellFocusHandler.updateFocusedCellStyle(cell,
  4813. escalator.getBody());
  4814. if (hasData && cellStyleGenerator != null) {
  4815. try {
  4816. cellReference
  4817. .set(cell.getColumn(), columnIndex, column);
  4818. String generatedStyle = cellStyleGenerator
  4819. .getStyle(cellReference);
  4820. setCustomStyleName(cell.getElement(), generatedStyle);
  4821. } catch (RuntimeException e) {
  4822. getLogger().log(
  4823. Level.SEVERE,
  4824. "Error generating style for cell in column "
  4825. + cell.getColumn(), e);
  4826. }
  4827. } else if (hasData || usedToHaveData) {
  4828. setCustomStyleName(cell.getElement(), null);
  4829. }
  4830. Renderer renderer = column.getRenderer();
  4831. try {
  4832. rendererCellReference.set(cell, columnIndex, column);
  4833. if (renderer instanceof ComplexRenderer) {
  4834. // Hide cell content if needed
  4835. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  4836. if (hasData) {
  4837. if (!usedToHaveData) {
  4838. // Prepare cell for rendering
  4839. clxRenderer.setContentVisible(
  4840. rendererCellReference, true);
  4841. }
  4842. Object value = column.getValue(rowData);
  4843. clxRenderer.render(rendererCellReference, value);
  4844. } else {
  4845. // Prepare cell for no data
  4846. clxRenderer.setContentVisible(
  4847. rendererCellReference, false);
  4848. }
  4849. } else if (hasData) {
  4850. // Simple renderers just render
  4851. Object value = column.getValue(rowData);
  4852. renderer.render(rendererCellReference, value);
  4853. } else {
  4854. // Clear cell if there is no data
  4855. cell.getElement().removeAllChildren();
  4856. }
  4857. } catch (RuntimeException e) {
  4858. getLogger().log(
  4859. Level.SEVERE,
  4860. "Error rendering cell in column "
  4861. + cell.getColumn(), e);
  4862. }
  4863. }
  4864. }
  4865. @Override
  4866. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  4867. for (FlyweightCell cell : cellsToDetach) {
  4868. Renderer<?> renderer = findRenderer(cell);
  4869. if (renderer instanceof WidgetRenderer) {
  4870. try {
  4871. Widget w = WidgetUtil.findWidget(cell.getElement()
  4872. .getFirstChildElement(), null);
  4873. if (w != null) {
  4874. // Logical detach
  4875. setParent(w, null);
  4876. // Physical detach
  4877. cell.getElement().removeChild(w.getElement());
  4878. }
  4879. } catch (RuntimeException e) {
  4880. getLogger().log(
  4881. Level.SEVERE,
  4882. "Error detaching widget in column "
  4883. + cell.getColumn(), e);
  4884. }
  4885. }
  4886. }
  4887. }
  4888. @Override
  4889. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  4890. int rowIndex = row.getRow();
  4891. // Passing null row data since it might not exist in the data source
  4892. // any more
  4893. rowReference.set(rowIndex, null, row.getElement());
  4894. for (FlyweightCell cell : detachedCells) {
  4895. Renderer<?> renderer = findRenderer(cell);
  4896. if (renderer instanceof ComplexRenderer) {
  4897. try {
  4898. Column<?, T> column = getVisibleColumn(cell.getColumn());
  4899. rendererCellReference.set(cell,
  4900. getColumns().indexOf(column), column);
  4901. ((ComplexRenderer) renderer)
  4902. .destroy(rendererCellReference);
  4903. } catch (RuntimeException e) {
  4904. getLogger().log(
  4905. Level.SEVERE,
  4906. "Error destroying cell in column "
  4907. + cell.getColumn(), e);
  4908. }
  4909. }
  4910. }
  4911. }
  4912. }
  4913. protected class StaticSectionUpdater implements EscalatorUpdater {
  4914. private StaticSection<?> section;
  4915. private RowContainer container;
  4916. public StaticSectionUpdater(StaticSection<?> section,
  4917. RowContainer container) {
  4918. super();
  4919. this.section = section;
  4920. this.container = container;
  4921. }
  4922. @Override
  4923. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  4924. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  4925. final List<Column<?, T>> columns = getVisibleColumns();
  4926. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  4927. for (FlyweightCell cell : cellsToUpdate) {
  4928. final StaticSection.StaticCell metadata = staticRow
  4929. .getCell(columns.get(cell.getColumn()));
  4930. // Decorate default row with sorting indicators
  4931. if (staticRow instanceof HeaderRow) {
  4932. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow, cell);
  4933. }
  4934. // Assign colspan to cell before rendering
  4935. cell.setColSpan(metadata.getColspan());
  4936. Element td = cell.getElement();
  4937. td.removeAllChildren();
  4938. setCustomStyleName(td, metadata.getStyleName());
  4939. Element content;
  4940. // Wrap text or html content in default header to isolate
  4941. // the content from the possible column resize drag handle
  4942. // next to it
  4943. if (metadata.getType() != GridStaticCellType.WIDGET) {
  4944. content = DOM.createDiv();
  4945. if (staticRow instanceof HeaderRow) {
  4946. content.setClassName(getStylePrimaryName()
  4947. + "-column-header-content");
  4948. if (((HeaderRow) staticRow).isDefault()) {
  4949. content.setClassName(content.getClassName() + " "
  4950. + getStylePrimaryName()
  4951. + "-column-default-header-content");
  4952. }
  4953. } else if (staticRow instanceof FooterRow) {
  4954. content.setClassName(getStylePrimaryName()
  4955. + "-column-footer-content");
  4956. } else {
  4957. getLogger().severe(
  4958. "Unhandled static row type "
  4959. + staticRow.getClass()
  4960. .getCanonicalName());
  4961. }
  4962. td.appendChild(content);
  4963. } else {
  4964. content = td;
  4965. }
  4966. switch (metadata.getType()) {
  4967. case TEXT:
  4968. content.setInnerText(metadata.getText());
  4969. break;
  4970. case HTML:
  4971. content.setInnerHTML(metadata.getHtml());
  4972. break;
  4973. case WIDGET:
  4974. preDetach(row, Arrays.asList(cell));
  4975. content.setInnerHTML("");
  4976. postAttach(row, Arrays.asList(cell));
  4977. break;
  4978. }
  4979. // XXX: Should add only once in preAttach/postAttach or when
  4980. // resizable status changes
  4981. // Only add resize handles to default header row for now
  4982. if (columns.get(cell.getColumn()).isResizable()
  4983. && staticRow instanceof HeaderRow
  4984. && ((HeaderRow) staticRow).isDefault()) {
  4985. final int column = cell.getColumn();
  4986. DragHandle dragger = new DragHandle(getStylePrimaryName()
  4987. + "-column-resize-handle",
  4988. new DragHandleCallback() {
  4989. private Column<?, T> col = getVisibleColumn(column);
  4990. private double initialWidth = 0;
  4991. private double minCellWidth;
  4992. @Override
  4993. public void onUpdate(double deltaX,
  4994. double deltaY) {
  4995. col.setWidth(Math.max(minCellWidth,
  4996. initialWidth + deltaX));
  4997. }
  4998. @Override
  4999. public void onStart() {
  5000. initialWidth = col.getWidthActual();
  5001. minCellWidth = escalator
  5002. .getMinCellWidth(getColumns()
  5003. .indexOf(col));
  5004. for (Column<?, T> c : getColumns()) {
  5005. if (selectionColumn == c) {
  5006. // Don't modify selection column.
  5007. continue;
  5008. }
  5009. if (c.getWidth() < 0) {
  5010. c.setWidth(c.getWidthActual());
  5011. fireEvent(new ColumnResizeEvent<T>(
  5012. c));
  5013. }
  5014. }
  5015. WidgetUtil.setTextSelectionEnabled(
  5016. getElement(), false);
  5017. }
  5018. @Override
  5019. public void onComplete() {
  5020. fireEvent(new ColumnResizeEvent<T>(col));
  5021. WidgetUtil.setTextSelectionEnabled(
  5022. getElement(), true);
  5023. }
  5024. @Override
  5025. public void onCancel() {
  5026. col.setWidth(initialWidth);
  5027. WidgetUtil.setTextSelectionEnabled(
  5028. getElement(), true);
  5029. }
  5030. });
  5031. dragger.addTo(td);
  5032. }
  5033. cellFocusHandler.updateFocusedCellStyle(cell, container);
  5034. }
  5035. }
  5036. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  5037. FlyweightCell cell) {
  5038. Element cellElement = cell.getElement();
  5039. boolean sortedBefore = cellElement.hasClassName("sort-asc")
  5040. || cellElement.hasClassName("sort-desc");
  5041. cleanup(cell);
  5042. if (!headerRow.isDefault()) {
  5043. // Nothing more to do if not in the default row
  5044. return;
  5045. }
  5046. final Column<?, T> column = getVisibleColumn(cell.getColumn());
  5047. SortOrder sortingOrder = getSortOrder(column);
  5048. boolean sortable = column.isSortable();
  5049. if (sortable) {
  5050. cellElement.addClassName("sortable");
  5051. }
  5052. if (!sortable || sortingOrder == null) {
  5053. // Only apply sorting indicators to sortable header columns
  5054. return;
  5055. }
  5056. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  5057. cellElement.addClassName("sort-asc");
  5058. } else {
  5059. cellElement.addClassName("sort-desc");
  5060. }
  5061. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  5062. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  5063. // Show sort order indicator if column is
  5064. // sorted and other sorted columns also exists.
  5065. cellElement.setAttribute("sort-order",
  5066. String.valueOf(sortIndex + 1));
  5067. }
  5068. if (!sortedBefore) {
  5069. verifyColumnWidth(column);
  5070. }
  5071. }
  5072. /**
  5073. * Sort indicator requires a bit more space from the cell than normally.
  5074. * This method check that the now sorted column has enough width.
  5075. *
  5076. * @param column
  5077. * sorted column
  5078. */
  5079. private void verifyColumnWidth(Column<?, T> column) {
  5080. int colIndex = getColumns().indexOf(column);
  5081. double minWidth = escalator.getMinCellWidth(colIndex);
  5082. if (column.getWidthActual() < minWidth) {
  5083. // Fix column size
  5084. escalator.getColumnConfiguration().setColumnWidth(colIndex,
  5085. minWidth);
  5086. fireEvent(new ColumnResizeEvent<T>(column));
  5087. }
  5088. }
  5089. /**
  5090. * Finds the sort order for this column
  5091. */
  5092. private SortOrder getSortOrder(Column<?, ?> column) {
  5093. for (SortOrder order : Grid.this.getSortOrder()) {
  5094. if (order.getColumn() == column) {
  5095. return order;
  5096. }
  5097. }
  5098. return null;
  5099. }
  5100. private void cleanup(FlyweightCell cell) {
  5101. Element cellElement = cell.getElement();
  5102. cellElement.removeAttribute("sort-order");
  5103. cellElement.removeClassName("sort-desc");
  5104. cellElement.removeClassName("sort-asc");
  5105. cellElement.removeClassName("sortable");
  5106. }
  5107. @Override
  5108. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  5109. }
  5110. @Override
  5111. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  5112. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  5113. List<Column<?, T>> columns = getVisibleColumns();
  5114. for (FlyweightCell cell : attachedCells) {
  5115. StaticSection.StaticCell metadata = gridRow.getCell(columns
  5116. .get(cell.getColumn()));
  5117. /*
  5118. * If the cell contains widgets that are not currently attached
  5119. * then attach them now.
  5120. */
  5121. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  5122. final Widget widget = metadata.getWidget();
  5123. if (widget != null && !widget.isAttached()) {
  5124. getGrid().attachWidget(metadata.getWidget(),
  5125. cell.getElement());
  5126. }
  5127. }
  5128. }
  5129. }
  5130. @Override
  5131. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  5132. if (section.getRowCount() > row.getRow()) {
  5133. StaticSection.StaticRow<?> gridRow = section.getRow(row
  5134. .getRow());
  5135. List<Column<?, T>> columns = getVisibleColumns();
  5136. for (FlyweightCell cell : cellsToDetach) {
  5137. StaticSection.StaticCell metadata = gridRow.getCell(columns
  5138. .get(cell.getColumn()));
  5139. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  5140. && metadata.getWidget() != null
  5141. && metadata.getWidget().isAttached()) {
  5142. getGrid().detachWidget(metadata.getWidget());
  5143. }
  5144. }
  5145. }
  5146. }
  5147. protected Grid getGrid() {
  5148. return section.grid;
  5149. }
  5150. @Override
  5151. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  5152. }
  5153. };
  5154. /**
  5155. * Creates a new instance.
  5156. */
  5157. public Grid() {
  5158. initWidget(escalator);
  5159. getElement().setTabIndex(0);
  5160. cellFocusHandler = new CellFocusHandler();
  5161. setStylePrimaryName(STYLE_NAME);
  5162. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  5163. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  5164. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  5165. header.setGrid(this);
  5166. HeaderRow defaultRow = header.appendRow();
  5167. header.setDefaultRow(defaultRow);
  5168. footer.setGrid(this);
  5169. editor.setGrid(this);
  5170. setSelectionMode(SelectionMode.SINGLE);
  5171. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  5172. escalator.addScrollHandler(new ScrollHandler() {
  5173. @Override
  5174. public void onScroll(ScrollEvent event) {
  5175. fireEvent(new ScrollEvent());
  5176. }
  5177. });
  5178. escalator
  5179. .addRowVisibilityChangeHandler(new RowVisibilityChangeHandler() {
  5180. @Override
  5181. public void onRowVisibilityChange(
  5182. RowVisibilityChangeEvent event) {
  5183. if (dataSource != null && dataSource.size() != 0) {
  5184. dataIsBeingFetched = true;
  5185. dataSource.ensureAvailability(
  5186. event.getFirstVisibleRow(),
  5187. event.getVisibleRowCount());
  5188. }
  5189. }
  5190. });
  5191. // Default action on SelectionEvents. Refresh the body so changed
  5192. // become visible.
  5193. addSelectionHandler(new SelectionHandler<T>() {
  5194. @Override
  5195. public void onSelect(SelectionEvent<T> event) {
  5196. refreshBody();
  5197. }
  5198. });
  5199. // Sink header events and key events
  5200. sinkEvents(getHeader().getConsumedEvents());
  5201. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  5202. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK,
  5203. BrowserEvents.MOUSEDOWN, BrowserEvents.CLICK));
  5204. // Make ENTER and SHIFT+ENTER in the header perform sorting
  5205. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  5206. @Override
  5207. public void onKeyUp(GridKeyUpEvent event) {
  5208. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  5209. return;
  5210. }
  5211. if (getHeader().getRow(event.getFocusedCell().getRowIndex())
  5212. .isDefault()) {
  5213. // Only sort for enter on the default header
  5214. sorter.sort(event.getFocusedCell().getColumn(),
  5215. event.isShiftKeyDown());
  5216. }
  5217. }
  5218. });
  5219. addDataAvailableHandler(new DataAvailableHandler() {
  5220. @Override
  5221. public void onDataAvailable(DataAvailableEvent event) {
  5222. dataIsBeingFetched = false;
  5223. }
  5224. });
  5225. }
  5226. @Override
  5227. public boolean isEnabled() {
  5228. return enabled;
  5229. }
  5230. @Override
  5231. public void setEnabled(boolean enabled) {
  5232. if (enabled == this.enabled) {
  5233. return;
  5234. }
  5235. this.enabled = enabled;
  5236. getElement().setTabIndex(enabled ? 0 : -1);
  5237. // Editor save and cancel buttons need to be disabled.
  5238. boolean editorOpen = editor.getState() != State.INACTIVE;
  5239. if (editorOpen) {
  5240. editor.setGridEnabled(enabled);
  5241. }
  5242. sidebar.setEnabled(enabled);
  5243. getEscalator().setScrollLocked(Direction.VERTICAL,
  5244. !enabled || editorOpen);
  5245. getEscalator().setScrollLocked(Direction.HORIZONTAL, !enabled);
  5246. fireEvent(new GridEnabledEvent(enabled));
  5247. }
  5248. @Override
  5249. public void setStylePrimaryName(String style) {
  5250. super.setStylePrimaryName(style);
  5251. escalator.setStylePrimaryName(style);
  5252. editor.setStylePrimaryName(style);
  5253. sidebar.setStylePrimaryName(style + "-sidebar");
  5254. sidebar.addStyleName("v-contextmenu");
  5255. String rowStyle = getStylePrimaryName() + "-row";
  5256. rowHasDataStyleName = rowStyle + "-has-data";
  5257. rowSelectedStyleName = rowStyle + "-selected";
  5258. rowStripeStyleName = rowStyle + "-stripe";
  5259. cellFocusStyleName = getStylePrimaryName() + "-cell-focused";
  5260. rowFocusStyleName = getStylePrimaryName() + "-row-focused";
  5261. if (isAttached()) {
  5262. refreshHeader();
  5263. refreshBody();
  5264. refreshFooter();
  5265. }
  5266. }
  5267. /**
  5268. * Creates the escalator updater used to update the header rows in this
  5269. * grid. The updater is invoked when header rows or columns are added or
  5270. * removed, or the content of existing header cells is changed.
  5271. *
  5272. * @return the new header updater instance
  5273. *
  5274. * @see GridHeader
  5275. * @see Grid#getHeader()
  5276. */
  5277. protected EscalatorUpdater createHeaderUpdater() {
  5278. return new StaticSectionUpdater(header, escalator.getHeader());
  5279. }
  5280. /**
  5281. * Creates the escalator updater used to update the body rows in this grid.
  5282. * The updater is invoked when body rows or columns are added or removed,
  5283. * the content of body cells is changed, or the body is scrolled to expose
  5284. * previously hidden content.
  5285. *
  5286. * @return the new body updater instance
  5287. */
  5288. protected EscalatorUpdater createBodyUpdater() {
  5289. return new BodyUpdater();
  5290. }
  5291. /**
  5292. * Creates the escalator updater used to update the footer rows in this
  5293. * grid. The updater is invoked when header rows or columns are added or
  5294. * removed, or the content of existing header cells is changed.
  5295. *
  5296. * @return the new footer updater instance
  5297. *
  5298. * @see GridFooter
  5299. * @see #getFooter()
  5300. */
  5301. protected EscalatorUpdater createFooterUpdater() {
  5302. return new StaticSectionUpdater(footer, escalator.getFooter());
  5303. }
  5304. /**
  5305. * Refreshes header or footer rows on demand
  5306. *
  5307. * @param rows
  5308. * The row container
  5309. * @param firstRowIsVisible
  5310. * is the first row visible
  5311. * @param isHeader
  5312. * <code>true</code> if we refreshing the header, else assumed
  5313. * the footer
  5314. */
  5315. private void refreshRowContainer(RowContainer rows, StaticSection<?> section) {
  5316. // Add or Remove rows on demand
  5317. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  5318. if (rowDiff > 0) {
  5319. rows.insertRows(0, rowDiff);
  5320. } else if (rowDiff < 0) {
  5321. rows.removeRows(0, -rowDiff);
  5322. }
  5323. // Refresh all the rows
  5324. if (rows.getRowCount() > 0) {
  5325. rows.refreshRows(0, rows.getRowCount());
  5326. }
  5327. }
  5328. /**
  5329. * Focus a body cell by row and column index.
  5330. *
  5331. * @param rowIndex
  5332. * index of row to focus
  5333. * @param columnIndex
  5334. * index of cell to focus
  5335. */
  5336. void focusCell(int rowIndex, int columnIndex) {
  5337. final Range rowRange = Range.between(0, dataSource.size());
  5338. final Range columnRange = Range.between(0, getVisibleColumns().size());
  5339. assert rowRange.contains(rowIndex) : "Illegal row index. Should be in range "
  5340. + rowRange;
  5341. assert columnRange.contains(columnIndex) : "Illegal column index. Should be in range "
  5342. + columnRange;
  5343. if (rowRange.contains(rowIndex) && columnRange.contains(columnIndex)) {
  5344. cellFocusHandler.setCellFocus(rowIndex, columnIndex,
  5345. escalator.getBody());
  5346. WidgetUtil.focus(getElement());
  5347. }
  5348. }
  5349. /**
  5350. * Refreshes all header rows
  5351. */
  5352. void refreshHeader() {
  5353. refreshRowContainer(escalator.getHeader(), header);
  5354. }
  5355. /**
  5356. * Refreshes all body rows
  5357. */
  5358. private void refreshBody() {
  5359. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  5360. }
  5361. /**
  5362. * Refreshes all footer rows
  5363. */
  5364. void refreshFooter() {
  5365. refreshRowContainer(escalator.getFooter(), footer);
  5366. }
  5367. /**
  5368. * Adds columns as the last columns in the grid.
  5369. *
  5370. * @param columns
  5371. * the columns to add
  5372. */
  5373. public void addColumns(Column<?, T>... columns) {
  5374. int count = getColumnCount();
  5375. for (Column<?, T> column : columns) {
  5376. addColumn(column, count++);
  5377. }
  5378. }
  5379. /**
  5380. * Adds a column as the last column in the grid.
  5381. *
  5382. * @param column
  5383. * the column to add
  5384. * @return given column
  5385. */
  5386. public <C extends Column<?, T>> C addColumn(C column) {
  5387. addColumn(column, getColumnCount());
  5388. return column;
  5389. }
  5390. /**
  5391. * Inserts a column into a specific position in the grid.
  5392. *
  5393. * @param index
  5394. * the index where the column should be inserted into
  5395. * @param column
  5396. * the column to add
  5397. * @return given column
  5398. *
  5399. * @throws IllegalStateException
  5400. * if Grid's current selection model renders a selection column,
  5401. * and {@code index} is 0.
  5402. */
  5403. public <C extends Column<?, T>> C addColumn(C column, int index) {
  5404. if (column == selectionColumn) {
  5405. throw new IllegalArgumentException("The selection column many "
  5406. + "not be added manually");
  5407. } else if (selectionColumn != null && index == 0) {
  5408. throw new IllegalStateException("A column cannot be inserted "
  5409. + "before the selection column");
  5410. }
  5411. addColumnSkipSelectionColumnCheck(column, index);
  5412. return column;
  5413. }
  5414. private void addColumnSkipSelectionColumnCheck(Column<?, T> column,
  5415. int index) {
  5416. // Register column with grid
  5417. columns.add(index, column);
  5418. header.addColumn(column);
  5419. footer.addColumn(column);
  5420. // Register this grid instance with the column
  5421. ((Column<?, T>) column).setGrid(this);
  5422. // Grid knows about hidden columns, Escalator only knows about what is
  5423. // visible so column indexes do not match
  5424. if (!column.isHidden()) {
  5425. int escalatorIndex = index;
  5426. for (int existingColumn = 0; existingColumn < index; existingColumn++) {
  5427. if (getColumn(existingColumn).isHidden()) {
  5428. escalatorIndex--;
  5429. }
  5430. }
  5431. escalator.getColumnConfiguration().insertColumns(escalatorIndex, 1);
  5432. }
  5433. // Reapply column width
  5434. column.reapplyWidth();
  5435. // Sink all renderer events
  5436. Set<String> events = new HashSet<String>();
  5437. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  5438. if (column.isHidable()) {
  5439. columnHider.updateColumnHidable(column);
  5440. }
  5441. sinkEvents(events);
  5442. }
  5443. private void sinkEvents(Collection<String> events) {
  5444. assert events != null;
  5445. int eventsToSink = 0;
  5446. for (String typeName : events) {
  5447. int typeInt = Event.getTypeInt(typeName);
  5448. if (typeInt < 0) {
  5449. // Type not recognized by typeInt
  5450. sinkBitlessEvent(typeName);
  5451. } else {
  5452. eventsToSink |= typeInt;
  5453. }
  5454. }
  5455. if (eventsToSink > 0) {
  5456. sinkEvents(eventsToSink);
  5457. }
  5458. }
  5459. private Renderer<?> findRenderer(FlyweightCell cell) {
  5460. Column<?, T> column = getVisibleColumn(cell.getColumn());
  5461. assert column != null : "Could not find column at index:"
  5462. + cell.getColumn();
  5463. return column.getRenderer();
  5464. }
  5465. /**
  5466. * Removes a column from the grid.
  5467. *
  5468. * @param column
  5469. * the column to remove
  5470. */
  5471. public void removeColumn(Column<?, T> column) {
  5472. if (column != null && column.equals(selectionColumn)) {
  5473. throw new IllegalArgumentException(
  5474. "The selection column may not be removed manually.");
  5475. }
  5476. removeColumnSkipSelectionColumnCheck(column);
  5477. }
  5478. private void removeColumnSkipSelectionColumnCheck(Column<?, T> column) {
  5479. int columnIndex = columns.indexOf(column);
  5480. // Remove from column configuration
  5481. escalator.getColumnConfiguration().removeColumns(
  5482. getVisibleColumns().indexOf(column), 1);
  5483. updateFrozenColumns();
  5484. header.removeColumn(column);
  5485. footer.removeColumn(column);
  5486. // de-register column with grid
  5487. ((Column<?, T>) column).setGrid(null);
  5488. columns.remove(columnIndex);
  5489. if (column.isHidable()) {
  5490. columnHider.removeColumnHidingToggle(column);
  5491. }
  5492. }
  5493. /**
  5494. * Returns the amount of columns in the grid.
  5495. * <p>
  5496. * <em>NOTE:</em> this includes the hidden columns in the count.
  5497. *
  5498. * @return The number of columns in the grid
  5499. */
  5500. public int getColumnCount() {
  5501. return columns.size();
  5502. }
  5503. /**
  5504. * Returns a list columns in the grid, including hidden columns.
  5505. * <p>
  5506. * For currently visible columns, use {@link #getVisibleColumns()}.
  5507. *
  5508. * @return A unmodifiable list of the columns in the grid
  5509. */
  5510. public List<Column<?, T>> getColumns() {
  5511. return Collections
  5512. .unmodifiableList(new ArrayList<Column<?, T>>(columns));
  5513. }
  5514. /**
  5515. * Returns a list of the currently visible columns in the grid.
  5516. * <p>
  5517. * No {@link Column#isHidden() hidden} columns included.
  5518. *
  5519. * @since 7.5.0
  5520. * @return A unmodifiable list of the currently visible columns in the grid
  5521. */
  5522. public List<Column<?, T>> getVisibleColumns() {
  5523. ArrayList<Column<?, T>> visible = new ArrayList<Column<?, T>>();
  5524. for (Column<?, T> c : columns) {
  5525. if (!c.isHidden()) {
  5526. visible.add(c);
  5527. }
  5528. }
  5529. return Collections.unmodifiableList(visible);
  5530. }
  5531. /**
  5532. * Returns a column by its index in the grid.
  5533. * <p>
  5534. * <em>NOTE:</em> The indexing includes hidden columns.
  5535. *
  5536. * @param index
  5537. * the index of the column
  5538. * @return The column in the given index
  5539. * @throws IllegalArgumentException
  5540. * if the column index does not exist in the grid
  5541. */
  5542. public Column<?, T> getColumn(int index) throws IllegalArgumentException {
  5543. if (index < 0 || index >= columns.size()) {
  5544. throw new IllegalStateException("Column not found.");
  5545. }
  5546. return columns.get(index);
  5547. }
  5548. private Column<?, T> getVisibleColumn(int index)
  5549. throws IllegalArgumentException {
  5550. List<Column<?, T>> visibleColumns = getVisibleColumns();
  5551. if (index < 0 || index >= visibleColumns.size()) {
  5552. throw new IllegalStateException("Column not found.");
  5553. }
  5554. return visibleColumns.get(index);
  5555. }
  5556. /**
  5557. * Returns the header section of this grid. The default header contains a
  5558. * single row displaying the column captions.
  5559. *
  5560. * @return the header
  5561. */
  5562. protected Header getHeader() {
  5563. return header;
  5564. }
  5565. /**
  5566. * Gets the header row at given index.
  5567. *
  5568. * @param rowIndex
  5569. * 0 based index for row. Counted from top to bottom
  5570. * @return header row at given index
  5571. * @throws IllegalArgumentException
  5572. * if no row exists at given index
  5573. */
  5574. public HeaderRow getHeaderRow(int rowIndex) {
  5575. return header.getRow(rowIndex);
  5576. }
  5577. /**
  5578. * Inserts a new row at the given position to the header section. Shifts the
  5579. * row currently at that position and any subsequent rows down (adds one to
  5580. * their indices).
  5581. *
  5582. * @param index
  5583. * the position at which to insert the row
  5584. * @return the new row
  5585. *
  5586. * @throws IllegalArgumentException
  5587. * if the index is less than 0 or greater than row count
  5588. * @see #appendHeaderRow()
  5589. * @see #prependHeaderRow()
  5590. * @see #removeHeaderRow(HeaderRow)
  5591. * @see #removeHeaderRow(int)
  5592. */
  5593. public HeaderRow addHeaderRowAt(int index) {
  5594. return header.addRowAt(index);
  5595. }
  5596. /**
  5597. * Adds a new row at the bottom of the header section.
  5598. *
  5599. * @return the new row
  5600. * @see #prependHeaderRow()
  5601. * @see #addHeaderRowAt(int)
  5602. * @see #removeHeaderRow(HeaderRow)
  5603. * @see #removeHeaderRow(int)
  5604. */
  5605. public HeaderRow appendHeaderRow() {
  5606. return header.appendRow();
  5607. }
  5608. /**
  5609. * Returns the current default row of the header section. The default row is
  5610. * a special header row providing a user interface for sorting columns.
  5611. * Setting a header caption for column updates cells in the default header.
  5612. *
  5613. * @return the default row or null if no default row set
  5614. */
  5615. public HeaderRow getDefaultHeaderRow() {
  5616. return header.getDefaultRow();
  5617. }
  5618. /**
  5619. * Gets the row count for the header section.
  5620. *
  5621. * @return row count
  5622. */
  5623. public int getHeaderRowCount() {
  5624. return header.getRowCount();
  5625. }
  5626. /**
  5627. * Adds a new row at the top of the header section.
  5628. *
  5629. * @return the new row
  5630. * @see #appendHeaderRow()
  5631. * @see #addHeaderRowAt(int)
  5632. * @see #removeHeaderRow(HeaderRow)
  5633. * @see #removeHeaderRow(int)
  5634. */
  5635. public HeaderRow prependHeaderRow() {
  5636. return header.prependRow();
  5637. }
  5638. /**
  5639. * Removes the given row from the header section.
  5640. *
  5641. * @param row
  5642. * the row to be removed
  5643. *
  5644. * @throws IllegalArgumentException
  5645. * if the row does not exist in this section
  5646. * @see #removeHeaderRow(int)
  5647. * @see #addHeaderRowAt(int)
  5648. * @see #appendHeaderRow()
  5649. * @see #prependHeaderRow()
  5650. */
  5651. public void removeHeaderRow(HeaderRow row) {
  5652. header.removeRow(row);
  5653. }
  5654. /**
  5655. * Removes the row at the given position from the header section.
  5656. *
  5657. * @param index
  5658. * the position of the row
  5659. *
  5660. * @throws IllegalArgumentException
  5661. * if no row exists at given index
  5662. * @see #removeHeaderRow(HeaderRow)
  5663. * @see #addHeaderRowAt(int)
  5664. * @see #appendHeaderRow()
  5665. * @see #prependHeaderRow()
  5666. */
  5667. public void removeHeaderRow(int rowIndex) {
  5668. header.removeRow(rowIndex);
  5669. }
  5670. /**
  5671. * Sets the default row of the header. The default row is a special header
  5672. * row providing a user interface for sorting columns.
  5673. * <p>
  5674. * Note: Setting the default header row will reset all cell contents to
  5675. * Column defaults.
  5676. *
  5677. * @param row
  5678. * the new default row, or null for no default row
  5679. *
  5680. * @throws IllegalArgumentException
  5681. * header does not contain the row
  5682. */
  5683. public void setDefaultHeaderRow(HeaderRow row) {
  5684. header.setDefaultRow(row);
  5685. }
  5686. /**
  5687. * Sets the visibility of the header section.
  5688. *
  5689. * @param visible
  5690. * true to show header section, false to hide
  5691. */
  5692. public void setHeaderVisible(boolean visible) {
  5693. header.setVisible(visible);
  5694. }
  5695. /**
  5696. * Returns the visibility of the header section.
  5697. *
  5698. * @return true if visible, false otherwise.
  5699. */
  5700. public boolean isHeaderVisible() {
  5701. return header.isVisible();
  5702. }
  5703. /* Grid Footers */
  5704. /**
  5705. * Returns the footer section of this grid. The default footer is empty.
  5706. *
  5707. * @return the footer
  5708. */
  5709. protected Footer getFooter() {
  5710. return footer;
  5711. }
  5712. /**
  5713. * Gets the footer row at given index.
  5714. *
  5715. * @param rowIndex
  5716. * 0 based index for row. Counted from top to bottom
  5717. * @return footer row at given index
  5718. * @throws IllegalArgumentException
  5719. * if no row exists at given index
  5720. */
  5721. public FooterRow getFooterRow(int rowIndex) {
  5722. return footer.getRow(rowIndex);
  5723. }
  5724. /**
  5725. * Inserts a new row at the given position to the footer section. Shifts the
  5726. * row currently at that position and any subsequent rows down (adds one to
  5727. * their indices).
  5728. *
  5729. * @param index
  5730. * the position at which to insert the row
  5731. * @return the new row
  5732. *
  5733. * @throws IllegalArgumentException
  5734. * if the index is less than 0 or greater than row count
  5735. * @see #appendFooterRow()
  5736. * @see #prependFooterRow()
  5737. * @see #removeFooterRow(FooterRow)
  5738. * @see #removeFooterRow(int)
  5739. */
  5740. public FooterRow addFooterRowAt(int index) {
  5741. return footer.addRowAt(index);
  5742. }
  5743. /**
  5744. * Adds a new row at the bottom of the footer section.
  5745. *
  5746. * @return the new row
  5747. * @see #prependFooterRow()
  5748. * @see #addFooterRowAt(int)
  5749. * @see #removeFooterRow(FooterRow)
  5750. * @see #removeFooterRow(int)
  5751. */
  5752. public FooterRow appendFooterRow() {
  5753. return footer.appendRow();
  5754. }
  5755. /**
  5756. * Gets the row count for the footer.
  5757. *
  5758. * @return row count
  5759. */
  5760. public int getFooterRowCount() {
  5761. return footer.getRowCount();
  5762. }
  5763. /**
  5764. * Adds a new row at the top of the footer section.
  5765. *
  5766. * @return the new row
  5767. * @see #appendFooterRow()
  5768. * @see #addFooterRowAt(int)
  5769. * @see #removeFooterRow(FooterRow)
  5770. * @see #removeFooterRow(int)
  5771. */
  5772. public FooterRow prependFooterRow() {
  5773. return footer.prependRow();
  5774. }
  5775. /**
  5776. * Removes the given row from the footer section.
  5777. *
  5778. * @param row
  5779. * the row to be removed
  5780. *
  5781. * @throws IllegalArgumentException
  5782. * if the row does not exist in this section
  5783. * @see #removeFooterRow(int)
  5784. * @see #addFooterRowAt(int)
  5785. * @see #appendFooterRow()
  5786. * @see #prependFooterRow()
  5787. */
  5788. public void removeFooterRow(FooterRow row) {
  5789. footer.removeRow(row);
  5790. }
  5791. /**
  5792. * Removes the row at the given position from the footer section.
  5793. *
  5794. * @param index
  5795. * the position of the row
  5796. *
  5797. * @throws IllegalArgumentException
  5798. * if no row exists at given index
  5799. * @see #removeFooterRow(FooterRow)
  5800. * @see #addFooterRowAt(int)
  5801. * @see #appendFooterRow()
  5802. * @see #prependFooterRow()
  5803. */
  5804. public void removeFooterRow(int rowIndex) {
  5805. footer.removeRow(rowIndex);
  5806. }
  5807. /**
  5808. * Sets the visibility of the footer section.
  5809. *
  5810. * @param visible
  5811. * true to show footer section, false to hide
  5812. */
  5813. public void setFooterVisible(boolean visible) {
  5814. footer.setVisible(visible);
  5815. }
  5816. /**
  5817. * Returns the visibility of the footer section.
  5818. *
  5819. * @return true if visible, false otherwise.
  5820. */
  5821. public boolean isFooterVisible() {
  5822. return footer.isVisible();
  5823. }
  5824. public Editor<T> getEditor() {
  5825. return editor;
  5826. }
  5827. protected Escalator getEscalator() {
  5828. return escalator;
  5829. }
  5830. /**
  5831. * {@inheritDoc}
  5832. * <p>
  5833. * <em>Note:</em> This method will change the widget's size in the browser
  5834. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  5835. *
  5836. * @see #setHeightMode(HeightMode)
  5837. */
  5838. @Override
  5839. public void setHeight(String height) {
  5840. escalator.setHeight(height);
  5841. }
  5842. @Override
  5843. public void setWidth(String width) {
  5844. escalator.setWidth(width);
  5845. }
  5846. /**
  5847. * Sets the data source used by this grid.
  5848. *
  5849. * @param dataSource
  5850. * the data source to use, not null
  5851. * @throws IllegalArgumentException
  5852. * if <code>dataSource</code> is <code>null</code>
  5853. */
  5854. public void setDataSource(final DataSource<T> dataSource)
  5855. throws IllegalArgumentException {
  5856. if (dataSource == null) {
  5857. throw new IllegalArgumentException("dataSource can't be null.");
  5858. }
  5859. selectionModel.reset();
  5860. if (this.dataSource != null) {
  5861. this.dataSource.setDataChangeHandler(null);
  5862. }
  5863. this.dataSource = dataSource;
  5864. dataSource.setDataChangeHandler(new DataChangeHandler() {
  5865. @Override
  5866. public void dataUpdated(int firstIndex, int numberOfItems) {
  5867. escalator.getBody().refreshRows(firstIndex, numberOfItems);
  5868. }
  5869. @Override
  5870. public void dataRemoved(int firstIndex, int numberOfItems) {
  5871. escalator.getBody().removeRows(firstIndex, numberOfItems);
  5872. Range removed = Range.withLength(firstIndex, numberOfItems);
  5873. cellFocusHandler.rowsRemovedFromBody(removed);
  5874. }
  5875. @Override
  5876. public void dataAdded(int firstIndex, int numberOfItems) {
  5877. escalator.getBody().insertRows(firstIndex, numberOfItems);
  5878. Range added = Range.withLength(firstIndex, numberOfItems);
  5879. cellFocusHandler.rowsAddedToBody(added);
  5880. }
  5881. @Override
  5882. public void dataAvailable(int firstIndex, int numberOfItems) {
  5883. currentDataAvailable = Range.withLength(firstIndex,
  5884. numberOfItems);
  5885. fireEvent(new DataAvailableEvent(currentDataAvailable));
  5886. }
  5887. @Override
  5888. public void resetDataAndSize(int newSize) {
  5889. RowContainer body = escalator.getBody();
  5890. int oldSize = body.getRowCount();
  5891. // Hide all details.
  5892. Set<Integer> oldDetails = new HashSet<Integer>(visibleDetails);
  5893. for (int i : oldDetails) {
  5894. setDetailsVisible(i, false);
  5895. }
  5896. if (newSize > oldSize) {
  5897. body.insertRows(oldSize, newSize - oldSize);
  5898. cellFocusHandler.rowsAddedToBody(Range.withLength(oldSize,
  5899. newSize - oldSize));
  5900. } else if (newSize < oldSize) {
  5901. body.removeRows(newSize, oldSize - newSize);
  5902. cellFocusHandler.rowsRemovedFromBody(Range.withLength(
  5903. newSize, oldSize - newSize));
  5904. }
  5905. if (newSize > 0) {
  5906. dataIsBeingFetched = true;
  5907. Range visibleRowRange = escalator.getVisibleRowRange();
  5908. dataSource.ensureAvailability(visibleRowRange.getStart(),
  5909. visibleRowRange.length());
  5910. } else {
  5911. // We won't expect any data more data updates, so just make
  5912. // the bookkeeping happy
  5913. dataAvailable(0, 0);
  5914. }
  5915. assert body.getRowCount() == newSize;
  5916. }
  5917. });
  5918. int previousRowCount = escalator.getBody().getRowCount();
  5919. if (previousRowCount != 0) {
  5920. escalator.getBody().removeRows(0, previousRowCount);
  5921. }
  5922. setEscalatorSizeFromDataSource();
  5923. }
  5924. private void setEscalatorSizeFromDataSource() {
  5925. assert escalator.getBody().getRowCount() == 0;
  5926. int size = dataSource.size();
  5927. if (size == -1 && isAttached()) {
  5928. // Exact size is not yet known, start with some reasonable guess
  5929. // just to get an initial backend request going
  5930. size = getEscalator().getMaxVisibleRowCount();
  5931. }
  5932. if (size > 0) {
  5933. escalator.getBody().insertRows(0, size);
  5934. }
  5935. }
  5936. /**
  5937. * Gets the {@Link DataSource} for this Grid.
  5938. *
  5939. * @return the data source used by this grid
  5940. */
  5941. public DataSource<T> getDataSource() {
  5942. return dataSource;
  5943. }
  5944. /**
  5945. * Sets the number of frozen columns in this grid. Setting the count to 0
  5946. * means that no data columns will be frozen, but the built-in selection
  5947. * checkbox column will still be frozen if it's in use. Setting the count to
  5948. * -1 will also disable the selection column.
  5949. * <p>
  5950. * The default value is 0.
  5951. *
  5952. * @param numberOfColumns
  5953. * the number of columns that should be frozen
  5954. *
  5955. * @throws IllegalArgumentException
  5956. * if the column count is < -1 or > the number of visible
  5957. * columns
  5958. */
  5959. public void setFrozenColumnCount(int numberOfColumns) {
  5960. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  5961. throw new IllegalArgumentException(
  5962. "count must be between -1 and the current number of columns ("
  5963. + getColumnCount() + ")");
  5964. }
  5965. frozenColumnCount = numberOfColumns;
  5966. updateFrozenColumns();
  5967. }
  5968. private void updateFrozenColumns() {
  5969. escalator.getColumnConfiguration().setFrozenColumnCount(
  5970. getVisibleFrozenColumnCount());
  5971. }
  5972. private int getVisibleFrozenColumnCount() {
  5973. int numberOfColumns = getFrozenColumnCount();
  5974. // for the escalator the hidden columns are not in the frozen column
  5975. // count, but for grid they are. thus need to convert the index
  5976. for (int i = 0; i < frozenColumnCount; i++) {
  5977. if (getColumn(i).isHidden()) {
  5978. numberOfColumns--;
  5979. }
  5980. }
  5981. if (numberOfColumns == -1) {
  5982. numberOfColumns = 0;
  5983. } else if (selectionColumn != null) {
  5984. numberOfColumns++;
  5985. }
  5986. return numberOfColumns;
  5987. }
  5988. /**
  5989. * Gets the number of frozen columns in this grid. 0 means that no data
  5990. * columns will be frozen, but the built-in selection checkbox column will
  5991. * still be frozen if it's in use. -1 means that not even the selection
  5992. * column is frozen.
  5993. * <p>
  5994. * <em>NOTE:</em> This includes {@link Column#isHidden() hidden columns} in
  5995. * the count.
  5996. *
  5997. * @return the number of frozen columns
  5998. */
  5999. public int getFrozenColumnCount() {
  6000. return frozenColumnCount;
  6001. }
  6002. public HandlerRegistration addRowVisibilityChangeHandler(
  6003. RowVisibilityChangeHandler handler) {
  6004. /*
  6005. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  6006. * concept is too abstract. e.g. the event needs to be re-sent when the
  6007. * widget is resized.
  6008. */
  6009. return escalator.addRowVisibilityChangeHandler(handler);
  6010. }
  6011. /**
  6012. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  6013. * <p>
  6014. * If the details for that row are visible, those will be taken into account
  6015. * as well.
  6016. *
  6017. * @param rowIndex
  6018. * zero-based index of the row to scroll to.
  6019. * @throws IllegalArgumentException
  6020. * if rowIndex is below zero, or above the maximum value
  6021. * supported by the data source.
  6022. */
  6023. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  6024. scrollToRow(rowIndex, ScrollDestination.ANY,
  6025. GridConstants.DEFAULT_PADDING);
  6026. }
  6027. /**
  6028. * Scrolls to a certain row, using user-specified scroll destination.
  6029. * <p>
  6030. * If the details for that row are visible, those will be taken into account
  6031. * as well.
  6032. *
  6033. * @param rowIndex
  6034. * zero-based index of the row to scroll to.
  6035. * @param destination
  6036. * desired destination placement of scrolled-to-row. See
  6037. * {@link ScrollDestination} for more information.
  6038. * @throws IllegalArgumentException
  6039. * if rowIndex is below zero, or above the maximum value
  6040. * supported by the data source.
  6041. */
  6042. public void scrollToRow(int rowIndex, ScrollDestination destination)
  6043. throws IllegalArgumentException {
  6044. scrollToRow(rowIndex, destination,
  6045. destination == ScrollDestination.MIDDLE ? 0
  6046. : GridConstants.DEFAULT_PADDING);
  6047. }
  6048. /**
  6049. * Scrolls to a certain row using only user-specified parameters.
  6050. * <p>
  6051. * If the details for that row are visible, those will be taken into account
  6052. * as well.
  6053. *
  6054. * @param rowIndex
  6055. * zero-based index of the row to scroll to.
  6056. * @param destination
  6057. * desired destination placement of scrolled-to-row. See
  6058. * {@link ScrollDestination} for more information.
  6059. * @param paddingPx
  6060. * number of pixels to overscroll. Behavior depends on
  6061. * destination.
  6062. * @throws IllegalArgumentException
  6063. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  6064. * and padding is nonzero, because having a padding on a
  6065. * centered row is undefined behavior, or if rowIndex is below
  6066. * zero or above the row count of the data source.
  6067. */
  6068. private void scrollToRow(int rowIndex, ScrollDestination destination,
  6069. int paddingPx) throws IllegalArgumentException {
  6070. int maxsize = escalator.getBody().getRowCount() - 1;
  6071. if (rowIndex < 0) {
  6072. throw new IllegalArgumentException("Row index (" + rowIndex
  6073. + ") is below zero!");
  6074. }
  6075. if (rowIndex > maxsize) {
  6076. throw new IllegalArgumentException("Row index (" + rowIndex
  6077. + ") is above maximum (" + maxsize + ")!");
  6078. }
  6079. escalator.scrollToRowAndSpacer(rowIndex, destination, paddingPx);
  6080. }
  6081. /**
  6082. * Scrolls to the beginning of the very first row.
  6083. */
  6084. public void scrollToStart() {
  6085. scrollToRow(0, ScrollDestination.START);
  6086. }
  6087. /**
  6088. * Scrolls to the end of the very last row.
  6089. */
  6090. public void scrollToEnd() {
  6091. scrollToRow(escalator.getBody().getRowCount() - 1,
  6092. ScrollDestination.END);
  6093. }
  6094. /**
  6095. * Sets the vertical scroll offset.
  6096. *
  6097. * @param px
  6098. * the number of pixels this grid should be scrolled down
  6099. */
  6100. public void setScrollTop(double px) {
  6101. escalator.setScrollTop(px);
  6102. }
  6103. /**
  6104. * Gets the vertical scroll offset
  6105. *
  6106. * @return the number of pixels this grid is scrolled down
  6107. */
  6108. public double getScrollTop() {
  6109. return escalator.getScrollTop();
  6110. }
  6111. /**
  6112. * Sets the horizontal scroll offset
  6113. *
  6114. * @since 7.5.0
  6115. * @param px
  6116. * the number of pixels this grid should be scrolled right
  6117. */
  6118. public void setScrollLeft(double px) {
  6119. escalator.setScrollLeft(px);
  6120. }
  6121. /**
  6122. * Gets the horizontal scroll offset
  6123. *
  6124. * @return the number of pixels this grid is scrolled to the right
  6125. */
  6126. public double getScrollLeft() {
  6127. return escalator.getScrollLeft();
  6128. }
  6129. /**
  6130. * Returns the height of the scrollable area in pixels.
  6131. *
  6132. * @since 7.5.0
  6133. * @return the height of the scrollable area in pixels
  6134. */
  6135. public double getScrollHeight() {
  6136. return escalator.getScrollHeight();
  6137. }
  6138. /**
  6139. * Returns the width of the scrollable area in pixels.
  6140. *
  6141. * @since 7.5.0
  6142. * @return the width of the scrollable area in pixels.
  6143. */
  6144. public double getScrollWidth() {
  6145. return escalator.getScrollWidth();
  6146. }
  6147. private static final Logger getLogger() {
  6148. return Logger.getLogger(Grid.class.getName());
  6149. }
  6150. /**
  6151. * Sets the number of rows that should be visible in Grid's body, while
  6152. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6153. * <p>
  6154. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  6155. * remembered, and applied once the mode is applied.
  6156. *
  6157. * @param rows
  6158. * The height in terms of number of rows displayed in Grid's
  6159. * body. If Grid doesn't contain enough rows, white space is
  6160. * displayed instead.
  6161. * @throws IllegalArgumentException
  6162. * if {@code rows} is zero or less
  6163. * @throws IllegalArgumentException
  6164. * if {@code rows} is {@link Double#isInifinite(double)
  6165. * infinite}
  6166. * @throws IllegalArgumentException
  6167. * if {@code rows} is {@link Double#isNaN(double) NaN}
  6168. *
  6169. * @see #setHeightMode(HeightMode)
  6170. */
  6171. public void setHeightByRows(double rows) throws IllegalArgumentException {
  6172. escalator.setHeightByRows(rows);
  6173. }
  6174. /**
  6175. * Gets the amount of rows in Grid's body that are shown, while
  6176. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  6177. * <p>
  6178. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  6179. *
  6180. * @return the amount of rows that should be shown in Grid's body, while in
  6181. * {@link HeightMode#ROW}.
  6182. * @see #setHeightByRows(double)
  6183. */
  6184. public double getHeightByRows() {
  6185. return escalator.getHeightByRows();
  6186. }
  6187. /**
  6188. * Defines the mode in which the Grid widget's height is calculated.
  6189. * <p>
  6190. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  6191. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  6192. * <p>
  6193. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  6194. * will display as many rows as {@link #getHeightByRows()} defines.
  6195. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  6196. * will resize itself to still display the required amount of rows in its
  6197. * body. It also takes the horizontal scrollbar into account.
  6198. *
  6199. * @param heightMode
  6200. * the mode in to which Grid should be set
  6201. */
  6202. public void setHeightMode(HeightMode heightMode) {
  6203. /*
  6204. * This method is a workaround for the fact that Vaadin re-applies
  6205. * widget dimensions (height/width) on each state change event. The
  6206. * original design was to have setHeight an setHeightByRow be equals,
  6207. * and whichever was called the latest was considered in effect.
  6208. *
  6209. * But, because of Vaadin always calling setHeight on the widget, this
  6210. * approach doesn't work.
  6211. */
  6212. escalator.setHeightMode(heightMode);
  6213. }
  6214. /**
  6215. * Returns the current {@link HeightMode} the Grid is in.
  6216. * <p>
  6217. * Defaults to {@link HeightMode#CSS}.
  6218. *
  6219. * @return the current HeightMode
  6220. */
  6221. public HeightMode getHeightMode() {
  6222. return escalator.getHeightMode();
  6223. }
  6224. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  6225. Set<String> events = new HashSet<String>();
  6226. if (renderer instanceof ComplexRenderer) {
  6227. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  6228. .getConsumedEvents();
  6229. if (consumedEvents != null) {
  6230. events.addAll(consumedEvents);
  6231. }
  6232. }
  6233. return events;
  6234. }
  6235. @Override
  6236. public void onBrowserEvent(Event event) {
  6237. if (!isEnabled()) {
  6238. return;
  6239. }
  6240. String eventType = event.getType();
  6241. if (eventType.equals(BrowserEvents.FOCUS)
  6242. || eventType.equals(BrowserEvents.BLUR)) {
  6243. super.onBrowserEvent(event);
  6244. return;
  6245. }
  6246. EventTarget target = event.getEventTarget();
  6247. if (!Element.is(target) || isOrContainsInSpacer(Element.as(target))) {
  6248. return;
  6249. }
  6250. Element e = Element.as(target);
  6251. RowContainer container = escalator.findRowContainer(e);
  6252. Cell cell;
  6253. if (container == null) {
  6254. if (eventType.equals(BrowserEvents.KEYDOWN)
  6255. || eventType.equals(BrowserEvents.KEYUP)
  6256. || eventType.equals(BrowserEvents.KEYPRESS)) {
  6257. cell = cellFocusHandler.getFocusedCell();
  6258. container = cellFocusHandler.containerWithFocus;
  6259. } else {
  6260. // Click might be in an editor cell, should still map.
  6261. if (editor.editorOverlay != null
  6262. && editor.editorOverlay.isOrHasChild(e)) {
  6263. container = escalator.getBody();
  6264. int rowIndex = editor.getRow();
  6265. int colIndex = editor.getElementColumn(e);
  6266. if (colIndex < 0) {
  6267. // Click in editor, but not for any column.
  6268. return;
  6269. }
  6270. TableCellElement cellElement = container
  6271. .getRowElement(rowIndex).getCells()
  6272. .getItem(colIndex);
  6273. cell = new Cell(rowIndex, colIndex, cellElement);
  6274. } else {
  6275. if (escalator.getElement().isOrHasChild(e)) {
  6276. eventCell.set(new Cell(-1, -1, null), Section.BODY);
  6277. // Fire native events.
  6278. super.onBrowserEvent(event);
  6279. }
  6280. return;
  6281. }
  6282. }
  6283. } else {
  6284. cell = container.getCell(e);
  6285. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  6286. cellOnPrevMouseDown = cell;
  6287. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  6288. /*
  6289. * Chrome has an interesting idea on click targets (see
  6290. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  6291. * the mousedown target as the click target.
  6292. */
  6293. cell = cellOnPrevMouseDown;
  6294. }
  6295. }
  6296. assert cell != null : "received " + eventType
  6297. + "-event with a null cell target";
  6298. eventCell.set(cell, getSectionFromContainer(container));
  6299. // Editor can steal focus from Grid and is still handled
  6300. if (isEditorEnabled() && handleEditorEvent(event, container)) {
  6301. return;
  6302. }
  6303. // Fire GridKeyEvents and GridClickEvents. Pass the event to escalator.
  6304. super.onBrowserEvent(event);
  6305. if (!isElementInChildWidget(e)) {
  6306. if (handleHeaderCellDragStartEvent(event, container)) {
  6307. return;
  6308. }
  6309. // Sorting through header Click / KeyUp
  6310. if (handleHeaderDefaultRowEvent(event, container)) {
  6311. return;
  6312. }
  6313. if (handleRendererEvent(event, container)) {
  6314. return;
  6315. }
  6316. if (handleCellFocusEvent(event, container)) {
  6317. return;
  6318. }
  6319. }
  6320. }
  6321. private Section getSectionFromContainer(RowContainer container) {
  6322. assert container != null : "RowContainer should not be null";
  6323. if (container == escalator.getBody()) {
  6324. return Section.BODY;
  6325. } else if (container == escalator.getFooter()) {
  6326. return Section.FOOTER;
  6327. } else if (container == escalator.getHeader()) {
  6328. return Section.HEADER;
  6329. }
  6330. assert false : "RowContainer was not header, footer or body.";
  6331. return null;
  6332. }
  6333. private boolean isOrContainsInSpacer(Node node) {
  6334. Node n = node;
  6335. while (n != null && n != getElement()) {
  6336. boolean isElement = Element.is(n);
  6337. if (isElement) {
  6338. String className = Element.as(n).getClassName();
  6339. if (className.contains(getStylePrimaryName() + "-spacer")) {
  6340. return true;
  6341. }
  6342. }
  6343. n = n.getParentNode();
  6344. }
  6345. return false;
  6346. }
  6347. private boolean isElementInChildWidget(Element e) {
  6348. Widget w = WidgetUtil.findWidget(e, null);
  6349. if (w == this) {
  6350. return false;
  6351. }
  6352. /*
  6353. * If e is directly inside this grid, but the grid is wrapped in a
  6354. * Composite, findWidget is not going to find this, only the wrapper.
  6355. * Thus we need to check its parents to see if we encounter this; if we
  6356. * don't, the found widget is actually a parent of this, so we should
  6357. * return false.
  6358. */
  6359. while (w != null && w != this) {
  6360. w = w.getParent();
  6361. }
  6362. return w != null;
  6363. }
  6364. private boolean handleEditorEvent(Event event, RowContainer container) {
  6365. Widget w;
  6366. if (editor.focusedColumnIndex < 0) {
  6367. w = null;
  6368. } else {
  6369. w = editor.getWidget(getColumn(editor.focusedColumnIndex));
  6370. }
  6371. EditorDomEvent<T> editorEvent = new EditorDomEvent<T>(event,
  6372. getEventCell(), w);
  6373. return getEditor().getEventHandler().handleEvent(editorEvent);
  6374. }
  6375. private boolean handleRendererEvent(Event event, RowContainer container) {
  6376. if (container == escalator.getBody()) {
  6377. Column<?, T> gridColumn = eventCell.getColumn();
  6378. boolean enterKey = event.getType().equals(BrowserEvents.KEYDOWN)
  6379. && event.getKeyCode() == KeyCodes.KEY_ENTER;
  6380. boolean doubleClick = event.getType()
  6381. .equals(BrowserEvents.DBLCLICK);
  6382. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  6383. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  6384. .getRenderer();
  6385. if (cplxRenderer.getConsumedEvents().contains(event.getType())) {
  6386. if (cplxRenderer.onBrowserEvent(eventCell, event)) {
  6387. return true;
  6388. }
  6389. }
  6390. // Calls onActivate if KeyDown and Enter or double click
  6391. if ((enterKey || doubleClick)
  6392. && cplxRenderer.onActivate(eventCell)) {
  6393. return true;
  6394. }
  6395. }
  6396. }
  6397. return false;
  6398. }
  6399. private boolean handleCellFocusEvent(Event event, RowContainer container) {
  6400. Collection<String> navigation = cellFocusHandler.getNavigationEvents();
  6401. if (navigation.contains(event.getType())) {
  6402. cellFocusHandler.handleNavigationEvent(event, eventCell);
  6403. }
  6404. return false;
  6405. }
  6406. private boolean handleHeaderCellDragStartEvent(Event event,
  6407. RowContainer container) {
  6408. if (!isColumnReorderingAllowed()) {
  6409. return false;
  6410. }
  6411. if (container != escalator.getHeader()) {
  6412. return false;
  6413. }
  6414. if (eventCell.getColumnIndex() < escalator.getColumnConfiguration()
  6415. .getFrozenColumnCount()) {
  6416. return false;
  6417. }
  6418. if (event.getTypeInt() == Event.ONMOUSEDOWN
  6419. && event.getButton() == NativeEvent.BUTTON_LEFT
  6420. || event.getTypeInt() == Event.ONTOUCHSTART) {
  6421. dndHandler.onDragStartOnDraggableElement(event,
  6422. headerCellDndCallback);
  6423. event.preventDefault();
  6424. event.stopPropagation();
  6425. return true;
  6426. }
  6427. return false;
  6428. }
  6429. private Point rowEventTouchStartingPoint;
  6430. private CellStyleGenerator<T> cellStyleGenerator;
  6431. private RowStyleGenerator<T> rowStyleGenerator;
  6432. private RowReference<T> rowReference = new RowReference<T>(this);
  6433. private CellReference<T> cellReference = new CellReference<T>(rowReference);
  6434. private RendererCellReference rendererCellReference = new RendererCellReference(
  6435. (RowReference<Object>) rowReference);
  6436. private boolean handleHeaderDefaultRowEvent(Event event,
  6437. RowContainer container) {
  6438. if (container != escalator.getHeader()) {
  6439. return false;
  6440. }
  6441. if (!getHeader().getRow(eventCell.getRowIndex()).isDefault()) {
  6442. return false;
  6443. }
  6444. if (!eventCell.getColumn().isSortable()) {
  6445. // Only handle sorting events if the column is sortable
  6446. return false;
  6447. }
  6448. if (BrowserEvents.MOUSEDOWN.equals(event.getType())
  6449. && event.getShiftKey()) {
  6450. // Don't select text when shift clicking on a header.
  6451. event.preventDefault();
  6452. }
  6453. if (BrowserEvents.TOUCHSTART.equals(event.getType())) {
  6454. if (event.getTouches().length() > 1) {
  6455. return false;
  6456. }
  6457. event.preventDefault();
  6458. Touch touch = event.getChangedTouches().get(0);
  6459. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  6460. touch.getClientY());
  6461. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, true);
  6462. return true;
  6463. } else if (BrowserEvents.TOUCHMOVE.equals(event.getType())) {
  6464. if (event.getTouches().length() > 1) {
  6465. return false;
  6466. }
  6467. event.preventDefault();
  6468. Touch touch = event.getChangedTouches().get(0);
  6469. double diffX = Math.abs(touch.getClientX()
  6470. - rowEventTouchStartingPoint.getX());
  6471. double diffY = Math.abs(touch.getClientY()
  6472. - rowEventTouchStartingPoint.getY());
  6473. // Cancel long tap if finger strays too far from
  6474. // starting point
  6475. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  6476. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  6477. sorter.cancelDelayedSort();
  6478. }
  6479. return true;
  6480. } else if (BrowserEvents.TOUCHEND.equals(event.getType())) {
  6481. if (event.getTouches().length() > 1) {
  6482. return false;
  6483. }
  6484. if (sorter.isDelayedSortScheduled()) {
  6485. // Not a long tap yet, perform single sort
  6486. sorter.cancelDelayedSort();
  6487. sorter.sort(eventCell.getColumn(), false);
  6488. }
  6489. return true;
  6490. } else if (BrowserEvents.TOUCHCANCEL.equals(event.getType())) {
  6491. if (event.getTouches().length() > 1) {
  6492. return false;
  6493. }
  6494. sorter.cancelDelayedSort();
  6495. return true;
  6496. } else if (BrowserEvents.CLICK.equals(event.getType())) {
  6497. sorter.sort(eventCell.getColumn(), event.getShiftKey());
  6498. // Click events should go onward to cell focus logic
  6499. return false;
  6500. } else {
  6501. return false;
  6502. }
  6503. }
  6504. @Override
  6505. @SuppressWarnings("deprecation")
  6506. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  6507. /*
  6508. * handles details[] (translated to spacer[] for Escalator), cell[],
  6509. * header[] and footer[]
  6510. */
  6511. // "#header[0][0]/DRAGhANDLE"
  6512. Element escalatorElement = escalator.getSubPartElement(subPart
  6513. .replaceFirst("^details\\[", "spacer["));
  6514. if (escalatorElement != null) {
  6515. int detailIdx = subPart.indexOf("/");
  6516. if (detailIdx > 0) {
  6517. String detail = subPart.substring(detailIdx + 1);
  6518. getLogger().severe(
  6519. "Looking up detail from index " + detailIdx
  6520. + " onward: \"" + detail + "\"");
  6521. if (detail.equalsIgnoreCase("content")) {
  6522. // XXX: Fix this to look up by class name!
  6523. return DOM.asOld(Element.as(escalatorElement.getChild(0)));
  6524. }
  6525. if (detail.equalsIgnoreCase("draghandle")) {
  6526. // XXX: Fix this to look up by class name!
  6527. return DOM.asOld(Element.as(escalatorElement.getChild(1)));
  6528. }
  6529. }
  6530. return DOM.asOld(escalatorElement);
  6531. }
  6532. SubPartArguments args = SubPartArguments.create(subPart);
  6533. Element editor = getSubPartElementEditor(args);
  6534. if (editor != null) {
  6535. return DOM.asOld(editor);
  6536. }
  6537. return null;
  6538. }
  6539. private Element getSubPartElementEditor(SubPartArguments args) {
  6540. if (!args.getType().equalsIgnoreCase("editor")
  6541. || editor.getState() != State.ACTIVE) {
  6542. return null;
  6543. }
  6544. if (args.getIndicesLength() == 0) {
  6545. return editor.editorOverlay;
  6546. } else if (args.getIndicesLength() == 1) {
  6547. int index = args.getIndex(0);
  6548. if (index >= columns.size()) {
  6549. return null;
  6550. }
  6551. escalator.scrollToColumn(index, ScrollDestination.ANY, 0);
  6552. Widget widget = editor.getWidget(columns.get(index));
  6553. if (widget != null) {
  6554. return widget.getElement();
  6555. }
  6556. // No widget for the column.
  6557. return null;
  6558. }
  6559. return null;
  6560. }
  6561. @Override
  6562. @SuppressWarnings("deprecation")
  6563. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  6564. String escalatorStructureName = escalator.getSubPartName(subElement);
  6565. if (escalatorStructureName != null) {
  6566. return escalatorStructureName.replaceFirst("^spacer", "details");
  6567. }
  6568. String editorName = getSubPartNameEditor(subElement);
  6569. if (editorName != null) {
  6570. return editorName;
  6571. }
  6572. return null;
  6573. }
  6574. private String getSubPartNameEditor(Element subElement) {
  6575. if (editor.getState() != State.ACTIVE
  6576. || !editor.editorOverlay.isOrHasChild(subElement)) {
  6577. return null;
  6578. }
  6579. int i = 0;
  6580. for (Column<?, T> column : columns) {
  6581. if (editor.getWidget(column).getElement().isOrHasChild(subElement)) {
  6582. return "editor[" + i + "]";
  6583. }
  6584. ++i;
  6585. }
  6586. return "editor";
  6587. }
  6588. private void setSelectColumnRenderer(
  6589. final Renderer<Boolean> selectColumnRenderer) {
  6590. if (this.selectColumnRenderer == selectColumnRenderer) {
  6591. return;
  6592. }
  6593. if (this.selectColumnRenderer != null) {
  6594. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  6595. // End of Life for the old selection column renderer.
  6596. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  6597. }
  6598. // Clear field so frozen column logic in the remove method knows
  6599. // what to do
  6600. Column<?, T> colToRemove = selectionColumn;
  6601. selectionColumn = null;
  6602. removeColumnSkipSelectionColumnCheck(colToRemove);
  6603. cellFocusHandler.offsetRangeBy(-1);
  6604. }
  6605. this.selectColumnRenderer = selectColumnRenderer;
  6606. if (selectColumnRenderer != null) {
  6607. cellFocusHandler.offsetRangeBy(1);
  6608. selectionColumn = new SelectionColumn(selectColumnRenderer);
  6609. addColumnSkipSelectionColumnCheck(selectionColumn, 0);
  6610. selectionColumn.setEnabled(isEnabled());
  6611. selectionColumn.initDone();
  6612. } else {
  6613. selectionColumn = null;
  6614. refreshBody();
  6615. }
  6616. updateFrozenColumns();
  6617. }
  6618. /**
  6619. * Sets the current selection model.
  6620. * <p>
  6621. * This function will call {@link SelectionModel#setGrid(Grid)}.
  6622. *
  6623. * @param selectionModel
  6624. * a selection model implementation.
  6625. * @throws IllegalArgumentException
  6626. * if selection model argument is null
  6627. */
  6628. public void setSelectionModel(SelectionModel<T> selectionModel) {
  6629. if (selectionModel == null) {
  6630. throw new IllegalArgumentException("Selection model can't be null");
  6631. }
  6632. if (this.selectionModel != null) {
  6633. // Detach selection model from Grid.
  6634. this.selectionModel.setGrid(null);
  6635. }
  6636. this.selectionModel = selectionModel;
  6637. selectionModel.setGrid(this);
  6638. setSelectColumnRenderer(this.selectionModel
  6639. .getSelectionColumnRenderer());
  6640. // Refresh rendered rows to update selection, if it has changed
  6641. refreshBody();
  6642. }
  6643. /**
  6644. * Gets a reference to the current selection model.
  6645. *
  6646. * @return the currently used SelectionModel instance.
  6647. */
  6648. public SelectionModel<T> getSelectionModel() {
  6649. return selectionModel;
  6650. }
  6651. /**
  6652. * Sets current selection mode.
  6653. * <p>
  6654. * This is a shorthand method for {@link Grid#setSelectionModel}.
  6655. *
  6656. * @param mode
  6657. * a selection mode value
  6658. * @see {@link SelectionMode}.
  6659. */
  6660. public void setSelectionMode(SelectionMode mode) {
  6661. SelectionModel<T> model = mode.createModel();
  6662. setSelectionModel(model);
  6663. }
  6664. /**
  6665. * Test if a row is selected.
  6666. *
  6667. * @param row
  6668. * a row object
  6669. * @return true, if the current selection model considers the provided row
  6670. * object selected.
  6671. */
  6672. public boolean isSelected(T row) {
  6673. return selectionModel.isSelected(row);
  6674. }
  6675. /**
  6676. * Select a row using the current selection model.
  6677. * <p>
  6678. * Only selection models implementing {@link SelectionModel.Single} and
  6679. * {@link SelectionModel.Multi} are supported; for anything else, an
  6680. * exception will be thrown.
  6681. *
  6682. * @param row
  6683. * a row object
  6684. * @return <code>true</code> iff the current selection changed
  6685. * @throws IllegalStateException
  6686. * if the current selection model is not an instance of
  6687. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6688. */
  6689. public boolean select(T row) {
  6690. if (selectionModel instanceof SelectionModel.Single<?>) {
  6691. return ((SelectionModel.Single<T>) selectionModel).select(row);
  6692. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6693. return ((SelectionModel.Multi<T>) selectionModel)
  6694. .select(Collections.singleton(row));
  6695. } else {
  6696. throw new IllegalStateException("Unsupported selection model");
  6697. }
  6698. }
  6699. /**
  6700. * Deselect a row using the current selection model.
  6701. * <p>
  6702. * Only selection models implementing {@link SelectionModel.Single} and
  6703. * {@link SelectionModel.Multi} are supported; for anything else, an
  6704. * exception will be thrown.
  6705. *
  6706. * @param row
  6707. * a row object
  6708. * @return <code>true</code> iff the current selection changed
  6709. * @throws IllegalStateException
  6710. * if the current selection model is not an instance of
  6711. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6712. */
  6713. public boolean deselect(T row) {
  6714. if (selectionModel instanceof SelectionModel.Single<?>) {
  6715. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  6716. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6717. return ((SelectionModel.Multi<T>) selectionModel)
  6718. .deselect(Collections.singleton(row));
  6719. } else {
  6720. throw new IllegalStateException("Unsupported selection model");
  6721. }
  6722. }
  6723. /**
  6724. * Deselect all rows using the current selection model.
  6725. *
  6726. * @param row
  6727. * a row object
  6728. * @return <code>true</code> iff the current selection changed
  6729. * @throws IllegalStateException
  6730. * if the current selection model is not an instance of
  6731. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  6732. */
  6733. public boolean deselectAll() {
  6734. if (selectionModel instanceof SelectionModel.Single<?>) {
  6735. Single<T> single = ((SelectionModel.Single<T>) selectionModel);
  6736. if (single.getSelectedRow() != null) {
  6737. return single.deselect(single.getSelectedRow());
  6738. } else {
  6739. return false;
  6740. }
  6741. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  6742. return ((SelectionModel.Multi<T>) selectionModel).deselectAll();
  6743. } else {
  6744. throw new IllegalStateException("Unsupported selection model");
  6745. }
  6746. }
  6747. /**
  6748. * Gets last selected row from the current SelectionModel.
  6749. * <p>
  6750. * Only selection models implementing {@link SelectionModel.Single} are
  6751. * valid for this method; for anything else, use the
  6752. * {@link Grid#getSelectedRows()} method.
  6753. *
  6754. * @return a selected row reference, or null, if no row is selected
  6755. * @throws IllegalStateException
  6756. * if the current selection model is not an instance of
  6757. * {@link SelectionModel.Single}
  6758. */
  6759. public T getSelectedRow() {
  6760. if (selectionModel instanceof SelectionModel.Single<?>) {
  6761. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  6762. } else {
  6763. throw new IllegalStateException(
  6764. "Unsupported selection model; can not get single selected row");
  6765. }
  6766. }
  6767. /**
  6768. * Gets currently selected rows from the current selection model.
  6769. *
  6770. * @return a non-null collection containing all currently selected rows.
  6771. */
  6772. public Collection<T> getSelectedRows() {
  6773. return selectionModel.getSelectedRows();
  6774. }
  6775. @Override
  6776. public HandlerRegistration addSelectionHandler(
  6777. final SelectionHandler<T> handler) {
  6778. return addHandler(handler, SelectionEvent.getType());
  6779. }
  6780. /**
  6781. * Sets the current sort order using the fluid Sort API. Read the
  6782. * documentation for {@link Sort} for more information.
  6783. *
  6784. * @param s
  6785. * a sort instance
  6786. */
  6787. public void sort(Sort s) {
  6788. setSortOrder(s.build());
  6789. }
  6790. /**
  6791. * Sorts the Grid data in ascending order along one column.
  6792. *
  6793. * @param column
  6794. * a grid column reference
  6795. */
  6796. public <C> void sort(Column<C, T> column) {
  6797. sort(column, SortDirection.ASCENDING);
  6798. }
  6799. /**
  6800. * Sorts the Grid data along one column.
  6801. *
  6802. * @param column
  6803. * a grid column reference
  6804. * @param direction
  6805. * a sort direction value
  6806. */
  6807. public <C> void sort(Column<C, T> column, SortDirection direction) {
  6808. sort(Sort.by(column, direction));
  6809. }
  6810. /**
  6811. * Sets the sort order to use. Setting this causes the Grid to re-sort
  6812. * itself.
  6813. *
  6814. * @param order
  6815. * a sort order list. If set to null, the sort order is cleared.
  6816. */
  6817. public void setSortOrder(List<SortOrder> order) {
  6818. setSortOrder(order, false);
  6819. }
  6820. /**
  6821. * Clears the sort order and indicators without re-sorting.
  6822. */
  6823. private void clearSortOrder() {
  6824. sortOrder.clear();
  6825. refreshHeader();
  6826. }
  6827. private void setSortOrder(List<SortOrder> order, boolean userOriginated) {
  6828. if (order != sortOrder) {
  6829. sortOrder.clear();
  6830. if (order != null) {
  6831. sortOrder.addAll(order);
  6832. }
  6833. }
  6834. sort(userOriginated);
  6835. }
  6836. /**
  6837. * Get a copy of the current sort order array.
  6838. *
  6839. * @return a copy of the current sort order array
  6840. */
  6841. public List<SortOrder> getSortOrder() {
  6842. return Collections.unmodifiableList(sortOrder);
  6843. }
  6844. /**
  6845. * Finds the sorting order for this column
  6846. */
  6847. private SortOrder getSortOrder(Column<?, ?> column) {
  6848. for (SortOrder order : getSortOrder()) {
  6849. if (order.getColumn() == column) {
  6850. return order;
  6851. }
  6852. }
  6853. return null;
  6854. }
  6855. /**
  6856. * Register a GWT event handler for a sorting event. This handler gets
  6857. * called whenever this Grid needs its data source to provide data sorted in
  6858. * a specific order.
  6859. *
  6860. * @param handler
  6861. * a sort event handler
  6862. * @return the registration for the event
  6863. */
  6864. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  6865. return addHandler(handler, SortEvent.getType());
  6866. }
  6867. /**
  6868. * Register a GWT event handler for a select all event. This handler gets
  6869. * called whenever Grid needs all rows selected.
  6870. *
  6871. * @param handler
  6872. * a select all event handler
  6873. */
  6874. public HandlerRegistration addSelectAllHandler(SelectAllHandler<T> handler) {
  6875. return addHandler(handler, SelectAllEvent.getType());
  6876. }
  6877. /**
  6878. * Register a GWT event handler for a data available event. This handler
  6879. * gets called whenever the {@link DataSource} for this Grid has new data
  6880. * available.
  6881. * <p>
  6882. * This handle will be fired with the current available data after
  6883. * registration is done.
  6884. *
  6885. * @param handler
  6886. * a data available event handler
  6887. * @return the registartion for the event
  6888. */
  6889. public HandlerRegistration addDataAvailableHandler(
  6890. final DataAvailableHandler handler) {
  6891. // Deferred call to handler with current row range
  6892. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  6893. @Override
  6894. public void execute() {
  6895. if (!dataIsBeingFetched) {
  6896. handler.onDataAvailable(new DataAvailableEvent(
  6897. currentDataAvailable));
  6898. }
  6899. }
  6900. });
  6901. return addHandler(handler, DataAvailableEvent.TYPE);
  6902. }
  6903. /**
  6904. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  6905. * fired when a KeyDown event occurs while cell focus is in the Body of this
  6906. * Grid.
  6907. *
  6908. * @param handler
  6909. * the key handler to register
  6910. * @return the registration for the event
  6911. */
  6912. public HandlerRegistration addBodyKeyDownHandler(BodyKeyDownHandler handler) {
  6913. return addHandler(handler, keyDown.getAssociatedType());
  6914. }
  6915. /**
  6916. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  6917. * fired when a KeyUp event occurs while cell focus is in the Body of this
  6918. * Grid.
  6919. *
  6920. * @param handler
  6921. * the key handler to register
  6922. * @return the registration for the event
  6923. */
  6924. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  6925. return addHandler(handler, keyUp.getAssociatedType());
  6926. }
  6927. /**
  6928. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  6929. * is fired when a KeyPress event occurs while cell focus is in the Body of
  6930. * this Grid.
  6931. *
  6932. * @param handler
  6933. * the key handler to register
  6934. * @return the registration for the event
  6935. */
  6936. public HandlerRegistration addBodyKeyPressHandler(
  6937. BodyKeyPressHandler handler) {
  6938. return addHandler(handler, keyPress.getAssociatedType());
  6939. }
  6940. /**
  6941. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  6942. * is fired when a KeyDown event occurs while cell focus is in the Header of
  6943. * this Grid.
  6944. *
  6945. * @param handler
  6946. * the key handler to register
  6947. * @return the registration for the event
  6948. */
  6949. public HandlerRegistration addHeaderKeyDownHandler(
  6950. HeaderKeyDownHandler handler) {
  6951. return addHandler(handler, keyDown.getAssociatedType());
  6952. }
  6953. /**
  6954. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  6955. * fired when a KeyUp event occurs while cell focus is in the Header of this
  6956. * Grid.
  6957. *
  6958. * @param handler
  6959. * the key handler to register
  6960. * @return the registration for the event
  6961. */
  6962. public HandlerRegistration addHeaderKeyUpHandler(HeaderKeyUpHandler handler) {
  6963. return addHandler(handler, keyUp.getAssociatedType());
  6964. }
  6965. /**
  6966. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  6967. * is fired when a KeyPress event occurs while cell focus is in the Header
  6968. * of this Grid.
  6969. *
  6970. * @param handler
  6971. * the key handler to register
  6972. * @return the registration for the event
  6973. */
  6974. public HandlerRegistration addHeaderKeyPressHandler(
  6975. HeaderKeyPressHandler handler) {
  6976. return addHandler(handler, keyPress.getAssociatedType());
  6977. }
  6978. /**
  6979. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  6980. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  6981. * this Grid.
  6982. *
  6983. * @param handler
  6984. * the key handler to register
  6985. * @return the registration for the event
  6986. */
  6987. public HandlerRegistration addFooterKeyDownHandler(
  6988. FooterKeyDownHandler handler) {
  6989. return addHandler(handler, keyDown.getAssociatedType());
  6990. }
  6991. /**
  6992. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  6993. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  6994. * Grid.
  6995. *
  6996. * @param handler
  6997. * the key handler to register
  6998. * @return the registration for the event
  6999. */
  7000. public HandlerRegistration addFooterKeyUpHandler(FooterKeyUpHandler handler) {
  7001. return addHandler(handler, keyUp.getAssociatedType());
  7002. }
  7003. /**
  7004. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  7005. * is fired when a KeyPress event occurs while cell focus is in the Footer
  7006. * of this Grid.
  7007. *
  7008. * @param handler
  7009. * the key handler to register
  7010. * @return the registration for the event
  7011. */
  7012. public HandlerRegistration addFooterKeyPressHandler(
  7013. FooterKeyPressHandler handler) {
  7014. return addHandler(handler, keyPress.getAssociatedType());
  7015. }
  7016. /**
  7017. * Register a BodyClickHandler to this Grid. The event for this handler is
  7018. * fired when a Click event occurs in the Body of this Grid.
  7019. *
  7020. * @param handler
  7021. * the click handler to register
  7022. * @return the registration for the event
  7023. */
  7024. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  7025. return addHandler(handler, clickEvent.getAssociatedType());
  7026. }
  7027. /**
  7028. * Register a HeaderClickHandler to this Grid. The event for this handler is
  7029. * fired when a Click event occurs in the Header of this Grid.
  7030. *
  7031. * @param handler
  7032. * the click handler to register
  7033. * @return the registration for the event
  7034. */
  7035. public HandlerRegistration addHeaderClickHandler(HeaderClickHandler handler) {
  7036. return addHandler(handler, clickEvent.getAssociatedType());
  7037. }
  7038. /**
  7039. * Register a FooterClickHandler to this Grid. The event for this handler is
  7040. * fired when a Click event occurs in the Footer of this Grid.
  7041. *
  7042. * @param handler
  7043. * the click handler to register
  7044. * @return the registration for the event
  7045. */
  7046. public HandlerRegistration addFooterClickHandler(FooterClickHandler handler) {
  7047. return addHandler(handler, clickEvent.getAssociatedType());
  7048. }
  7049. /**
  7050. * Register a BodyDoubleClickHandler to this Grid. The event for this
  7051. * handler is fired when a double click event occurs in the Body of this
  7052. * Grid.
  7053. *
  7054. * @param handler
  7055. * the double click handler to register
  7056. * @return the registration for the event
  7057. */
  7058. public HandlerRegistration addBodyDoubleClickHandler(
  7059. BodyDoubleClickHandler handler) {
  7060. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7061. }
  7062. /**
  7063. * Register a HeaderDoubleClickHandler to this Grid. The event for this
  7064. * handler is fired when a double click event occurs in the Header of this
  7065. * Grid.
  7066. *
  7067. * @param handler
  7068. * the double click handler to register
  7069. * @return the registration for the event
  7070. */
  7071. public HandlerRegistration addHeaderDoubleClickHandler(
  7072. HeaderDoubleClickHandler handler) {
  7073. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7074. }
  7075. /**
  7076. * Register a FooterDoubleClickHandler to this Grid. The event for this
  7077. * handler is fired when a double click event occurs in the Footer of this
  7078. * Grid.
  7079. *
  7080. * @param handler
  7081. * the double click handler to register
  7082. * @return the registration for the event
  7083. */
  7084. public HandlerRegistration addFooterDoubleClickHandler(
  7085. FooterDoubleClickHandler handler) {
  7086. return addHandler(handler, doubleClickEvent.getAssociatedType());
  7087. }
  7088. /**
  7089. * Register a column reorder handler to this Grid. The event for this
  7090. * handler is fired when the Grid's columns are reordered.
  7091. *
  7092. * @since 7.5.0
  7093. * @param handler
  7094. * the handler for the event
  7095. * @return the registration for the event
  7096. */
  7097. public HandlerRegistration addColumnReorderHandler(
  7098. ColumnReorderHandler<T> handler) {
  7099. return addHandler(handler, ColumnReorderEvent.getType());
  7100. }
  7101. /**
  7102. * Register a column visibility change handler to this Grid. The event for
  7103. * this handler is fired when the Grid's columns change visibility.
  7104. *
  7105. * @since 7.5.0
  7106. * @param handler
  7107. * the handler for the event
  7108. * @return the registration for the event
  7109. */
  7110. public HandlerRegistration addColumnVisibilityChangeHandler(
  7111. ColumnVisibilityChangeHandler<T> handler) {
  7112. return addHandler(handler, ColumnVisibilityChangeEvent.getType());
  7113. }
  7114. /**
  7115. * Register a column resize handler to this Grid. The event for this handler
  7116. * is fired when the Grid's columns are resized.
  7117. *
  7118. * @since 7.6
  7119. * @param handler
  7120. * the handler for the event
  7121. * @return the registration for the event
  7122. */
  7123. public HandlerRegistration addColumnResizeHandler(
  7124. ColumnResizeHandler<T> handler) {
  7125. return addHandler(handler, ColumnResizeEvent.getType());
  7126. }
  7127. /**
  7128. * Register a enabled status change handler to this Grid.
  7129. * The event for this handler is fired when the Grid changes from disabled
  7130. * to enabled and vice-versa.
  7131. * @param handler the handler for the event
  7132. * @return the registration for the event
  7133. */
  7134. public HandlerRegistration addEnabledHandler(GridEnabledHandler handler) {
  7135. return addHandler(handler, GridEnabledEvent.TYPE);
  7136. }
  7137. /**
  7138. * Apply sorting to data source.
  7139. */
  7140. private void sort(boolean userOriginated) {
  7141. refreshHeader();
  7142. fireEvent(new SortEvent<T>(this,
  7143. Collections.unmodifiableList(sortOrder), userOriginated));
  7144. }
  7145. private int getLastVisibleRowIndex() {
  7146. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  7147. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  7148. Element lastRow;
  7149. do {
  7150. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  7151. } while (lastRow.getAbsoluteTop() > footerTop);
  7152. return lastRowIndex;
  7153. }
  7154. private int getFirstVisibleRowIndex() {
  7155. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  7156. int headerBottom = escalator.getHeader().getElement()
  7157. .getAbsoluteBottom();
  7158. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  7159. while (firstRow.getAbsoluteBottom() < headerBottom) {
  7160. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  7161. }
  7162. return firstRowIndex;
  7163. }
  7164. /**
  7165. * Adds a scroll handler to this grid
  7166. *
  7167. * @param handler
  7168. * the scroll handler to add
  7169. * @return a handler registration for the registered scroll handler
  7170. */
  7171. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  7172. return addHandler(handler, ScrollEvent.TYPE);
  7173. }
  7174. @Override
  7175. public boolean isWorkPending() {
  7176. return escalator.isWorkPending() || dataIsBeingFetched
  7177. || autoColumnWidthsRecalculator.isScheduled()
  7178. || editor.isWorkPending();
  7179. }
  7180. /**
  7181. * Returns whether columns can be reordered with drag and drop.
  7182. *
  7183. * @since 7.5.0
  7184. * @return <code>true</code> if columns can be reordered, false otherwise
  7185. */
  7186. public boolean isColumnReorderingAllowed() {
  7187. return columnReorderingAllowed;
  7188. }
  7189. /**
  7190. * Sets whether column reordering with drag and drop is allowed or not.
  7191. *
  7192. * @since 7.5.0
  7193. * @param columnReorderingAllowed
  7194. * specifies whether column reordering is allowed
  7195. */
  7196. public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
  7197. this.columnReorderingAllowed = columnReorderingAllowed;
  7198. }
  7199. /**
  7200. * Sets a new column order for the grid. All columns which are not ordered
  7201. * here will remain in the order they were before as the last columns of
  7202. * grid.
  7203. *
  7204. * @param orderedColumns
  7205. * array of columns in wanted order
  7206. */
  7207. public void setColumnOrder(Column<?, T>... orderedColumns) {
  7208. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  7209. // Trigger ComplexRenderer.destroy for old content
  7210. conf.removeColumns(0, conf.getColumnCount());
  7211. List<Column<?, T>> newOrder = new ArrayList<Column<?, T>>();
  7212. if (selectionColumn != null) {
  7213. newOrder.add(selectionColumn);
  7214. }
  7215. int i = 0;
  7216. for (Column<?, T> column : orderedColumns) {
  7217. if (columns.contains(column)) {
  7218. newOrder.add(column);
  7219. ++i;
  7220. } else {
  7221. throw new IllegalArgumentException("Given column at index " + i
  7222. + " does not exist in Grid");
  7223. }
  7224. }
  7225. if (columns.size() != newOrder.size()) {
  7226. columns.removeAll(newOrder);
  7227. newOrder.addAll(columns);
  7228. }
  7229. columns = newOrder;
  7230. List<Column<?, T>> visibleColumns = getVisibleColumns();
  7231. // Do ComplexRenderer.init and render new content
  7232. conf.insertColumns(0, visibleColumns.size());
  7233. // Number of frozen columns should be kept same #16901
  7234. updateFrozenColumns();
  7235. // Update column widths.
  7236. for (Column<?, T> column : columns) {
  7237. column.reapplyWidth();
  7238. }
  7239. // Recalculate all the colspans
  7240. for (HeaderRow row : header.getRows()) {
  7241. row.calculateColspans();
  7242. }
  7243. for (FooterRow row : footer.getRows()) {
  7244. row.calculateColspans();
  7245. }
  7246. columnHider.updateTogglesOrder();
  7247. fireEvent(new ColumnReorderEvent<T>());
  7248. }
  7249. /**
  7250. * Sets the style generator that is used for generating styles for cells
  7251. *
  7252. * @param cellStyleGenerator
  7253. * the cell style generator to set, or <code>null</code> to
  7254. * remove a previously set generator
  7255. */
  7256. public void setCellStyleGenerator(CellStyleGenerator<T> cellStyleGenerator) {
  7257. this.cellStyleGenerator = cellStyleGenerator;
  7258. refreshBody();
  7259. }
  7260. /**
  7261. * Gets the style generator that is used for generating styles for cells
  7262. *
  7263. * @return the cell style generator, or <code>null</code> if no generator is
  7264. * set
  7265. */
  7266. public CellStyleGenerator<T> getCellStyleGenerator() {
  7267. return cellStyleGenerator;
  7268. }
  7269. /**
  7270. * Sets the style generator that is used for generating styles for rows
  7271. *
  7272. * @param rowStyleGenerator
  7273. * the row style generator to set, or <code>null</code> to remove
  7274. * a previously set generator
  7275. */
  7276. public void setRowStyleGenerator(RowStyleGenerator<T> rowStyleGenerator) {
  7277. this.rowStyleGenerator = rowStyleGenerator;
  7278. refreshBody();
  7279. }
  7280. /**
  7281. * Gets the style generator that is used for generating styles for rows
  7282. *
  7283. * @return the row style generator, or <code>null</code> if no generator is
  7284. * set
  7285. */
  7286. public RowStyleGenerator<T> getRowStyleGenerator() {
  7287. return rowStyleGenerator;
  7288. }
  7289. private static void setCustomStyleName(Element element, String styleName) {
  7290. assert element != null;
  7291. String oldStyleName = element
  7292. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  7293. if (!SharedUtil.equals(oldStyleName, styleName)) {
  7294. if (oldStyleName != null && !oldStyleName.isEmpty()) {
  7295. element.removeClassName(oldStyleName);
  7296. }
  7297. if (styleName != null && !styleName.isEmpty()) {
  7298. element.addClassName(styleName);
  7299. }
  7300. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  7301. }
  7302. }
  7303. /**
  7304. * Opens the editor over the row with the given index.
  7305. *
  7306. * @param rowIndex
  7307. * the index of the row to be edited
  7308. *
  7309. * @throws IllegalStateException
  7310. * if the editor is not enabled
  7311. * @throws IllegalStateException
  7312. * if the editor is already in edit mode
  7313. */
  7314. public void editRow(int rowIndex) {
  7315. editor.editRow(rowIndex);
  7316. }
  7317. /**
  7318. * Returns whether the editor is currently open on some row.
  7319. *
  7320. * @return {@code true} if the editor is active, {@code false} otherwise.
  7321. */
  7322. public boolean isEditorActive() {
  7323. return editor.getState() != State.INACTIVE;
  7324. }
  7325. /**
  7326. * Saves any unsaved changes in the editor to the data source.
  7327. *
  7328. * @throws IllegalStateException
  7329. * if the editor is not enabled
  7330. * @throws IllegalStateException
  7331. * if the editor is not in edit mode
  7332. */
  7333. public void saveEditor() {
  7334. editor.save();
  7335. }
  7336. /**
  7337. * Cancels the currently active edit and hides the editor. Any changes that
  7338. * are not {@link #saveEditor() saved} are lost.
  7339. *
  7340. * @throws IllegalStateException
  7341. * if the editor is not enabled
  7342. * @throws IllegalStateException
  7343. * if the editor is not in edit mode
  7344. */
  7345. public void cancelEditor() {
  7346. editor.cancel();
  7347. }
  7348. /**
  7349. * Returns the handler responsible for binding data and editor widgets to
  7350. * the editor.
  7351. *
  7352. * @return the editor handler or null if not set
  7353. */
  7354. public EditorHandler<T> getEditorHandler() {
  7355. return editor.getHandler();
  7356. }
  7357. /**
  7358. * Sets the handler responsible for binding data and editor widgets to the
  7359. * editor.
  7360. *
  7361. * @param rowHandler
  7362. * the new editor handler
  7363. *
  7364. * @throws IllegalStateException
  7365. * if the editor is currently in edit mode
  7366. */
  7367. public void setEditorHandler(EditorHandler<T> handler) {
  7368. editor.setHandler(handler);
  7369. }
  7370. /**
  7371. * Returns the enabled state of the editor.
  7372. *
  7373. * @return true if editing is enabled, false otherwise
  7374. */
  7375. public boolean isEditorEnabled() {
  7376. return editor.isEnabled();
  7377. }
  7378. /**
  7379. * Sets the enabled state of the editor.
  7380. *
  7381. * @param enabled
  7382. * true to enable editing, false to disable
  7383. *
  7384. * @throws IllegalStateException
  7385. * if in edit mode and trying to disable
  7386. * @throws IllegalStateException
  7387. * if the editor handler is not set
  7388. */
  7389. public void setEditorEnabled(boolean enabled) {
  7390. editor.setEnabled(enabled);
  7391. }
  7392. /**
  7393. * Returns the editor widget associated with the given column. If the editor
  7394. * is not active, returns null.
  7395. *
  7396. * @param column
  7397. * the column
  7398. * @return the widget if the editor is open, null otherwise
  7399. */
  7400. public Widget getEditorWidget(Column<?, T> column) {
  7401. return editor.getWidget(column);
  7402. }
  7403. /**
  7404. * Sets the caption on the save button in the Grid editor.
  7405. *
  7406. * @param saveCaption
  7407. * the caption to set
  7408. * @throws IllegalArgumentException
  7409. * if {@code saveCaption} is {@code null}
  7410. */
  7411. public void setEditorSaveCaption(String saveCaption)
  7412. throws IllegalArgumentException {
  7413. editor.setSaveCaption(saveCaption);
  7414. }
  7415. /**
  7416. * Gets the current caption on the save button in the Grid editor.
  7417. *
  7418. * @return the current caption on the save button
  7419. */
  7420. public String getEditorSaveCaption() {
  7421. return editor.getSaveCaption();
  7422. }
  7423. /**
  7424. * Sets the caption on the cancel button in the Grid editor.
  7425. *
  7426. * @param cancelCaption
  7427. * the caption to set
  7428. * @throws IllegalArgumentException
  7429. * if {@code cancelCaption} is {@code null}
  7430. */
  7431. public void setEditorCancelCaption(String cancelCaption)
  7432. throws IllegalArgumentException {
  7433. editor.setCancelCaption(cancelCaption);
  7434. }
  7435. /**
  7436. * Gets the caption on the cancel button in the Grid editor.
  7437. *
  7438. * @return the current caption on the cancel button
  7439. */
  7440. public String getEditorCancelCaption() {
  7441. return editor.getCancelCaption();
  7442. }
  7443. @Override
  7444. protected void onAttach() {
  7445. super.onAttach();
  7446. if (getEscalator().getBody().getRowCount() == 0 && dataSource != null) {
  7447. setEscalatorSizeFromDataSource();
  7448. }
  7449. // Grid was just attached to DOM. Column widths should be calculated.
  7450. recalculateColumnWidths();
  7451. }
  7452. @Override
  7453. protected void onDetach() {
  7454. Set<Integer> details = new HashSet<Integer>(visibleDetails);
  7455. for (int row : details) {
  7456. setDetailsVisible(row, false);
  7457. }
  7458. super.onDetach();
  7459. }
  7460. @Override
  7461. public void onResize() {
  7462. super.onResize();
  7463. /*
  7464. * Delay calculation to be deferred so Escalator can do it's magic.
  7465. */
  7466. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7467. @Override
  7468. public void execute() {
  7469. if (escalator.getInnerWidth() != autoColumnWidthsRecalculator.lastCalculatedInnerWidth) {
  7470. recalculateColumnWidths();
  7471. }
  7472. // Vertical resizing could make editor positioning invalid so it
  7473. // needs to be recalculated on resize
  7474. if (isEditorActive()) {
  7475. editor.updateVerticalScrollPosition();
  7476. }
  7477. // if there is a resize, we need to refresh the body to avoid an
  7478. // off-by-one error which occurs when the user scrolls all the
  7479. // way to the bottom.
  7480. refreshBody();
  7481. }
  7482. });
  7483. }
  7484. /**
  7485. * Grid does not support adding Widgets this way.
  7486. * <p>
  7487. * This method is implemented only because removing widgets from Grid (added
  7488. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7489. *
  7490. * @param w
  7491. * irrelevant
  7492. * @throws UnsupportedOperationException
  7493. * always
  7494. */
  7495. @Override
  7496. @Deprecated
  7497. public void add(Widget w) {
  7498. throw new UnsupportedOperationException(
  7499. "Cannot add widgets to Grid with this method");
  7500. }
  7501. /**
  7502. * Grid does not support clearing Widgets this way.
  7503. * <p>
  7504. * This method is implemented only because removing widgets from Grid (added
  7505. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7506. *
  7507. * @throws UnsupportedOperationException
  7508. * always
  7509. */
  7510. @Override
  7511. @Deprecated
  7512. public void clear() {
  7513. throw new UnsupportedOperationException(
  7514. "Cannot clear widgets from Grid this way");
  7515. }
  7516. /**
  7517. * Grid does not support iterating through Widgets this way.
  7518. * <p>
  7519. * This method is implemented only because removing widgets from Grid (added
  7520. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7521. *
  7522. * @return never
  7523. * @throws UnsupportedOperationException
  7524. * always
  7525. */
  7526. @Override
  7527. @Deprecated
  7528. public Iterator<Widget> iterator() {
  7529. throw new UnsupportedOperationException(
  7530. "Cannot iterate through widgets in Grid this way");
  7531. }
  7532. /**
  7533. * Grid does not support removing Widgets this way.
  7534. * <p>
  7535. * This method is implemented only because removing widgets from Grid (added
  7536. * via e.g. {@link Renderer}s) requires the {@link HasWidgets} interface.
  7537. *
  7538. * @return always <code>false</code>
  7539. */
  7540. @Override
  7541. @Deprecated
  7542. public boolean remove(Widget w) {
  7543. /*
  7544. * This is the method that is the sole reason to have Grid implement
  7545. * HasWidget - when Vaadin removes a Component from the hierarchy, the
  7546. * corresponding Widget will call removeFromParent() on itself. GWT will
  7547. * check there that its parent (i.e. Grid) implements HasWidgets, and
  7548. * will call this remove(Widget) method.
  7549. *
  7550. * tl;dr: all this song and dance to make sure GWT's sanity checks
  7551. * aren't triggered, even though they effectively do nothing interesting
  7552. * from Grid's perspective.
  7553. */
  7554. return false;
  7555. }
  7556. /**
  7557. * Accesses the package private method Widget#setParent()
  7558. *
  7559. * @param widget
  7560. * The widget to access
  7561. * @param parent
  7562. * The parent to set
  7563. */
  7564. private static native final void setParent(Widget widget, Grid<?> parent)
  7565. /*-{
  7566. widget.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(parent);
  7567. }-*/;
  7568. private static native final void onAttach(Widget widget)
  7569. /*-{
  7570. widget.@Widget::onAttach()();
  7571. }-*/;
  7572. private static native final void onDetach(Widget widget)
  7573. /*-{
  7574. widget.@Widget::onDetach()();
  7575. }-*/;
  7576. @Override
  7577. protected void doAttachChildren() {
  7578. if (sidebar.getParent() == this) {
  7579. onAttach(sidebar);
  7580. }
  7581. }
  7582. @Override
  7583. protected void doDetachChildren() {
  7584. if (sidebar.getParent() == this) {
  7585. onDetach(sidebar);
  7586. }
  7587. }
  7588. private void attachWidget(Widget w, Element parent) {
  7589. assert w.getParent() == null;
  7590. parent.appendChild(w.getElement());
  7591. setParent(w, this);
  7592. }
  7593. private void detachWidget(Widget w) {
  7594. assert w.getParent() == this;
  7595. setParent(w, null);
  7596. w.getElement().removeFromParent();
  7597. }
  7598. /**
  7599. * Resets all cached pixel sizes and reads new values from the DOM. This
  7600. * methods should be used e.g. when styles affecting the dimensions of
  7601. * elements in this grid have been changed.
  7602. */
  7603. public void resetSizesFromDom() {
  7604. getEscalator().resetSizesFromDom();
  7605. }
  7606. /**
  7607. * Sets a new details generator for row details.
  7608. * <p>
  7609. * The currently opened row details will be re-rendered.
  7610. *
  7611. * @since 7.5.0
  7612. * @param detailsGenerator
  7613. * the details generator to set
  7614. * @throws IllegalArgumentException
  7615. * if detailsGenerator is <code>null</code>;
  7616. */
  7617. public void setDetailsGenerator(DetailsGenerator detailsGenerator)
  7618. throws IllegalArgumentException {
  7619. if (detailsGenerator == null) {
  7620. throw new IllegalArgumentException(
  7621. "Details generator may not be null");
  7622. }
  7623. for (Integer index : visibleDetails) {
  7624. setDetailsVisible(index, false);
  7625. }
  7626. this.detailsGenerator = detailsGenerator;
  7627. // this will refresh all visible spacers
  7628. escalator.getBody().setSpacerUpdater(gridSpacerUpdater);
  7629. }
  7630. /**
  7631. * Gets the current details generator for row details.
  7632. *
  7633. * @since 7.5.0
  7634. * @return the detailsGenerator the current details generator
  7635. */
  7636. public DetailsGenerator getDetailsGenerator() {
  7637. return detailsGenerator;
  7638. }
  7639. /**
  7640. * Shows or hides the details for a specific row.
  7641. * <p>
  7642. * This method does nothing if trying to set show already-visible details,
  7643. * or hide already-hidden details.
  7644. *
  7645. * @since 7.5.0
  7646. * @param rowIndex
  7647. * the index of the affected row
  7648. * @param visible
  7649. * <code>true</code> to show the details, or <code>false</code>
  7650. * to hide them
  7651. * @see #isDetailsVisible(int)
  7652. */
  7653. public void setDetailsVisible(int rowIndex, boolean visible) {
  7654. if (DetailsGenerator.NULL.equals(detailsGenerator)) {
  7655. return;
  7656. }
  7657. Integer rowIndexInteger = Integer.valueOf(rowIndex);
  7658. /*
  7659. * We want to prevent opening a details row twice, so any subsequent
  7660. * openings (or closings) of details is a NOOP.
  7661. *
  7662. * When a details row is opened, it is given an arbitrary height
  7663. * (because Escalator requires a height upon opening). Only when it's
  7664. * opened, Escalator will ask the generator to generate a widget, which
  7665. * we then can measure. When measured, we correct the initial height by
  7666. * the original height.
  7667. *
  7668. * Without this check, we would override the measured height, and revert
  7669. * back to the initial, arbitrary, height which would most probably be
  7670. * wrong.
  7671. *
  7672. * see GridSpacerUpdater.init for implementation details.
  7673. */
  7674. boolean isVisible = isDetailsVisible(rowIndex);
  7675. if (visible && !isVisible) {
  7676. escalator.getBody().setSpacer(rowIndex, DETAILS_ROW_INITIAL_HEIGHT);
  7677. visibleDetails.add(rowIndexInteger);
  7678. }
  7679. else if (!visible && isVisible) {
  7680. escalator.getBody().setSpacer(rowIndex, -1);
  7681. visibleDetails.remove(rowIndexInteger);
  7682. }
  7683. }
  7684. /**
  7685. * Check whether the details for a row is visible or not.
  7686. *
  7687. * @since 7.5.0
  7688. * @param rowIndex
  7689. * the index of the row for which to check details
  7690. * @return <code>true</code> iff the details for the given row is visible
  7691. * @see #setDetailsVisible(int, boolean)
  7692. */
  7693. public boolean isDetailsVisible(int rowIndex) {
  7694. return visibleDetails.contains(Integer.valueOf(rowIndex));
  7695. }
  7696. /**
  7697. * Requests that the column widths should be recalculated.
  7698. * <p>
  7699. * The actual recalculation is not necessarily done immediately so you
  7700. * cannot rely on the columns being the correct width after the call
  7701. * returns.
  7702. *
  7703. * @since 7.4.1
  7704. */
  7705. public void recalculateColumnWidths() {
  7706. autoColumnWidthsRecalculator.schedule();
  7707. }
  7708. /**
  7709. * Gets the customizable menu bar that is by default used for toggling
  7710. * column hidability. The application developer is allowed to add their
  7711. * custom items to the end of the menu, but should try to avoid modifying
  7712. * the items in the beginning of the menu that control the column hiding if
  7713. * any columns are marked as hidable. A toggle for opening the menu will be
  7714. * displayed whenever the menu contains at least one item.
  7715. *
  7716. * @since 7.5.0
  7717. * @return the menu bar
  7718. */
  7719. public MenuBar getSidebarMenu() {
  7720. return sidebar.menuBar;
  7721. }
  7722. /**
  7723. * Tests whether the sidebar menu is currently open.
  7724. *
  7725. * @since 7.5.0
  7726. * @see #getSidebarMenu()
  7727. * @return <code>true</code> if the sidebar is open; <code>false</code> if
  7728. * it is closed
  7729. */
  7730. public boolean isSidebarOpen() {
  7731. return sidebar.isOpen();
  7732. }
  7733. /**
  7734. * Sets whether the sidebar menu is open.
  7735. *
  7736. *
  7737. * @since 7.5.0
  7738. * @see #getSidebarMenu()
  7739. * @see #isSidebarOpen()
  7740. * @param sidebarOpen
  7741. * <code>true</code> to open the sidebar; <code>false</code> to
  7742. * close it
  7743. */
  7744. public void setSidebarOpen(boolean sidebarOpen) {
  7745. if (sidebarOpen) {
  7746. sidebar.open();
  7747. } else {
  7748. sidebar.close();
  7749. }
  7750. }
  7751. @Override
  7752. public int getTabIndex() {
  7753. return FocusUtil.getTabIndex(this);
  7754. }
  7755. @Override
  7756. public void setAccessKey(char key) {
  7757. FocusUtil.setAccessKey(this, key);
  7758. }
  7759. @Override
  7760. public void setFocus(boolean focused) {
  7761. FocusUtil.setFocus(this, focused);
  7762. }
  7763. @Override
  7764. public void setTabIndex(int index) {
  7765. FocusUtil.setTabIndex(this, index);
  7766. }
  7767. @Override
  7768. public void focus() {
  7769. setFocus(true);
  7770. }
  7771. /**
  7772. * Sets the buffered editor mode.
  7773. *
  7774. * @since 7.6
  7775. * @param editorUnbuffered
  7776. * <code>true</code> to enable buffered editor,
  7777. * <code>false</code> to disable it
  7778. */
  7779. public void setEditorBuffered(boolean editorBuffered) {
  7780. editor.setBuffered(editorBuffered);
  7781. }
  7782. /**
  7783. * Gets the buffered editor mode.
  7784. *
  7785. * @since 7.6
  7786. * @return <code>true</code> if buffered editor is enabled,
  7787. * <code>false</code> otherwise
  7788. */
  7789. public boolean isEditorBuffered() {
  7790. return editor.isBuffered();
  7791. }
  7792. /**
  7793. * Returns the {@link EventCellReference} for the latest event fired from
  7794. * this Grid.
  7795. * <p>
  7796. * Note: This cell reference will be updated when firing the next event.
  7797. *
  7798. * @since 7.5
  7799. * @return event cell reference
  7800. */
  7801. public EventCellReference<T> getEventCell() {
  7802. return eventCell;
  7803. }
  7804. /**
  7805. * Returns a CellReference for the cell to which the given element belongs
  7806. * to.
  7807. *
  7808. * @since 7.6
  7809. * @param element
  7810. * Element to find from the cell's content.
  7811. * @return CellReference or <code>null</code> if cell was not found.
  7812. */
  7813. public CellReference<T> getCellReference(Element element) {
  7814. RowContainer container = getEscalator().findRowContainer(element);
  7815. if (container != null) {
  7816. Cell cell = container.getCell(element);
  7817. if (cell != null) {
  7818. EventCellReference<T> cellRef = new EventCellReference<T>(this);
  7819. cellRef.set(cell, getSectionFromContainer(container));
  7820. return cellRef;
  7821. }
  7822. }
  7823. return null;
  7824. }
  7825. }