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

Grid.java 314KB

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