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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui.grid;
  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.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import com.google.gwt.core.client.Scheduler;
  29. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  30. import com.google.gwt.core.shared.GWT;
  31. import com.google.gwt.dom.client.BrowserEvents;
  32. import com.google.gwt.dom.client.Element;
  33. import com.google.gwt.dom.client.EventTarget;
  34. import com.google.gwt.dom.client.TableCellElement;
  35. import com.google.gwt.dom.client.TableRowElement;
  36. import com.google.gwt.dom.client.Touch;
  37. import com.google.gwt.event.dom.client.KeyCodes;
  38. import com.google.gwt.event.dom.client.KeyEvent;
  39. import com.google.gwt.event.dom.client.MouseEvent;
  40. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  41. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  42. import com.google.gwt.event.shared.HandlerRegistration;
  43. import com.google.gwt.touch.client.Point;
  44. import com.google.gwt.user.client.DOM;
  45. import com.google.gwt.user.client.Event;
  46. import com.google.gwt.user.client.Timer;
  47. import com.google.gwt.user.client.ui.CheckBox;
  48. import com.google.gwt.user.client.ui.ResizeComposite;
  49. import com.google.gwt.user.client.ui.Widget;
  50. import com.vaadin.client.DeferredWorker;
  51. import com.vaadin.client.Util;
  52. import com.vaadin.client.data.DataChangeHandler;
  53. import com.vaadin.client.data.DataSource;
  54. import com.vaadin.client.ui.SubPartAware;
  55. import com.vaadin.client.ui.grid.EditorRow.State;
  56. import com.vaadin.client.ui.grid.events.AbstractGridKeyEventHandler;
  57. import com.vaadin.client.ui.grid.events.AbstractGridMouseEventHandler;
  58. import com.vaadin.client.ui.grid.events.BodyClickHandler;
  59. import com.vaadin.client.ui.grid.events.BodyKeyDownHandler;
  60. import com.vaadin.client.ui.grid.events.BodyKeyPressHandler;
  61. import com.vaadin.client.ui.grid.events.BodyKeyUpHandler;
  62. import com.vaadin.client.ui.grid.events.FooterClickHandler;
  63. import com.vaadin.client.ui.grid.events.FooterKeyDownHandler;
  64. import com.vaadin.client.ui.grid.events.FooterKeyPressHandler;
  65. import com.vaadin.client.ui.grid.events.FooterKeyUpHandler;
  66. import com.vaadin.client.ui.grid.events.GridClickEvent;
  67. import com.vaadin.client.ui.grid.events.GridKeyDownEvent;
  68. import com.vaadin.client.ui.grid.events.GridKeyPressEvent;
  69. import com.vaadin.client.ui.grid.events.GridKeyUpEvent;
  70. import com.vaadin.client.ui.grid.events.HeaderClickHandler;
  71. import com.vaadin.client.ui.grid.events.HeaderKeyDownHandler;
  72. import com.vaadin.client.ui.grid.events.HeaderKeyPressHandler;
  73. import com.vaadin.client.ui.grid.events.HeaderKeyUpHandler;
  74. import com.vaadin.client.ui.grid.events.ScrollEvent;
  75. import com.vaadin.client.ui.grid.events.ScrollHandler;
  76. import com.vaadin.client.ui.grid.events.SelectAllEvent;
  77. import com.vaadin.client.ui.grid.events.SelectAllHandler;
  78. import com.vaadin.client.ui.grid.renderers.ComplexRenderer;
  79. import com.vaadin.client.ui.grid.renderers.WidgetRenderer;
  80. import com.vaadin.client.ui.grid.selection.HasSelectionChangeHandlers;
  81. import com.vaadin.client.ui.grid.selection.SelectionChangeEvent;
  82. import com.vaadin.client.ui.grid.selection.SelectionChangeHandler;
  83. import com.vaadin.client.ui.grid.selection.SelectionModel;
  84. import com.vaadin.client.ui.grid.selection.SelectionModel.Multi;
  85. import com.vaadin.client.ui.grid.selection.SelectionModelMulti;
  86. import com.vaadin.client.ui.grid.selection.SelectionModelNone;
  87. import com.vaadin.client.ui.grid.selection.SelectionModelSingle;
  88. import com.vaadin.client.ui.grid.sort.Sort;
  89. import com.vaadin.client.ui.grid.sort.SortEvent;
  90. import com.vaadin.client.ui.grid.sort.SortHandler;
  91. import com.vaadin.client.ui.grid.sort.SortOrder;
  92. import com.vaadin.shared.ui.grid.GridColumnState;
  93. import com.vaadin.shared.ui.grid.GridConstants;
  94. import com.vaadin.shared.ui.grid.GridStaticCellType;
  95. import com.vaadin.shared.ui.grid.HeightMode;
  96. import com.vaadin.shared.ui.grid.Range;
  97. import com.vaadin.shared.ui.grid.ScrollDestination;
  98. import com.vaadin.shared.ui.grid.SortDirection;
  99. import com.vaadin.shared.ui.grid.SortEventOriginator;
  100. import com.vaadin.shared.util.SharedUtil;
  101. /**
  102. * A data grid view that supports columns and lazy loading of data rows from a
  103. * data source.
  104. *
  105. * <h3>Columns</h3>
  106. * <p>
  107. * The {@link GridColumn} class defines the renderer used to render a cell in
  108. * the grid. Implement {@link GridColumn#getValue(Object)} to retrieve the cell
  109. * value from the row object and return the cell renderer to render that cell.
  110. * </p>
  111. * <p>
  112. * {@link GridColumn}s contain other properties like the width of the column and
  113. * the visiblity of the column. If you want to change a column's properties
  114. * after it has been added to the grid you can get a column object for a
  115. * specific column index using {@link Grid#getColumn(int)}.
  116. * </p>
  117. * <p>
  118. *
  119. * TODO Explain about headers/footers once the multiple header/footer api has
  120. * been implemented
  121. *
  122. * <h3>Data sources</h3>
  123. * <p>
  124. * TODO Explain about what a data source is and how it should be implemented.
  125. * </p>
  126. *
  127. * @param <T>
  128. * The row type of the grid. The row type is the POJO type from where
  129. * the data is retrieved into the column cells.
  130. * @since
  131. * @author Vaadin Ltd
  132. */
  133. public class Grid<T> extends ResizeComposite implements
  134. HasSelectionChangeHandlers<T>, SubPartAware, DeferredWorker {
  135. /**
  136. * Callback interface for generating custom style names for data rows and
  137. * cells.
  138. *
  139. * @see Grid#setCellStyleGenerator(CellStyleGenerator)
  140. */
  141. public interface CellStyleGenerator<T> {
  142. /**
  143. * Called by Grid to generate a style name for a row or cell element.
  144. * Row styles are generated when the column parameter is
  145. * <code>null</code>, otherwise a cell style is generated.
  146. * <p>
  147. * The returned style name is prefixed so that the actual style for
  148. * cells will be <tt>v-grid-cell-content-[style name]</tt>, and the row
  149. * style will be <tt>v-grid-row-[style name]</tt>.
  150. *
  151. * @param grid
  152. * the source grid
  153. * @param row
  154. * the data object of the target row
  155. * @param rowIndex
  156. * the index of the row
  157. * @param column
  158. * the column of the cell, <code>null</code> when getting a
  159. * row style
  160. * @param columnIndex
  161. * the index of the column, -1 when getting a row style
  162. * @return the style name to add to this cell or row element, or
  163. * <code>null</code> to not set any style
  164. */
  165. public abstract String getStyle(Grid<T> grid, T row, int rowIndex,
  166. GridColumn<?, T> column, int columnIndex);
  167. }
  168. /**
  169. * Abstract base class for Grid header and footer sections.
  170. *
  171. * @param <ROWTYPE>
  172. * the type of the rows in the section
  173. */
  174. protected abstract static class StaticSection<ROWTYPE extends StaticSection.StaticRow<?>> {
  175. /**
  176. * A header or footer cell. Has a simple textual caption.
  177. *
  178. */
  179. static class StaticCell {
  180. private Object content = null;
  181. private int colspan = 1;
  182. private StaticSection<?> section;
  183. private GridStaticCellType type = GridStaticCellType.TEXT;
  184. private String styleName = null;
  185. /**
  186. * Sets the text displayed in this cell.
  187. *
  188. * @param text
  189. * a plain text caption
  190. */
  191. public void setText(String text) {
  192. this.content = text;
  193. this.type = GridStaticCellType.TEXT;
  194. section.requestSectionRefresh();
  195. }
  196. /**
  197. * Returns the text displayed in this cell.
  198. *
  199. * @return the plain text caption
  200. */
  201. public String getText() {
  202. if (type != GridStaticCellType.TEXT) {
  203. throw new IllegalStateException(
  204. "Cannot fetch Text from a cell with type " + type);
  205. }
  206. return (String) content;
  207. }
  208. protected StaticSection<?> getSection() {
  209. assert section != null;
  210. return section;
  211. }
  212. protected void setSection(StaticSection<?> section) {
  213. this.section = section;
  214. }
  215. /**
  216. * Returns the amount of columns the cell spans. By default is 1.
  217. *
  218. * @return The amount of columns the cell spans.
  219. */
  220. public int getColspan() {
  221. return colspan;
  222. }
  223. /**
  224. * Sets the amount of columns the cell spans. Must be more or equal
  225. * to 1. By default is 1.
  226. *
  227. * @param colspan
  228. * the colspan to set
  229. */
  230. public void setColspan(int colspan) {
  231. if (colspan < 1) {
  232. throw new IllegalArgumentException(
  233. "Colspan cannot be less than 1");
  234. }
  235. this.colspan = colspan;
  236. section.requestSectionRefresh();
  237. }
  238. /**
  239. * Returns the html inside the cell.
  240. *
  241. * @throws IllegalStateException
  242. * if trying to retrive HTML from a cell with a type
  243. * other than {@link GridStaticCellType#HTML}.
  244. * @return the html content of the cell.
  245. */
  246. public String getHtml() {
  247. if (type != GridStaticCellType.HTML) {
  248. throw new IllegalStateException(
  249. "Cannot fetch HTML from a cell with type " + type);
  250. }
  251. return (String) content;
  252. }
  253. /**
  254. * Sets the content of the cell to the provided html. All previous
  255. * content is discarded and the cell type is set to
  256. * {@link GridStaticCellType#HTML}.
  257. *
  258. * @param html
  259. * The html content of the cell
  260. */
  261. public void setHtml(String html) {
  262. this.content = html;
  263. this.type = GridStaticCellType.HTML;
  264. section.requestSectionRefresh();
  265. }
  266. /**
  267. * Returns the widget in the cell.
  268. *
  269. * @throws IllegalStateException
  270. * if the cell is not {@link GridStaticCellType#WIDGET}
  271. *
  272. * @return the widget in the cell
  273. */
  274. public Widget getWidget() {
  275. if (type != GridStaticCellType.WIDGET) {
  276. throw new IllegalStateException(
  277. "Cannot fetch Widget from a cell with type " + type);
  278. }
  279. return (Widget) content;
  280. }
  281. /**
  282. * Set widget as the content of the cell. The type of the cell
  283. * becomes {@link GridStaticCellType#WIDGET}. All previous content
  284. * is discarded.
  285. *
  286. * @param widget
  287. * The widget to add to the cell. Should not be
  288. * previously attached anywhere (widget.getParent ==
  289. * null).
  290. */
  291. public void setWidget(Widget widget) {
  292. this.content = widget;
  293. this.type = GridStaticCellType.WIDGET;
  294. section.requestSectionRefresh();
  295. }
  296. /**
  297. * Returns the type of the cell.
  298. *
  299. * @return the type of content the cell contains.
  300. */
  301. public GridStaticCellType getType() {
  302. return type;
  303. }
  304. /**
  305. * Returns the custom style name for this cell.
  306. *
  307. * @return the style name or null if no style name has been set
  308. */
  309. public String getStyleName() {
  310. return styleName;
  311. }
  312. /**
  313. * Sets a custom style name for this cell.
  314. *
  315. * @param styleName
  316. * the style name to set or null to not use any style
  317. * name
  318. */
  319. public void setStyleName(String styleName) {
  320. this.styleName = styleName;
  321. section.requestSectionRefresh();
  322. }
  323. }
  324. /**
  325. * Abstract base class for Grid header and footer rows.
  326. *
  327. * @param <CELLTYPE>
  328. * the type of the cells in the row
  329. */
  330. abstract static class StaticRow<CELLTYPE extends StaticCell> {
  331. private Map<GridColumn<?, ?>, CELLTYPE> cells = new HashMap<GridColumn<?, ?>, CELLTYPE>();
  332. private StaticSection<?> section;
  333. /**
  334. * Map from set of spanned columns to cell meta data.
  335. */
  336. private Map<Set<GridColumn<?, ?>>, CELLTYPE> cellGroups = new HashMap<Set<GridColumn<?, ?>>, CELLTYPE>();
  337. /**
  338. * A custom style name for the row or null if none is set.
  339. */
  340. private String styleName = null;
  341. /**
  342. * Returns the cell on given GridColumn. If the column is merged
  343. * returned cell is the cell for the whole group.
  344. *
  345. * @param column
  346. * the column in grid
  347. * @return the cell on given column, merged cell for merged columns,
  348. * null if not found
  349. */
  350. public CELLTYPE getCell(GridColumn<?, ?> column) {
  351. Set<GridColumn<?, ?>> cellGroup = getCellGroupForColumn(column);
  352. if (cellGroup != null) {
  353. return cellGroups.get(cellGroup);
  354. }
  355. return cells.get(column);
  356. }
  357. /**
  358. * Merges columns cells in a row
  359. *
  360. * @param columns
  361. * the columns which header should be merged
  362. * @return the remaining visible cell after the merge, or the cell
  363. * on first column if all are hidden
  364. */
  365. public CELLTYPE join(GridColumn<?, ?>... columns) {
  366. if (columns.length <= 1) {
  367. throw new IllegalArgumentException(
  368. "You can't merge less than 2 columns together.");
  369. }
  370. HashSet<GridColumn<?, ?>> columnGroup = new HashSet<GridColumn<?, ?>>();
  371. for (GridColumn<?, ?> column : columns) {
  372. if (!cells.containsKey(column)) {
  373. throw new IllegalArgumentException(
  374. "Given column does not exists on row " + column);
  375. } else if (getCellGroupForColumn(column) != null) {
  376. throw new IllegalStateException(
  377. "Column is already in a group.");
  378. }
  379. columnGroup.add(column);
  380. }
  381. CELLTYPE joinedCell = createCell();
  382. cellGroups.put(columnGroup, joinedCell);
  383. joinedCell.setSection(getSection());
  384. calculateColspans();
  385. return joinedCell;
  386. }
  387. /**
  388. * Merges columns cells in a row
  389. *
  390. * @param cells
  391. * The cells to merge. Must be from the same row.
  392. * @return The remaining visible cell after the merge, or the first
  393. * cell if all columns are hidden
  394. */
  395. public CELLTYPE join(CELLTYPE... cells) {
  396. if (cells.length <= 1) {
  397. throw new IllegalArgumentException(
  398. "You can't merge less than 2 cells together.");
  399. }
  400. GridColumn<?, ?>[] columns = new GridColumn<?, ?>[cells.length];
  401. int j = 0;
  402. for (GridColumn<?, ?> column : this.cells.keySet()) {
  403. CELLTYPE cell = this.cells.get(column);
  404. if (!this.cells.containsValue(cells[j])) {
  405. throw new IllegalArgumentException(
  406. "Given cell does not exists on row");
  407. } else if (cell.equals(cells[j])) {
  408. columns[j++] = column;
  409. if (j == cells.length) {
  410. break;
  411. }
  412. }
  413. }
  414. return join(columns);
  415. }
  416. private Set<GridColumn<?, ?>> getCellGroupForColumn(
  417. GridColumn<?, ?> column) {
  418. for (Set<GridColumn<?, ?>> group : cellGroups.keySet()) {
  419. if (group.contains(column)) {
  420. return group;
  421. }
  422. }
  423. return null;
  424. }
  425. void calculateColspans() {
  426. // Reset all cells
  427. for (CELLTYPE cell : this.cells.values()) {
  428. cell.setColspan(1);
  429. }
  430. List<GridColumn<?, ?>> columnOrder = new ArrayList<GridColumn<?, ?>>(
  431. section.grid.getColumns());
  432. // Set colspan for grouped cells
  433. for (Set<GridColumn<?, ?>> group : cellGroups.keySet()) {
  434. if (!checkCellGroupAndOrder(columnOrder, group)) {
  435. cellGroups.get(group).setColspan(1);
  436. } else {
  437. int colSpan = group.size();
  438. cellGroups.get(group).setColspan(colSpan);
  439. }
  440. }
  441. }
  442. private boolean checkCellGroupAndOrder(
  443. List<GridColumn<?, ?>> columnOrder,
  444. Set<GridColumn<?, ?>> cellGroup) {
  445. if (!columnOrder.containsAll(cellGroup)) {
  446. return false;
  447. }
  448. for (int i = 0; i < columnOrder.size(); ++i) {
  449. if (!cellGroup.contains(columnOrder.get(i))) {
  450. continue;
  451. }
  452. for (int j = 1; j < cellGroup.size(); ++j) {
  453. if (!cellGroup.contains(columnOrder.get(i + j))) {
  454. return false;
  455. }
  456. }
  457. return true;
  458. }
  459. return false;
  460. }
  461. protected void addCell(GridColumn<?, ?> column) {
  462. CELLTYPE cell = createCell();
  463. cell.setSection(getSection());
  464. cells.put(column, cell);
  465. }
  466. protected void removeCell(GridColumn<?, ?> column) {
  467. cells.remove(column);
  468. }
  469. protected abstract CELLTYPE createCell();
  470. protected StaticSection<?> getSection() {
  471. return section;
  472. }
  473. protected void setSection(StaticSection<?> section) {
  474. this.section = section;
  475. }
  476. /**
  477. * Returns the custom style name for this row.
  478. *
  479. * @return the style name or null if no style name has been set
  480. */
  481. public String getStyleName() {
  482. return styleName;
  483. }
  484. /**
  485. * Sets a custom style name for this row.
  486. *
  487. * @param styleName
  488. * the style name to set or null to not use any style
  489. * name
  490. */
  491. public void setStyleName(String styleName) {
  492. this.styleName = styleName;
  493. section.requestSectionRefresh();
  494. }
  495. }
  496. private Grid<?> grid;
  497. private List<ROWTYPE> rows = new ArrayList<ROWTYPE>();
  498. private boolean visible = true;
  499. /**
  500. * Creates and returns a new instance of the row type.
  501. *
  502. * @return the created row
  503. */
  504. protected abstract ROWTYPE createRow();
  505. /**
  506. * Informs the grid that this section should be re-rendered.
  507. * <p>
  508. * <b>Note</b> that re-render means calling update() on each cell,
  509. * preAttach()/postAttach()/preDetach()/postDetach() is not called as
  510. * the cells are not removed from the DOM.
  511. */
  512. protected abstract void requestSectionRefresh();
  513. /**
  514. * Sets the visibility of the whole section.
  515. *
  516. * @param visible
  517. * true to show this section, false to hide
  518. */
  519. public void setVisible(boolean visible) {
  520. this.visible = visible;
  521. requestSectionRefresh();
  522. }
  523. /**
  524. * Returns the visibility of this section.
  525. *
  526. * @return true if visible, false otherwise.
  527. */
  528. public boolean isVisible() {
  529. return visible;
  530. }
  531. /**
  532. * Inserts a new row at the given position. Shifts the row currently at
  533. * that position and any subsequent rows down (adds one to their
  534. * indices).
  535. *
  536. * @param index
  537. * the position at which to insert the row
  538. * @return the new row
  539. *
  540. * @throws IndexOutOfBoundsException
  541. * if the index is out of bounds
  542. * @see #appendRow()
  543. * @see #prependRow()
  544. * @see #removeRow(int)
  545. * @see #removeRow(StaticRow)
  546. */
  547. public ROWTYPE addRowAt(int index) {
  548. ROWTYPE row = createRow();
  549. row.setSection(this);
  550. for (int i = 0; i < getGrid().getColumnCount(); ++i) {
  551. row.addCell(grid.getColumn(i));
  552. }
  553. rows.add(index, row);
  554. requestSectionRefresh();
  555. return row;
  556. }
  557. /**
  558. * Adds a new row at the top of this section.
  559. *
  560. * @return the new row
  561. * @see #appendRow()
  562. * @see #addRowAt(int)
  563. * @see #removeRow(int)
  564. * @see #removeRow(StaticRow)
  565. */
  566. public ROWTYPE prependRow() {
  567. return addRowAt(0);
  568. }
  569. /**
  570. * Adds a new row at the bottom of this section.
  571. *
  572. * @return the new row
  573. * @see #prependRow()
  574. * @see #addRowAt(int)
  575. * @see #removeRow(int)
  576. * @see #removeRow(StaticRow)
  577. */
  578. public ROWTYPE appendRow() {
  579. return addRowAt(rows.size());
  580. }
  581. /**
  582. * Removes the row at the given position.
  583. *
  584. * @param index
  585. * the position of the row
  586. *
  587. * @throws IndexOutOfBoundsException
  588. * if the index is out of bounds
  589. * @see #addRowAt(int)
  590. * @see #appendRow()
  591. * @see #prependRow()
  592. * @see #removeRow(StaticRow)
  593. */
  594. public void removeRow(int index) {
  595. rows.remove(index);
  596. requestSectionRefresh();
  597. }
  598. /**
  599. * Removes the given row from the section.
  600. *
  601. * @param row
  602. * the row to be removed
  603. *
  604. * @throws IllegalArgumentException
  605. * if the row does not exist in this section
  606. * @see #addRowAt(int)
  607. * @see #appendRow()
  608. * @see #prependRow()
  609. * @see #removeRow(int)
  610. */
  611. public void removeRow(ROWTYPE row) {
  612. try {
  613. removeRow(rows.indexOf(row));
  614. } catch (IndexOutOfBoundsException e) {
  615. throw new IllegalArgumentException(
  616. "Section does not contain the given row");
  617. }
  618. }
  619. /**
  620. * Returns the row at the given position.
  621. *
  622. * @param index
  623. * the position of the row
  624. * @return the row with the given index
  625. *
  626. * @throws IndexOutOfBoundsException
  627. * if the index is out of bounds
  628. */
  629. public ROWTYPE getRow(int index) {
  630. try {
  631. return rows.get(index);
  632. } catch (IndexOutOfBoundsException e) {
  633. throw new IllegalArgumentException("Row with index " + index
  634. + " does not exist");
  635. }
  636. }
  637. /**
  638. * Returns the number of rows in this section.
  639. *
  640. * @return the number of rows
  641. */
  642. public int getRowCount() {
  643. return rows.size();
  644. }
  645. protected List<ROWTYPE> getRows() {
  646. return rows;
  647. }
  648. protected int getVisibleRowCount() {
  649. return isVisible() ? getRowCount() : 0;
  650. }
  651. protected void addColumn(GridColumn<?, ?> column) {
  652. for (ROWTYPE row : rows) {
  653. row.addCell(column);
  654. }
  655. }
  656. protected void removeColumn(GridColumn<?, ?> column) {
  657. for (ROWTYPE row : rows) {
  658. row.removeCell(column);
  659. }
  660. }
  661. protected void setGrid(Grid<?> grid) {
  662. this.grid = grid;
  663. }
  664. protected Grid<?> getGrid() {
  665. assert grid != null;
  666. return grid;
  667. }
  668. }
  669. /**
  670. * Represents the header section of a Grid. A header consists of a single
  671. * header row containing a header cell for each column. Each cell has a
  672. * simple textual caption.
  673. */
  674. protected static class Header extends StaticSection<HeaderRow> {
  675. private HeaderRow defaultRow;
  676. private boolean markAsDirty = false;
  677. @Override
  678. public void removeRow(int index) {
  679. HeaderRow removedRow = getRow(index);
  680. super.removeRow(index);
  681. if (removedRow == defaultRow) {
  682. setDefaultRow(null);
  683. }
  684. }
  685. /**
  686. * Sets the default row of this header. The default row is a special
  687. * header row providing a user interface for sorting columns.
  688. *
  689. * @param row
  690. * the new default row, or null for no default row
  691. *
  692. * @throws IllegalArgumentException
  693. * this header does not contain the row
  694. */
  695. public void setDefaultRow(HeaderRow row) {
  696. if (row == defaultRow) {
  697. return;
  698. }
  699. if (row != null && !getRows().contains(row)) {
  700. throw new IllegalArgumentException(
  701. "Cannot set a default row that does not exist in the container");
  702. }
  703. if (defaultRow != null) {
  704. defaultRow.setDefault(false);
  705. }
  706. if (row != null) {
  707. row.setDefault(true);
  708. }
  709. defaultRow = row;
  710. requestSectionRefresh();
  711. }
  712. /**
  713. * Returns the current default row of this header. The default row is a
  714. * special header row providing a user interface for sorting columns.
  715. *
  716. * @return the default row or null if no default row set
  717. */
  718. public HeaderRow getDefaultRow() {
  719. return defaultRow;
  720. }
  721. @Override
  722. protected HeaderRow createRow() {
  723. return new HeaderRow();
  724. }
  725. @Override
  726. protected void requestSectionRefresh() {
  727. markAsDirty = true;
  728. /*
  729. * Defer the refresh so if we multiple times call refreshSection()
  730. * (for example when updating cell values) we only get one actual
  731. * refresh in the end.
  732. */
  733. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  734. @Override
  735. public void execute() {
  736. if (markAsDirty) {
  737. markAsDirty = false;
  738. getGrid().refreshHeader();
  739. }
  740. }
  741. });
  742. }
  743. /**
  744. * Returns the events consumed by the header
  745. *
  746. * @return a collection of BrowserEvents
  747. */
  748. public Collection<String> getConsumedEvents() {
  749. return Arrays.asList(BrowserEvents.TOUCHSTART,
  750. BrowserEvents.TOUCHMOVE, BrowserEvents.TOUCHEND,
  751. BrowserEvents.TOUCHCANCEL, BrowserEvents.CLICK);
  752. }
  753. }
  754. /**
  755. * A single row in a grid header section.
  756. *
  757. */
  758. public static class HeaderRow extends StaticSection.StaticRow<HeaderCell> {
  759. private boolean isDefault = false;
  760. protected void setDefault(boolean isDefault) {
  761. this.isDefault = isDefault;
  762. }
  763. public boolean isDefault() {
  764. return isDefault;
  765. }
  766. @Override
  767. protected HeaderCell createCell() {
  768. return new HeaderCell();
  769. }
  770. }
  771. /**
  772. * A single cell in a grid header row. Has a textual caption.
  773. *
  774. */
  775. public static class HeaderCell extends StaticSection.StaticCell {
  776. }
  777. /**
  778. * Represents the footer section of a Grid. The footer is always empty.
  779. */
  780. protected static class Footer extends StaticSection<FooterRow> {
  781. private boolean markAsDirty = false;
  782. @Override
  783. protected FooterRow createRow() {
  784. return new FooterRow();
  785. }
  786. @Override
  787. protected void requestSectionRefresh() {
  788. markAsDirty = true;
  789. /*
  790. * Defer the refresh so if we multiple times call refreshSection()
  791. * (for example when updating cell values) we only get one actual
  792. * refresh in the end.
  793. */
  794. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
  795. @Override
  796. public void execute() {
  797. if (markAsDirty) {
  798. markAsDirty = false;
  799. getGrid().refreshFooter();
  800. }
  801. }
  802. });
  803. }
  804. }
  805. /**
  806. * A single cell in a grid Footer row. Has a textual caption.
  807. *
  808. */
  809. public static class FooterCell extends StaticSection.StaticCell {
  810. }
  811. /**
  812. * A single row in a grid Footer section.
  813. *
  814. */
  815. public static class FooterRow extends StaticSection.StaticRow<FooterCell> {
  816. @Override
  817. protected FooterCell createCell() {
  818. return new FooterCell();
  819. }
  820. }
  821. public static abstract class AbstractGridKeyEvent<HANDLER extends AbstractGridKeyEventHandler>
  822. extends KeyEvent<HANDLER> {
  823. /**
  824. * Enum describing different sections of Grid.
  825. */
  826. public enum GridSection {
  827. HEADER, BODY, FOOTER
  828. }
  829. private Grid<?> grid;
  830. protected Cell focusedCell;
  831. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  832. getBrowserEventType(), this);
  833. public AbstractGridKeyEvent(Grid<?> grid) {
  834. this.grid = grid;
  835. }
  836. protected abstract String getBrowserEventType();
  837. /**
  838. * Gets the Grid instance for this event.
  839. *
  840. * @return grid
  841. */
  842. public Grid<?> getGrid() {
  843. return grid;
  844. }
  845. /**
  846. * Gets the focused cell for this event.
  847. *
  848. * @return focused cell
  849. */
  850. public Cell getFocusedCell() {
  851. return focusedCell;
  852. }
  853. @Override
  854. protected void dispatch(HANDLER handler) {
  855. EventTarget target = getNativeEvent().getEventTarget();
  856. if (Element.is(target)
  857. && !grid.isElementInChildWidget(Element.as(target))) {
  858. focusedCell = grid.cellFocusHandler.getFocusedCell();
  859. GridSection section = GridSection.FOOTER;
  860. final RowContainer container = grid.cellFocusHandler.containerWithFocus;
  861. if (container == grid.escalator.getHeader()) {
  862. section = GridSection.HEADER;
  863. } else if (container == grid.escalator.getBody()) {
  864. section = GridSection.BODY;
  865. }
  866. doDispatch(handler, section);
  867. }
  868. }
  869. protected abstract void doDispatch(HANDLER handler, GridSection section);
  870. @Override
  871. public Type<HANDLER> getAssociatedType() {
  872. return associatedType;
  873. }
  874. }
  875. public static abstract class AbstractGridMouseEvent<HANDLER extends AbstractGridMouseEventHandler>
  876. extends MouseEvent<HANDLER> {
  877. /**
  878. * Enum describing different sections of Grid.
  879. */
  880. public enum GridSection {
  881. HEADER, BODY, FOOTER
  882. }
  883. private Grid<?> grid;
  884. protected Cell targetCell;
  885. private final Type<HANDLER> associatedType = new Type<HANDLER>(
  886. getBrowserEventType(), this);
  887. public AbstractGridMouseEvent(Grid<?> grid) {
  888. this.grid = grid;
  889. }
  890. protected abstract String getBrowserEventType();
  891. /**
  892. * Gets the Grid instance for this event.
  893. *
  894. * @return grid
  895. */
  896. public Grid<?> getGrid() {
  897. return grid;
  898. }
  899. /**
  900. * Gets the target cell for this event.
  901. *
  902. * @return target cell
  903. */
  904. public Cell getTargetCell() {
  905. return targetCell;
  906. }
  907. @Override
  908. protected void dispatch(HANDLER handler) {
  909. EventTarget target = getNativeEvent().getEventTarget();
  910. if (!Element.is(target)) {
  911. // Target is not an element
  912. return;
  913. }
  914. Element targetElement = Element.as(target);
  915. if (grid.isElementInChildWidget(targetElement)) {
  916. // Target is some widget inside of Grid
  917. return;
  918. }
  919. final RowContainer container = grid.escalator
  920. .findRowContainer(targetElement);
  921. if (container == null) {
  922. // No container for given element
  923. return;
  924. }
  925. targetCell = container.getCell(targetElement);
  926. if (targetCell == null) {
  927. // Is not a cell in given container.
  928. return;
  929. }
  930. GridSection section = GridSection.FOOTER;
  931. if (container == grid.escalator.getHeader()) {
  932. section = GridSection.HEADER;
  933. } else if (container == grid.escalator.getBody()) {
  934. section = GridSection.BODY;
  935. }
  936. doDispatch(handler, section);
  937. }
  938. protected abstract void doDispatch(HANDLER handler, GridSection section);
  939. @Override
  940. public Type<HANDLER> getAssociatedType() {
  941. return associatedType;
  942. }
  943. }
  944. private static final String CUSTOM_STYLE_PROPERTY_NAME = "customStyle";
  945. private GridKeyDownEvent keyDown = new GridKeyDownEvent(this);
  946. private GridKeyUpEvent keyUp = new GridKeyUpEvent(this);
  947. private GridKeyPressEvent keyPress = new GridKeyPressEvent(this);
  948. private GridClickEvent clickEvent = new GridClickEvent(this);
  949. private class CellFocusHandler {
  950. private RowContainer containerWithFocus = escalator.getBody();
  951. private int rowWithFocus = 0;
  952. private Range cellFocusRange = Range.withLength(0, 1);
  953. private int lastFocusedBodyRow = 0;
  954. private int lastFocusedHeaderRow = 0;
  955. private int lastFocusedFooterRow = 0;
  956. private TableCellElement cellWithFocusStyle = null;
  957. private TableRowElement rowWithFocusStyle = null;
  958. public CellFocusHandler() {
  959. sinkEvents(getNavigationEvents());
  960. }
  961. private Cell getFocusedCell() {
  962. return new Cell(rowWithFocus, cellFocusRange.getStart(),
  963. cellWithFocusStyle);
  964. }
  965. /**
  966. * Sets style names for given cell when needed.
  967. */
  968. public void updateFocusedCellStyle(FlyweightCell cell,
  969. RowContainer cellContainer) {
  970. int cellRow = cell.getRow();
  971. int cellColumn = cell.getColumn();
  972. int colSpan = cell.getColSpan();
  973. boolean columnHasFocus = Range.withLength(cellColumn, colSpan)
  974. .intersects(cellFocusRange);
  975. if (cellContainer == containerWithFocus) {
  976. // Cell is in the current container
  977. if (cellRow == rowWithFocus && columnHasFocus) {
  978. if (cellWithFocusStyle != cell.getElement()) {
  979. // Cell is correct but it does not have focused style
  980. if (cellWithFocusStyle != null) {
  981. // Remove old focus style
  982. setStyleName(cellWithFocusStyle,
  983. cellFocusStyleName, false);
  984. }
  985. cellWithFocusStyle = cell.getElement();
  986. // Add focus style to correct cell.
  987. setStyleName(cellWithFocusStyle, cellFocusStyleName,
  988. true);
  989. }
  990. } else if (cellWithFocusStyle == cell.getElement()) {
  991. // Due to escalator reusing cells, a new cell has the same
  992. // element but is not the focused cell.
  993. setStyleName(cellWithFocusStyle, cellFocusStyleName, false);
  994. cellWithFocusStyle = null;
  995. }
  996. }
  997. if (cellContainer == escalator.getHeader()
  998. || cellContainer == escalator.getFooter()) {
  999. // Correct header and footer column also needs highlighting
  1000. setStyleName(cell.getElement(), headerFooterFocusStyleName,
  1001. columnHasFocus);
  1002. }
  1003. }
  1004. /**
  1005. * Sets focus style for the given row if needed.
  1006. *
  1007. * @param row
  1008. * a row object
  1009. */
  1010. public void updateFocusedRowStyle(Row row) {
  1011. if (rowWithFocus == row.getRow()
  1012. && containerWithFocus == escalator.getBody()) {
  1013. if (row.getElement() != rowWithFocusStyle) {
  1014. // Row should have focus style but does not have it.
  1015. if (rowWithFocusStyle != null) {
  1016. setStyleName(rowWithFocusStyle, rowFocusStyleName,
  1017. false);
  1018. }
  1019. rowWithFocusStyle = row.getElement();
  1020. setStyleName(rowWithFocusStyle, rowFocusStyleName, true);
  1021. }
  1022. } else if (rowWithFocusStyle == row.getElement()
  1023. || (containerWithFocus != escalator.getBody() && rowWithFocusStyle != null)) {
  1024. // Remove focus style.
  1025. setStyleName(rowWithFocusStyle, rowFocusStyleName, false);
  1026. rowWithFocusStyle = null;
  1027. }
  1028. }
  1029. /**
  1030. * Sets the currently focused.
  1031. *
  1032. * @param row
  1033. * the index of the row having focus
  1034. * @param column
  1035. * the index of the column having focus
  1036. * @param container
  1037. * the row container having focus
  1038. */
  1039. private void setCellFocus(int row, int column, RowContainer container) {
  1040. if (row == rowWithFocus && cellFocusRange.contains(column)
  1041. && container == this.containerWithFocus) {
  1042. refreshRow(rowWithFocus);
  1043. return;
  1044. }
  1045. int oldRow = rowWithFocus;
  1046. rowWithFocus = row;
  1047. Range oldRange = cellFocusRange;
  1048. if (container == escalator.getBody()) {
  1049. scrollToRow(rowWithFocus);
  1050. cellFocusRange = Range.withLength(column, 1);
  1051. } else {
  1052. int i = 0;
  1053. Element cell = container.getRowElement(rowWithFocus)
  1054. .getFirstChildElement();
  1055. do {
  1056. int colSpan = cell
  1057. .getPropertyInt(FlyweightCell.COLSPAN_ATTR);
  1058. Range cellRange = Range.withLength(i, colSpan);
  1059. if (cellRange.contains(column)) {
  1060. cellFocusRange = cellRange;
  1061. break;
  1062. }
  1063. cell = cell.getNextSiblingElement();
  1064. ++i;
  1065. } while (cell != null);
  1066. }
  1067. if (column >= escalator.getColumnConfiguration()
  1068. .getFrozenColumnCount()) {
  1069. escalator.scrollToColumn(column, ScrollDestination.ANY, 10);
  1070. }
  1071. if (this.containerWithFocus == container) {
  1072. if (oldRange.equals(cellFocusRange) && oldRow != rowWithFocus) {
  1073. refreshRow(oldRow);
  1074. } else {
  1075. refreshHeader();
  1076. refreshFooter();
  1077. }
  1078. } else {
  1079. RowContainer oldContainer = this.containerWithFocus;
  1080. this.containerWithFocus = container;
  1081. if (oldContainer == escalator.getBody()) {
  1082. lastFocusedBodyRow = oldRow;
  1083. } else if (oldContainer == escalator.getHeader()) {
  1084. lastFocusedHeaderRow = oldRow;
  1085. } else {
  1086. lastFocusedFooterRow = oldRow;
  1087. }
  1088. if (!oldRange.equals(cellFocusRange)) {
  1089. refreshHeader();
  1090. refreshFooter();
  1091. if (oldContainer == escalator.getBody()) {
  1092. oldContainer.refreshRows(oldRow, 1);
  1093. }
  1094. } else {
  1095. oldContainer.refreshRows(oldRow, 1);
  1096. }
  1097. }
  1098. refreshRow(rowWithFocus);
  1099. }
  1100. /**
  1101. * Sets focus on a cell.
  1102. *
  1103. * <p>
  1104. * <em>Note</em>: cell focus is not the same as JavaScript's
  1105. * {@code document.activeElement}.
  1106. *
  1107. * @param cell
  1108. * a cell object
  1109. */
  1110. public void setCellFocus(Cell cell) {
  1111. setCellFocus(cell.getRow(), cell.getColumn(),
  1112. escalator.findRowContainer(cell.getElement()));
  1113. }
  1114. /**
  1115. * Gets list of events that can be used for cell focusing.
  1116. *
  1117. * @return list of navigation related event types
  1118. */
  1119. public Collection<String> getNavigationEvents() {
  1120. return Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.CLICK);
  1121. }
  1122. /**
  1123. * Handle events that can move the cell focus.
  1124. */
  1125. public void handleNavigationEvent(Event event, Cell cell) {
  1126. if (event.getType().equals(BrowserEvents.CLICK)) {
  1127. setCellFocus(cell);
  1128. // Grid should have focus when clicked.
  1129. getElement().focus();
  1130. } else if (event.getType().equals(BrowserEvents.KEYDOWN)) {
  1131. int newRow = rowWithFocus;
  1132. RowContainer newContainer = containerWithFocus;
  1133. int newColumn = cellFocusRange.getStart();
  1134. switch (event.getKeyCode()) {
  1135. case KeyCodes.KEY_DOWN:
  1136. ++newRow;
  1137. break;
  1138. case KeyCodes.KEY_UP:
  1139. --newRow;
  1140. break;
  1141. case KeyCodes.KEY_RIGHT:
  1142. if (cellFocusRange.getEnd() >= getColumns().size()) {
  1143. return;
  1144. }
  1145. newColumn = cellFocusRange.getEnd();
  1146. break;
  1147. case KeyCodes.KEY_LEFT:
  1148. if (newColumn == 0) {
  1149. return;
  1150. }
  1151. --newColumn;
  1152. break;
  1153. case KeyCodes.KEY_TAB:
  1154. if (event.getShiftKey()) {
  1155. newContainer = getPreviousContainer(containerWithFocus);
  1156. } else {
  1157. newContainer = getNextContainer(containerWithFocus);
  1158. }
  1159. if (newContainer == containerWithFocus) {
  1160. return;
  1161. }
  1162. break;
  1163. default:
  1164. return;
  1165. }
  1166. if (newContainer != containerWithFocus) {
  1167. if (newContainer == escalator.getBody()) {
  1168. newRow = lastFocusedBodyRow;
  1169. } else if (newContainer == escalator.getHeader()) {
  1170. newRow = lastFocusedHeaderRow;
  1171. } else {
  1172. newRow = lastFocusedFooterRow;
  1173. }
  1174. } else if (newRow < 0) {
  1175. newContainer = getPreviousContainer(newContainer);
  1176. if (newContainer == containerWithFocus) {
  1177. newRow = 0;
  1178. } else if (newContainer == escalator.getBody()) {
  1179. newRow = getLastVisibleRowIndex();
  1180. } else {
  1181. newRow = newContainer.getRowCount() - 1;
  1182. }
  1183. } else if (newRow >= containerWithFocus.getRowCount()) {
  1184. newContainer = getNextContainer(newContainer);
  1185. if (newContainer == containerWithFocus) {
  1186. newRow = containerWithFocus.getRowCount() - 1;
  1187. } else if (newContainer == escalator.getBody()) {
  1188. newRow = getFirstVisibleRowIndex();
  1189. } else {
  1190. newRow = 0;
  1191. }
  1192. }
  1193. if (newContainer.getRowCount() == 0) {
  1194. /*
  1195. * There are no rows in the container. Can't change the
  1196. * focused cell.
  1197. */
  1198. return;
  1199. }
  1200. event.preventDefault();
  1201. event.stopPropagation();
  1202. setCellFocus(newRow, newColumn, newContainer);
  1203. }
  1204. }
  1205. private RowContainer getPreviousContainer(RowContainer current) {
  1206. if (current == escalator.getFooter()) {
  1207. current = escalator.getBody();
  1208. } else if (current == escalator.getBody()) {
  1209. current = escalator.getHeader();
  1210. } else {
  1211. return current;
  1212. }
  1213. if (current.getRowCount() == 0) {
  1214. return getPreviousContainer(current);
  1215. }
  1216. return current;
  1217. }
  1218. private RowContainer getNextContainer(RowContainer current) {
  1219. if (current == escalator.getHeader()) {
  1220. current = escalator.getBody();
  1221. } else if (current == escalator.getBody()) {
  1222. current = escalator.getFooter();
  1223. } else {
  1224. return current;
  1225. }
  1226. if (current.getRowCount() == 0) {
  1227. return getNextContainer(current);
  1228. }
  1229. return current;
  1230. }
  1231. private void refreshRow(int row) {
  1232. containerWithFocus.refreshRows(row, 1);
  1233. }
  1234. /**
  1235. * Offsets the focused cell's range.
  1236. *
  1237. * @param offset
  1238. * offset for fixing focused cell's range
  1239. */
  1240. public void offsetRangeBy(int offset) {
  1241. cellFocusRange = cellFocusRange.offsetBy(offset);
  1242. }
  1243. /**
  1244. * Informs {@link CellFocusHandler} that certain range of rows has been
  1245. * added to the Grid body. {@link CellFocusHandler} will fix indices
  1246. * accordingly.
  1247. *
  1248. * @param added
  1249. * a range of added rows
  1250. */
  1251. public void rowsAddedToBody(Range added) {
  1252. boolean bodyHasFocus = (containerWithFocus == escalator.getBody());
  1253. boolean insertionIsAboveFocusedCell = (added.getStart() <= rowWithFocus);
  1254. if (bodyHasFocus && insertionIsAboveFocusedCell) {
  1255. setCellFocus(rowWithFocus + added.length(),
  1256. cellFocusRange.getStart(), containerWithFocus);
  1257. }
  1258. }
  1259. /**
  1260. * Informs {@link CellFocusHandler} that certain range of rows has been
  1261. * removed from the Grid body. {@link CellFocusHandler} will fix indices
  1262. * accordingly.
  1263. *
  1264. * @param removed
  1265. * a range of removed rows
  1266. */
  1267. public void rowsRemovedFromBody(Range removed) {
  1268. int focusedColumn = cellFocusRange.getStart();
  1269. if (containerWithFocus != escalator.getBody()) {
  1270. return;
  1271. } else if (!removed.contains(rowWithFocus)) {
  1272. if (removed.getStart() > rowWithFocus) {
  1273. return;
  1274. }
  1275. setCellFocus(rowWithFocus - removed.length(), focusedColumn,
  1276. containerWithFocus);
  1277. } else {
  1278. if (containerWithFocus.getRowCount() > removed.getEnd()) {
  1279. setCellFocus(removed.getStart(), focusedColumn,
  1280. containerWithFocus);
  1281. } else if (removed.getStart() > 0) {
  1282. setCellFocus(removed.getStart() - 1, focusedColumn,
  1283. containerWithFocus);
  1284. } else {
  1285. if (escalator.getHeader().getRowCount() > 0) {
  1286. setCellFocus(lastFocusedHeaderRow, focusedColumn,
  1287. escalator.getHeader());
  1288. } else if (escalator.getFooter().getRowCount() > 0) {
  1289. setCellFocus(lastFocusedFooterRow, focusedColumn,
  1290. escalator.getFooter());
  1291. }
  1292. }
  1293. }
  1294. }
  1295. }
  1296. public final class SelectionColumn extends GridColumn<Boolean, T> {
  1297. private boolean initDone = false;
  1298. SelectionColumn(final Renderer<Boolean> selectColumnRenderer) {
  1299. super(selectColumnRenderer);
  1300. }
  1301. void initDone() {
  1302. if (getSelectionModel() instanceof SelectionModel.Multi
  1303. && header.getDefaultRow() != null) {
  1304. /*
  1305. * TODO: Currently the select all check box is shown when multi
  1306. * selection is in use. This might result in malfunctions if no
  1307. * SelectAllHandlers are present.
  1308. *
  1309. * Later on this could be fixed so that it check such handlers
  1310. * exist.
  1311. */
  1312. final SelectionModel.Multi<T> model = (Multi<T>) getSelectionModel();
  1313. final CheckBox checkBox = new CheckBox();
  1314. checkBox.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
  1315. @Override
  1316. public void onValueChange(ValueChangeEvent<Boolean> event) {
  1317. if (event.getValue()) {
  1318. fireEvent(new SelectAllEvent<T>(model));
  1319. } else {
  1320. model.deselectAll();
  1321. }
  1322. }
  1323. });
  1324. header.getDefaultRow().getCell(this).setWidget(checkBox);
  1325. }
  1326. setWidth(-1);
  1327. initDone = true;
  1328. }
  1329. @Override
  1330. public GridColumn<Boolean, T> setWidth(int pixels) {
  1331. if (pixels != getWidth() && initDone) {
  1332. throw new UnsupportedOperationException("The selection "
  1333. + "column cannot be modified after init");
  1334. } else {
  1335. super.setWidth(pixels);
  1336. }
  1337. return this;
  1338. }
  1339. @Override
  1340. public Boolean getValue(T row) {
  1341. return Boolean.valueOf(isSelected(row));
  1342. }
  1343. }
  1344. /**
  1345. * Helper class for performing sorting through the user interface. Controls
  1346. * the sort() method, reporting USER as the event originator. This is a
  1347. * completely internal class, and is, as such, safe to re-name should a more
  1348. * descriptive name come to mind.
  1349. */
  1350. private final class UserSorter {
  1351. private final Timer timer;
  1352. private Cell scheduledCell;
  1353. private boolean scheduledMultisort;
  1354. private UserSorter() {
  1355. timer = new Timer() {
  1356. @Override
  1357. public void run() {
  1358. UserSorter.this.sort(scheduledCell, scheduledMultisort);
  1359. }
  1360. };
  1361. }
  1362. /**
  1363. * Toggle sorting for a cell. If the multisort parameter is set to true,
  1364. * the cell's sort order is modified as a natural part of a multi-sort
  1365. * chain. If false, the sorting order is set to ASCENDING for that
  1366. * cell's column. If that column was already the only sorted column in
  1367. * the Grid, the sort direction is flipped.
  1368. *
  1369. * @param cell
  1370. * a valid cell reference
  1371. * @param multisort
  1372. * whether the sort command should act as a multi-sort stack
  1373. * or not
  1374. */
  1375. public void sort(Cell cell, boolean multisort) {
  1376. final GridColumn<?, T> column = getColumn(cell.getColumn());
  1377. if (!column.isSortable()) {
  1378. return;
  1379. }
  1380. final SortOrder so = getSortOrder(column);
  1381. if (multisort) {
  1382. // If the sort order exists, replace existing value with its
  1383. // opposite
  1384. if (so != null) {
  1385. final int idx = sortOrder.indexOf(so);
  1386. sortOrder.set(idx, so.getOpposite());
  1387. } else {
  1388. // If it doesn't, just add a new sort order to the end of
  1389. // the list
  1390. sortOrder.add(new SortOrder(column));
  1391. }
  1392. } else {
  1393. // Since we're doing single column sorting, first clear the
  1394. // list. Then, if the sort order existed, add its opposite,
  1395. // otherwise just add a new sort value
  1396. int items = sortOrder.size();
  1397. sortOrder.clear();
  1398. if (so != null && items == 1) {
  1399. sortOrder.add(so.getOpposite());
  1400. } else {
  1401. sortOrder.add(new SortOrder(column));
  1402. }
  1403. }
  1404. // sortOrder has been changed; tell the Grid to re-sort itself by
  1405. // user request.
  1406. Grid.this.sort(SortEventOriginator.USER);
  1407. }
  1408. /**
  1409. * Perform a sort after a delay.
  1410. *
  1411. * @param delay
  1412. * delay, in milliseconds
  1413. */
  1414. public void sortAfterDelay(int delay, Cell cell, boolean multisort) {
  1415. scheduledCell = cell;
  1416. scheduledMultisort = multisort;
  1417. timer.schedule(delay);
  1418. }
  1419. /**
  1420. * Check if a delayed sort command has been issued but not yet carried
  1421. * out.
  1422. *
  1423. * @return a boolean value
  1424. */
  1425. public boolean isDelayedSortScheduled() {
  1426. return timer.isRunning();
  1427. }
  1428. /**
  1429. * Cancel a scheduled sort.
  1430. */
  1431. public void cancelDelayedSort() {
  1432. timer.cancel();
  1433. }
  1434. }
  1435. /**
  1436. * Escalator used internally by grid to render the rows
  1437. */
  1438. private Escalator escalator = GWT.create(Escalator.class);
  1439. private final Header header = GWT.create(Header.class);
  1440. private final Footer footer = GWT.create(Footer.class);
  1441. /**
  1442. * List of columns in the grid. Order defines the visible order.
  1443. */
  1444. private List<GridColumn<?, T>> columns = new ArrayList<GridColumn<?, T>>();
  1445. /**
  1446. * The datasource currently in use. <em>Note:</em> it is <code>null</code>
  1447. * on initialization, but not after that.
  1448. */
  1449. private DataSource<T> dataSource;
  1450. /**
  1451. * Currently available row range in DataSource.
  1452. */
  1453. private Range currentDataAvailable = Range.withLength(0, 0);
  1454. /**
  1455. * The number of frozen columns, 0 freezes the selection column if
  1456. * displayed, -1 also prevents selection col from freezing.
  1457. */
  1458. private int frozenColumnCount = 0;
  1459. /**
  1460. * Current sort order. The (private) sort() method reads this list to
  1461. * determine the order in which to present rows.
  1462. */
  1463. private List<SortOrder> sortOrder = new ArrayList<SortOrder>();
  1464. private Renderer<Boolean> selectColumnRenderer = null;
  1465. private SelectionColumn selectionColumn;
  1466. private String rowStripeStyleName;
  1467. private String rowHasDataStyleName;
  1468. private String rowGeneratedStylePrefix;
  1469. private String rowSelectedStyleName;
  1470. private String cellGeneratedStylePrefix;
  1471. private String cellFocusStyleName;
  1472. private String rowFocusStyleName;
  1473. private String headerFooterFocusStyleName;
  1474. /**
  1475. * Current selection model.
  1476. */
  1477. private SelectionModel<T> selectionModel;
  1478. protected final CellFocusHandler cellFocusHandler;
  1479. private final UserSorter sorter = new UserSorter();
  1480. private final EditorRow<T> editorRow = GWT.create(EditorRow.class);
  1481. private boolean dataIsBeingFetched = false;
  1482. /**
  1483. * The cell a click event originated from
  1484. * <p>
  1485. * This is a workaround to make Chrome work like Firefox. In Chrome,
  1486. * normally if you start a drag on one cell and release on:
  1487. * <ul>
  1488. * <li>that same cell, the click event is that {@code <td>}.
  1489. * <li>a cell on that same row, the click event is the parent {@code <tr>}.
  1490. * <li>a cell on another row, the click event is the table section ancestor
  1491. * ({@code <thead>}, {@code <tbody>} or {@code <tfoot>}).
  1492. * </ul>
  1493. *
  1494. * @see #onBrowserEvent(Event)
  1495. */
  1496. private Cell cellOnPrevMouseDown;
  1497. /**
  1498. * Enumeration for easy setting of selection mode.
  1499. */
  1500. public enum SelectionMode {
  1501. /**
  1502. * Shortcut for {@link SelectionModelSingle}.
  1503. */
  1504. SINGLE {
  1505. @Override
  1506. protected <T> SelectionModel<T> createModel() {
  1507. return new SelectionModelSingle<T>();
  1508. }
  1509. },
  1510. /**
  1511. * Shortcut for {@link SelectionModelMulti}.
  1512. */
  1513. MULTI {
  1514. @Override
  1515. protected <T> SelectionModel<T> createModel() {
  1516. return new SelectionModelMulti<T>();
  1517. }
  1518. },
  1519. /**
  1520. * Shortcut for {@link SelectionModelNone}.
  1521. */
  1522. NONE {
  1523. @Override
  1524. protected <T> SelectionModel<T> createModel() {
  1525. return new SelectionModelNone<T>();
  1526. }
  1527. };
  1528. protected abstract <T> SelectionModel<T> createModel();
  1529. }
  1530. /**
  1531. * Base class for grid columns internally used by the Grid. The user should
  1532. * use {@link GridColumn} when creating new columns.
  1533. *
  1534. * @param <C>
  1535. * the column type
  1536. *
  1537. * @param <T>
  1538. * the row type
  1539. */
  1540. static abstract class AbstractGridColumn<C, T> {
  1541. /**
  1542. * Default renderer for GridColumns. Renders everything into text
  1543. * through {@link Object#toString()}.
  1544. */
  1545. private final class DefaultTextRenderer implements Renderer<Object> {
  1546. boolean warned = false;
  1547. private final String DEFAULT_RENDERER_WARNING = "This column uses a dummy default TextRenderer. "
  1548. + "A more suitable renderer should be set using the setRenderer() method.";
  1549. @Override
  1550. public void render(FlyweightCell cell, Object data) {
  1551. if (!warned) {
  1552. getLogger().warning(
  1553. AbstractGridColumn.this.toString() + ": "
  1554. + DEFAULT_RENDERER_WARNING);
  1555. warned = true;
  1556. }
  1557. cell.getElement().setInnerText(data.toString());
  1558. }
  1559. }
  1560. private final class AsyncWidthAutodetectRunner {
  1561. private static final int POLLING_PERIOD_MS = 50;
  1562. private final Timer timer = new Timer() {
  1563. @Override
  1564. public void run() {
  1565. /* Detaching the column from the grid should've cancelled */
  1566. assert grid != null : "Column was detached from Grid before width autodetection completed";
  1567. /*
  1568. * setting a positive value for the width should've
  1569. * cancelled
  1570. */
  1571. assert widthUser < 0 : "User defined width is not negative (to indicate autodetection) anymore!";
  1572. if (!grid.dataIsBeingFetched) {
  1573. setWidthForce(widthUser);
  1574. } else {
  1575. timer.schedule(POLLING_PERIOD_MS);
  1576. return;
  1577. }
  1578. }
  1579. };
  1580. /**
  1581. * Schedules an width autodetection.
  1582. * <p>
  1583. * It's not done immediately in case we're retrieving some lazy
  1584. * data, that will affect the appropriate width of the cells.
  1585. */
  1586. public void reschedule() {
  1587. /*
  1588. * Check immediately. This will be _actually_ rescheduled if
  1589. * things don't work out. Otherwise, autodetectionage will
  1590. * happen.
  1591. */
  1592. timer.schedule(0);
  1593. }
  1594. public void stop() {
  1595. timer.cancel();
  1596. }
  1597. public boolean isRunning() {
  1598. return timer.isRunning();
  1599. }
  1600. }
  1601. /**
  1602. * the column is associated with
  1603. */
  1604. private Grid<T> grid;
  1605. /**
  1606. * Should the column be visible in the grid
  1607. */
  1608. private boolean visible = true;
  1609. /** Width of column in pixels as {@link #setWidth(int)} has been called */
  1610. private int widthUser = GridColumnState.DEFAULT_COLUMN_WIDTH_PX;
  1611. /**
  1612. * Renderer for rendering a value into the cell
  1613. */
  1614. private Renderer<? super C> bodyRenderer;
  1615. private boolean sortable = false;
  1616. private String headerText = "";
  1617. private final AsyncWidthAutodetectRunner asyncAutodetectWidth = new AsyncWidthAutodetectRunner();
  1618. /**
  1619. * Constructs a new column with a simple TextRenderer.
  1620. */
  1621. public AbstractGridColumn() {
  1622. setRenderer(new DefaultTextRenderer());
  1623. }
  1624. /**
  1625. * Constructs a new column with a simple TextRenderer.
  1626. *
  1627. * @param headerText
  1628. * The header text for this column
  1629. *
  1630. * @throws IllegalArgumentException
  1631. * if given header text is null
  1632. */
  1633. public AbstractGridColumn(String headerText)
  1634. throws IllegalArgumentException {
  1635. this();
  1636. setHeaderText(headerText);
  1637. }
  1638. /**
  1639. * Constructs a new column with a custom renderer.
  1640. *
  1641. * @param renderer
  1642. * The renderer to use for rendering the cells
  1643. *
  1644. * @throws IllegalArgumentException
  1645. * if given Renderer is null
  1646. */
  1647. public AbstractGridColumn(Renderer<? super C> renderer)
  1648. throws IllegalArgumentException {
  1649. setRenderer(renderer);
  1650. }
  1651. /**
  1652. * Constructs a new column with a custom renderer.
  1653. *
  1654. * @param renderer
  1655. * The renderer to use for rendering the cells
  1656. * @param headerText
  1657. * The header text for this column
  1658. *
  1659. * @throws IllegalArgumentException
  1660. * if given Renderer or header text is null
  1661. */
  1662. public AbstractGridColumn(String headerText,
  1663. Renderer<? super C> renderer) throws IllegalArgumentException {
  1664. this(renderer);
  1665. setHeaderText(headerText);
  1666. }
  1667. /**
  1668. * Internally used by the grid to set itself
  1669. *
  1670. * @param grid
  1671. */
  1672. private void setGrid(Grid<T> grid) {
  1673. if (this.grid != null && grid != null) {
  1674. // Trying to replace grid
  1675. throw new IllegalStateException("Column already is attached "
  1676. + "to a grid. Remove the column first from the grid "
  1677. + "and then add it. (in: " + toString() + ")");
  1678. }
  1679. this.grid = grid;
  1680. if (grid != null) {
  1681. updateHeader();
  1682. } else {
  1683. asyncAutodetectWidth.stop();
  1684. }
  1685. }
  1686. /**
  1687. * Sets a header text for this column.
  1688. *
  1689. * @param headerText
  1690. * The header text for this column
  1691. * @return the column itself
  1692. *
  1693. * @throws IllegalArgumentException
  1694. * if given header text is null
  1695. */
  1696. public GridColumn<C, T> setHeaderText(String headerText) {
  1697. if (headerText == null) {
  1698. throw new IllegalArgumentException(
  1699. "Header text cannot be null.");
  1700. }
  1701. if (!this.headerText.equals(headerText)) {
  1702. this.headerText = headerText;
  1703. if (grid != null) {
  1704. updateHeader();
  1705. }
  1706. }
  1707. return (GridColumn<C, T>) this;
  1708. }
  1709. private void updateHeader() {
  1710. HeaderRow row = grid.getHeader().getDefaultRow();
  1711. if (row != null) {
  1712. row.getCell((GridColumn<?, ?>) this).setText(headerText);
  1713. }
  1714. }
  1715. /**
  1716. * Returns the data that should be rendered into the cell. By default
  1717. * returning Strings and Widgets are supported. If the return type is a
  1718. * String then it will be treated as preformatted text.
  1719. * <p>
  1720. * To support other types you will need to pass a custom renderer to the
  1721. * column via the column constructor.
  1722. *
  1723. * @param row
  1724. * The row object that provides the cell content.
  1725. *
  1726. * @return The cell content
  1727. */
  1728. public abstract C getValue(T row);
  1729. /**
  1730. * The renderer to render the cell width. By default renders the data as
  1731. * a String or adds the widget into the cell if the column type is of
  1732. * widget type.
  1733. *
  1734. * @return The renderer to render the cell content with
  1735. */
  1736. public Renderer<? super C> getRenderer() {
  1737. return bodyRenderer;
  1738. }
  1739. /**
  1740. * Sets a custom {@link Renderer} for this column.
  1741. *
  1742. * @param renderer
  1743. * The renderer to use for rendering the cells
  1744. * @return the column itself
  1745. *
  1746. * @throws IllegalArgumentException
  1747. * if given Renderer is null
  1748. */
  1749. public GridColumn<C, T> setRenderer(Renderer<? super C> renderer)
  1750. throws IllegalArgumentException {
  1751. if (renderer == null) {
  1752. throw new IllegalArgumentException("Renderer cannot be null.");
  1753. }
  1754. bodyRenderer = renderer;
  1755. if (grid != null) {
  1756. grid.refreshBody();
  1757. }
  1758. return (GridColumn<C, T>) this;
  1759. }
  1760. /**
  1761. * Sets the pixel width of the column. Use a negative value for the grid
  1762. * to autosize column based on content and available space
  1763. *
  1764. * @param pixels
  1765. * the width in pixels or negative for auto sizing
  1766. * @return the column itself
  1767. */
  1768. public GridColumn<C, T> setWidth(int pixels) {
  1769. widthUser = pixels;
  1770. if (pixels < 0) {
  1771. setWidthAutodetect();
  1772. } else {
  1773. setWidthAbsolute(pixels);
  1774. }
  1775. return (GridColumn<C, T>) this;
  1776. }
  1777. private void setWidthAutodetect() {
  1778. if (grid != null) {
  1779. asyncAutodetectWidth.reschedule();
  1780. }
  1781. /*
  1782. * It's okay if the colum isn't attached to a grid immediately. The
  1783. * width will be re-set once it gets attached.
  1784. */
  1785. }
  1786. private void setWidthAbsolute(int pixels) {
  1787. asyncAutodetectWidth.stop();
  1788. if (grid != null) {
  1789. setWidthForce(pixels);
  1790. }
  1791. }
  1792. private void setWidthForce(int pixels) {
  1793. int index = grid.columns.indexOf(this);
  1794. ColumnConfiguration conf = grid.escalator.getColumnConfiguration();
  1795. conf.setColumnWidth(index, pixels);
  1796. }
  1797. /**
  1798. * Returns the pixel width of the column as given by the user.
  1799. * <p>
  1800. * <em>Note:</em> If a negative value was given to
  1801. * {@link #setWidth(int)}, that same negative value is returned here.
  1802. *
  1803. * @return pixel width of the column, or a negative number if the column
  1804. * width has been automatically calculated.
  1805. * @see #setWidth(int)
  1806. * @see #getWidthActual()
  1807. */
  1808. public int getWidth() {
  1809. return widthUser;
  1810. }
  1811. /**
  1812. * Returns the effective pixel width of the column.
  1813. * <p>
  1814. * This differs from {@link #getWidth()} only when the column has been
  1815. * automatically resized.
  1816. *
  1817. * @return pixel width of the column.
  1818. */
  1819. public int getWidthActual() {
  1820. return grid.escalator.getColumnConfiguration()
  1821. .getColumnWidthActual(grid.columns.indexOf(this));
  1822. }
  1823. void reapplyWidth() {
  1824. setWidth(getWidth());
  1825. }
  1826. /**
  1827. * Enables sort indicators for the grid.
  1828. * <p>
  1829. * <b>Note:</b>The API can still sort the column even if this is set to
  1830. * <code>false</code>.
  1831. *
  1832. * @param sortable
  1833. * <code>true</code> when column sort indicators are visible.
  1834. * @return the column itself
  1835. */
  1836. public GridColumn<C, T> setSortable(boolean sortable) {
  1837. if (this.sortable != sortable) {
  1838. this.sortable = sortable;
  1839. if (grid != null) {
  1840. grid.refreshHeader();
  1841. }
  1842. }
  1843. return (GridColumn<C, T>) this;
  1844. }
  1845. /**
  1846. * Are sort indicators shown for the column.
  1847. *
  1848. * @return <code>true</code> if the column is sortable
  1849. */
  1850. public boolean isSortable() {
  1851. return sortable;
  1852. }
  1853. @Override
  1854. public String toString() {
  1855. String details = "";
  1856. if (headerText != null && !headerText.isEmpty()) {
  1857. details += "header:\"" + headerText + "\" ";
  1858. } else {
  1859. details += "header:empty ";
  1860. }
  1861. if (grid != null) {
  1862. int index = grid.getColumns().indexOf(this);
  1863. if (index != -1) {
  1864. details += "attached:#" + index + " ";
  1865. } else {
  1866. details += "attached:unindexed ";
  1867. }
  1868. } else {
  1869. details += "detached ";
  1870. }
  1871. details += "sortable:" + sortable + " ";
  1872. return getClass().getSimpleName() + "[" + details.trim() + "]";
  1873. }
  1874. boolean widthCalculationPending() {
  1875. return asyncAutodetectWidth.isRunning();
  1876. }
  1877. }
  1878. protected class BodyUpdater implements EscalatorUpdater {
  1879. @Override
  1880. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  1881. for (FlyweightCell cell : cellsToAttach) {
  1882. Renderer<?> renderer = findRenderer(cell);
  1883. if (renderer instanceof ComplexRenderer) {
  1884. try {
  1885. ((ComplexRenderer<?>) renderer).init(cell);
  1886. } catch (RuntimeException e) {
  1887. getLogger().log(
  1888. Level.SEVERE,
  1889. "Error initing cell in column "
  1890. + cell.getColumn(), e);
  1891. }
  1892. }
  1893. }
  1894. }
  1895. @Override
  1896. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  1897. for (FlyweightCell cell : attachedCells) {
  1898. Renderer<?> renderer = findRenderer(cell);
  1899. if (renderer instanceof WidgetRenderer) {
  1900. try {
  1901. WidgetRenderer<?, ?> widgetRenderer = (WidgetRenderer<?, ?>) renderer;
  1902. Widget widget = widgetRenderer.createWidget();
  1903. assert widget != null : "WidgetRenderer.createWidget() returned null. It should return a widget.";
  1904. assert widget.getParent() == null : "WidgetRenderer.createWidget() returned a widget which already is attached.";
  1905. assert cell.getElement().getChildCount() == 0 : "Cell content should be empty when adding Widget";
  1906. // Physical attach
  1907. cell.getElement().appendChild(widget.getElement());
  1908. // Logical attach
  1909. GridUtil.setParent(widget, Grid.this);
  1910. } catch (RuntimeException e) {
  1911. getLogger().log(
  1912. Level.SEVERE,
  1913. "Error attaching child widget in column "
  1914. + cell.getColumn(), e);
  1915. }
  1916. }
  1917. }
  1918. }
  1919. @Override
  1920. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  1921. int rowIndex = row.getRow();
  1922. TableRowElement rowElement = row.getElement();
  1923. T rowData = dataSource.getRow(rowIndex);
  1924. boolean hasData = rowData != null;
  1925. /*
  1926. * TODO could be more efficient to build a list of all styles that
  1927. * should be used and update the element only once instead of
  1928. * attempting to update only the ones that have changed.
  1929. */
  1930. // Assign stylename for rows with data
  1931. boolean usedToHaveData = rowElement
  1932. .hasClassName(rowHasDataStyleName);
  1933. if (usedToHaveData != hasData) {
  1934. setStyleName(rowElement, rowHasDataStyleName, hasData);
  1935. }
  1936. boolean isEvenIndex = (row.getRow() % 2 == 0);
  1937. setStyleName(rowElement, rowStripeStyleName, isEvenIndex);
  1938. if (hasData) {
  1939. setStyleName(rowElement, rowSelectedStyleName,
  1940. isSelected(rowData));
  1941. if (cellStyleGenerator != null) {
  1942. try {
  1943. String rowStylename = cellStyleGenerator.getStyle(
  1944. Grid.this, rowData, rowIndex, null, -1);
  1945. if (rowStylename != null) {
  1946. rowStylename = rowGeneratedStylePrefix
  1947. + rowStylename;
  1948. }
  1949. setCustomStyleName(rowElement, rowStylename);
  1950. } catch (RuntimeException e) {
  1951. getLogger().log(
  1952. Level.SEVERE,
  1953. "Error generating styles for row "
  1954. + row.getRow(), e);
  1955. }
  1956. } else {
  1957. // Remove in case there was a generator previously
  1958. setCustomStyleName(rowElement, null);
  1959. }
  1960. } else if (usedToHaveData) {
  1961. setStyleName(rowElement, rowSelectedStyleName, false);
  1962. setCustomStyleName(rowElement, null);
  1963. }
  1964. cellFocusHandler.updateFocusedRowStyle(row);
  1965. for (FlyweightCell cell : cellsToUpdate) {
  1966. GridColumn<?, T> column = getColumn(cell.getColumn());
  1967. assert column != null : "Column was not found from cell ("
  1968. + cell.getColumn() + "," + cell.getRow() + ")";
  1969. cellFocusHandler.updateFocusedCellStyle(cell,
  1970. escalator.getBody());
  1971. if (hasData && cellStyleGenerator != null) {
  1972. try {
  1973. String generatedStyle = cellStyleGenerator.getStyle(
  1974. Grid.this, rowData, rowIndex, column,
  1975. cell.getColumn());
  1976. if (generatedStyle != null) {
  1977. generatedStyle = cellGeneratedStylePrefix
  1978. + generatedStyle;
  1979. }
  1980. setCustomStyleName(cell.getElement(), generatedStyle);
  1981. } catch (RuntimeException e) {
  1982. getLogger().log(
  1983. Level.SEVERE,
  1984. "Error generating style for cell in column "
  1985. + cell.getColumn(), e);
  1986. }
  1987. } else if (hasData || usedToHaveData) {
  1988. setCustomStyleName(cell.getElement(), null);
  1989. }
  1990. Renderer renderer = column.getRenderer();
  1991. try {
  1992. if (renderer instanceof ComplexRenderer) {
  1993. // Hide cell content if needed
  1994. ComplexRenderer clxRenderer = (ComplexRenderer) renderer;
  1995. if (hasData) {
  1996. if (!usedToHaveData) {
  1997. // Prepare cell for rendering
  1998. clxRenderer.setContentVisible(cell, true);
  1999. }
  2000. Object value = column.getValue(rowData);
  2001. clxRenderer.render(cell, value);
  2002. } else {
  2003. // Prepare cell for no data
  2004. clxRenderer.setContentVisible(cell, false);
  2005. }
  2006. } else if (hasData) {
  2007. // Simple renderers just render
  2008. Object value = column.getValue(rowData);
  2009. renderer.render(cell, value);
  2010. } else {
  2011. // Clear cell if there is no data
  2012. cell.getElement().removeAllChildren();
  2013. }
  2014. } catch (RuntimeException e) {
  2015. getLogger().log(
  2016. Level.SEVERE,
  2017. "Error rendering cell in column "
  2018. + cell.getColumn(), e);
  2019. }
  2020. }
  2021. }
  2022. @Override
  2023. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  2024. for (FlyweightCell cell : cellsToDetach) {
  2025. Renderer renderer = findRenderer(cell);
  2026. if (renderer instanceof WidgetRenderer) {
  2027. try {
  2028. Widget w = Util.findWidget(cell.getElement()
  2029. .getFirstChildElement(), Widget.class);
  2030. if (w != null) {
  2031. // Logical detach
  2032. GridUtil.setParent(w, null);
  2033. // Physical detach
  2034. cell.getElement().removeChild(w.getElement());
  2035. }
  2036. } catch (RuntimeException e) {
  2037. getLogger().log(
  2038. Level.SEVERE,
  2039. "Error detaching widget in column "
  2040. + cell.getColumn(), e);
  2041. }
  2042. }
  2043. }
  2044. }
  2045. @Override
  2046. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  2047. for (FlyweightCell cell : detachedCells) {
  2048. Renderer renderer = findRenderer(cell);
  2049. if (renderer instanceof ComplexRenderer) {
  2050. try {
  2051. ((ComplexRenderer) renderer).destroy(cell);
  2052. } catch (RuntimeException e) {
  2053. getLogger().log(
  2054. Level.SEVERE,
  2055. "Error destroying cell in column "
  2056. + cell.getColumn(), e);
  2057. }
  2058. }
  2059. }
  2060. }
  2061. }
  2062. protected class StaticSectionUpdater implements EscalatorUpdater {
  2063. private StaticSection<?> section;
  2064. private RowContainer container;
  2065. public StaticSectionUpdater(StaticSection<?> section,
  2066. RowContainer container) {
  2067. super();
  2068. this.section = section;
  2069. this.container = container;
  2070. }
  2071. @Override
  2072. public void update(Row row, Iterable<FlyweightCell> cellsToUpdate) {
  2073. StaticSection.StaticRow<?> staticRow = section.getRow(row.getRow());
  2074. final List<GridColumn<?, T>> columns = getColumns();
  2075. setCustomStyleName(row.getElement(), staticRow.getStyleName());
  2076. for (FlyweightCell cell : cellsToUpdate) {
  2077. final StaticSection.StaticCell metadata = staticRow
  2078. .getCell(columns.get(cell.getColumn()));
  2079. // Decorate default row with sorting indicators
  2080. if (staticRow instanceof HeaderRow) {
  2081. addSortingIndicatorsToHeaderRow((HeaderRow) staticRow, cell);
  2082. }
  2083. // Assign colspan to cell before rendering
  2084. cell.setColSpan(metadata.getColspan());
  2085. TableCellElement element = cell.getElement();
  2086. switch (metadata.getType()) {
  2087. case TEXT:
  2088. element.setInnerText(metadata.getText());
  2089. break;
  2090. case HTML:
  2091. element.setInnerHTML(metadata.getHtml());
  2092. break;
  2093. case WIDGET:
  2094. preDetach(row, Arrays.asList(cell));
  2095. element.setInnerHTML("");
  2096. postAttach(row, Arrays.asList(cell));
  2097. break;
  2098. }
  2099. setCustomStyleName(element, metadata.getStyleName());
  2100. cellFocusHandler.updateFocusedCellStyle(cell, container);
  2101. }
  2102. }
  2103. private void addSortingIndicatorsToHeaderRow(HeaderRow headerRow,
  2104. FlyweightCell cell) {
  2105. cleanup(cell);
  2106. GridColumn<?, ?> column = getColumn(cell.getColumn());
  2107. SortOrder sortingOrder = getSortOrder(column);
  2108. if (!headerRow.isDefault() || !column.isSortable()
  2109. || sortingOrder == null) {
  2110. // Only apply sorting indicators to sortable header columns in
  2111. // the default header row
  2112. return;
  2113. }
  2114. Element cellElement = cell.getElement();
  2115. if (SortDirection.ASCENDING == sortingOrder.getDirection()) {
  2116. cellElement.addClassName("sort-asc");
  2117. } else {
  2118. cellElement.addClassName("sort-desc");
  2119. }
  2120. int sortIndex = Grid.this.getSortOrder().indexOf(sortingOrder);
  2121. if (sortIndex > -1 && Grid.this.getSortOrder().size() > 1) {
  2122. // Show sort order indicator if column is
  2123. // sorted and other sorted columns also exists.
  2124. cellElement.setAttribute("sort-order",
  2125. String.valueOf(sortIndex + 1));
  2126. }
  2127. }
  2128. /**
  2129. * Finds the sort order for this column
  2130. */
  2131. private SortOrder getSortOrder(GridColumn<?, ?> column) {
  2132. for (SortOrder order : Grid.this.getSortOrder()) {
  2133. if (order.getColumn() == column) {
  2134. return order;
  2135. }
  2136. }
  2137. return null;
  2138. }
  2139. private void cleanup(FlyweightCell cell) {
  2140. Element cellElement = cell.getElement();
  2141. cellElement.removeAttribute("sort-order");
  2142. cellElement.removeClassName("sort-desc");
  2143. cellElement.removeClassName("sort-asc");
  2144. }
  2145. @Override
  2146. public void preAttach(Row row, Iterable<FlyweightCell> cellsToAttach) {
  2147. }
  2148. @Override
  2149. public void postAttach(Row row, Iterable<FlyweightCell> attachedCells) {
  2150. StaticSection.StaticRow<?> gridRow = section.getRow(row.getRow());
  2151. List<GridColumn<?, T>> columns = getColumns();
  2152. for (FlyweightCell cell : attachedCells) {
  2153. StaticSection.StaticCell metadata = gridRow.getCell(columns
  2154. .get(cell.getColumn()));
  2155. /*
  2156. * If the cell contains widgets that are not currently attach
  2157. * then attach them now.
  2158. */
  2159. if (GridStaticCellType.WIDGET.equals(metadata.getType())) {
  2160. final Widget widget = metadata.getWidget();
  2161. final Element cellElement = cell.getElement();
  2162. if (!widget.isAttached()) {
  2163. // Physical attach
  2164. cellElement.appendChild(widget.getElement());
  2165. // Logical attach
  2166. GridUtil.setParent(widget, Grid.this);
  2167. }
  2168. }
  2169. }
  2170. }
  2171. @Override
  2172. public void preDetach(Row row, Iterable<FlyweightCell> cellsToDetach) {
  2173. if (section.getRowCount() > row.getRow()) {
  2174. StaticSection.StaticRow<?> gridRow = section.getRow(row
  2175. .getRow());
  2176. List<GridColumn<?, T>> columns = getColumns();
  2177. for (FlyweightCell cell : cellsToDetach) {
  2178. StaticSection.StaticCell metadata = gridRow.getCell(columns
  2179. .get(cell.getColumn()));
  2180. if (GridStaticCellType.WIDGET.equals(metadata.getType())
  2181. && metadata.getWidget().isAttached()) {
  2182. Widget widget = metadata.getWidget();
  2183. // Logical detach
  2184. GridUtil.setParent(widget, null);
  2185. // Physical detach
  2186. widget.getElement().removeFromParent();
  2187. }
  2188. }
  2189. }
  2190. }
  2191. @Override
  2192. public void postDetach(Row row, Iterable<FlyweightCell> detachedCells) {
  2193. }
  2194. };
  2195. /**
  2196. * Creates a new instance.
  2197. */
  2198. public Grid() {
  2199. initWidget(escalator);
  2200. getElement().setTabIndex(0);
  2201. cellFocusHandler = new CellFocusHandler();
  2202. setStylePrimaryName("v-grid");
  2203. escalator.getHeader().setEscalatorUpdater(createHeaderUpdater());
  2204. escalator.getBody().setEscalatorUpdater(createBodyUpdater());
  2205. escalator.getFooter().setEscalatorUpdater(createFooterUpdater());
  2206. header.setGrid(this);
  2207. HeaderRow defaultRow = header.appendRow();
  2208. header.setDefaultRow(defaultRow);
  2209. footer.setGrid(this);
  2210. editorRow.setGrid(this);
  2211. setSelectionMode(SelectionMode.MULTI);
  2212. escalator.addScrollHandler(new ScrollHandler() {
  2213. @Override
  2214. public void onScroll(ScrollEvent event) {
  2215. fireEvent(new ScrollEvent());
  2216. }
  2217. });
  2218. escalator
  2219. .addRowVisibilityChangeHandler(new RowVisibilityChangeHandler() {
  2220. @Override
  2221. public void onRowVisibilityChange(
  2222. RowVisibilityChangeEvent event) {
  2223. if (dataSource != null && dataSource.size() > 0) {
  2224. dataIsBeingFetched = true;
  2225. dataSource.ensureAvailability(
  2226. event.getFirstVisibleRow(),
  2227. event.getVisibleRowCount());
  2228. }
  2229. }
  2230. });
  2231. // Default action on SelectionChangeEvents. Refresh the body so changed
  2232. // become visible.
  2233. addSelectionChangeHandler(new SelectionChangeHandler<T>() {
  2234. @Override
  2235. public void onSelectionChange(SelectionChangeEvent<T> event) {
  2236. refreshBody();
  2237. }
  2238. });
  2239. // Sink header events and key events
  2240. sinkEvents(getHeader().getConsumedEvents());
  2241. sinkEvents(Arrays.asList(BrowserEvents.KEYDOWN, BrowserEvents.KEYUP,
  2242. BrowserEvents.KEYPRESS, BrowserEvents.DBLCLICK));
  2243. // Make ENTER and SHIFT+ENTER in the header perform sorting
  2244. addHeaderKeyUpHandler(new HeaderKeyUpHandler() {
  2245. @Override
  2246. public void onKeyUp(GridKeyUpEvent event) {
  2247. if (event.getNativeKeyCode() != KeyCodes.KEY_ENTER) {
  2248. return;
  2249. }
  2250. sorter.sort(event.getFocusedCell(), event.isShiftKeyDown());
  2251. }
  2252. });
  2253. addDataAvailableHandler(new DataAvailableHandler() {
  2254. @Override
  2255. public void onDataAvailable(DataAvailableEvent event) {
  2256. dataIsBeingFetched = false;
  2257. }
  2258. });
  2259. }
  2260. @Override
  2261. public void setStylePrimaryName(String style) {
  2262. super.setStylePrimaryName(style);
  2263. escalator.setStylePrimaryName(style);
  2264. editorRow.setStylePrimaryName(style);
  2265. String rowStyle = getStylePrimaryName() + "-row";
  2266. rowHasDataStyleName = rowStyle + "-has-data";
  2267. rowSelectedStyleName = rowStyle + "-selected";
  2268. rowStripeStyleName = rowStyle + "-stripe";
  2269. rowGeneratedStylePrefix = rowStyle + "-";
  2270. /*
  2271. * TODO rename CSS "active" to "focused" once Valo theme has been
  2272. * merged.
  2273. */
  2274. cellFocusStyleName = getStylePrimaryName() + "-cell-active";
  2275. cellGeneratedStylePrefix = getStylePrimaryName() + "-cell-content-";
  2276. headerFooterFocusStyleName = getStylePrimaryName() + "-header-active";
  2277. rowFocusStyleName = getStylePrimaryName() + "-row-active";
  2278. if (isAttached()) {
  2279. refreshHeader();
  2280. refreshBody();
  2281. refreshFooter();
  2282. }
  2283. }
  2284. /**
  2285. * Creates the escalator updater used to update the header rows in this
  2286. * grid. The updater is invoked when header rows or columns are added or
  2287. * removed, or the content of existing header cells is changed.
  2288. *
  2289. * @return the new header updater instance
  2290. *
  2291. * @see GridHeader
  2292. * @see Grid#getHeader()
  2293. */
  2294. protected EscalatorUpdater createHeaderUpdater() {
  2295. return new StaticSectionUpdater(header, escalator.getHeader());
  2296. }
  2297. /**
  2298. * Creates the escalator updater used to update the body rows in this grid.
  2299. * The updater is invoked when body rows or columns are added or removed,
  2300. * the content of body cells is changed, or the body is scrolled to expose
  2301. * previously hidden content.
  2302. *
  2303. * @return the new body updater instance
  2304. */
  2305. protected EscalatorUpdater createBodyUpdater() {
  2306. return new BodyUpdater();
  2307. }
  2308. /**
  2309. * Creates the escalator updater used to update the footer rows in this
  2310. * grid. The updater is invoked when header rows or columns are added or
  2311. * removed, or the content of existing header cells is changed.
  2312. *
  2313. * @return the new footer updater instance
  2314. *
  2315. * @see GridFooter
  2316. * @see #getFooter()
  2317. */
  2318. protected EscalatorUpdater createFooterUpdater() {
  2319. return new StaticSectionUpdater(footer, escalator.getFooter());
  2320. }
  2321. /**
  2322. * Refreshes header or footer rows on demand
  2323. *
  2324. * @param rows
  2325. * The row container
  2326. * @param firstRowIsVisible
  2327. * is the first row visible
  2328. * @param isHeader
  2329. * <code>true</code> if we refreshing the header, else assumed
  2330. * the footer
  2331. */
  2332. private void refreshRowContainer(RowContainer rows, StaticSection<?> section) {
  2333. // Add or Remove rows on demand
  2334. int rowDiff = section.getVisibleRowCount() - rows.getRowCount();
  2335. if (rowDiff > 0) {
  2336. rows.insertRows(0, rowDiff);
  2337. } else if (rowDiff < 0) {
  2338. rows.removeRows(0, -rowDiff);
  2339. }
  2340. // Refresh all the rows
  2341. if (rows.getRowCount() > 0) {
  2342. rows.refreshRows(0, rows.getRowCount());
  2343. }
  2344. }
  2345. /**
  2346. * Refreshes all header rows
  2347. */
  2348. void refreshHeader() {
  2349. refreshRowContainer(escalator.getHeader(), header);
  2350. }
  2351. /**
  2352. * Refreshes all body rows
  2353. */
  2354. private void refreshBody() {
  2355. escalator.getBody().refreshRows(0, escalator.getBody().getRowCount());
  2356. }
  2357. /**
  2358. * Refreshes all footer rows
  2359. */
  2360. void refreshFooter() {
  2361. refreshRowContainer(escalator.getFooter(), footer);
  2362. }
  2363. /**
  2364. * Adds columns as the last columns in the grid.
  2365. *
  2366. * @param columns
  2367. * the columns to add
  2368. */
  2369. public void addColumns(GridColumn<?, T>... columns) {
  2370. int count = getColumnCount();
  2371. for (GridColumn<?, T> column : columns) {
  2372. addColumn(column, count++);
  2373. }
  2374. }
  2375. /**
  2376. * Adds a column as the last column in the grid.
  2377. *
  2378. * @param column
  2379. * the column to add
  2380. * @return given column
  2381. */
  2382. public GridColumn<?, T> addColumn(GridColumn<?, T> column) {
  2383. addColumn(column, getColumnCount());
  2384. return column;
  2385. }
  2386. /**
  2387. * Inserts a column into a specific position in the grid.
  2388. *
  2389. * @param index
  2390. * the index where the column should be inserted into
  2391. * @param column
  2392. * the column to add
  2393. * @return given column
  2394. *
  2395. * @throws IllegalStateException
  2396. * if Grid's current selection model renders a selection column,
  2397. * and {@code index} is 0.
  2398. */
  2399. public GridColumn<?, T> addColumn(GridColumn<?, T> column, int index) {
  2400. if (column == selectionColumn) {
  2401. throw new IllegalArgumentException("The selection column many "
  2402. + "not be added manually");
  2403. } else if (selectionColumn != null && index == 0) {
  2404. throw new IllegalStateException("A column cannot be inserted "
  2405. + "before the selection column");
  2406. }
  2407. addColumnSkipSelectionColumnCheck(column, index);
  2408. return column;
  2409. }
  2410. private void addColumnSkipSelectionColumnCheck(GridColumn<?, T> column,
  2411. int index) {
  2412. // Register column with grid
  2413. columns.add(index, column);
  2414. header.addColumn(column);
  2415. footer.addColumn(column);
  2416. // Register this grid instance with the column
  2417. ((AbstractGridColumn<?, T>) column).setGrid(this);
  2418. // Add to escalator
  2419. escalator.getColumnConfiguration().insertColumns(index, 1);
  2420. // Reapply column width
  2421. column.reapplyWidth();
  2422. // Sink all renderer events
  2423. Set<String> events = new HashSet<String>();
  2424. events.addAll(getConsumedEventsForRenderer(column.getRenderer()));
  2425. sinkEvents(events);
  2426. }
  2427. private void sinkEvents(Collection<String> events) {
  2428. assert events != null;
  2429. int eventsToSink = 0;
  2430. for (String typeName : events) {
  2431. int typeInt = Event.getTypeInt(typeName);
  2432. if (typeInt < 0) {
  2433. // Type not recognized by typeInt
  2434. sinkBitlessEvent(typeName);
  2435. } else {
  2436. eventsToSink |= typeInt;
  2437. }
  2438. }
  2439. if (eventsToSink > 0) {
  2440. sinkEvents(eventsToSink);
  2441. }
  2442. }
  2443. private Renderer<?> findRenderer(FlyweightCell cell) {
  2444. GridColumn<?, T> column = getColumn(cell.getColumn());
  2445. assert column != null : "Could not find column at index:"
  2446. + cell.getColumn();
  2447. return column.getRenderer();
  2448. }
  2449. /**
  2450. * Removes a column from the grid.
  2451. *
  2452. * @param column
  2453. * the column to remove
  2454. */
  2455. public void removeColumn(GridColumn<?, T> column) {
  2456. if (column != null && column.equals(selectionColumn)) {
  2457. throw new IllegalArgumentException(
  2458. "The selection column may not be removed manually.");
  2459. }
  2460. removeColumnSkipSelectionColumnCheck(column);
  2461. }
  2462. private void removeColumnSkipSelectionColumnCheck(GridColumn<?, T> column) {
  2463. int columnIndex = columns.indexOf(column);
  2464. // Remove from column configuration
  2465. escalator.getColumnConfiguration().removeColumns(columnIndex, 1);
  2466. updateFrozenColumns();
  2467. header.removeColumn(column);
  2468. footer.removeColumn(column);
  2469. // de-register column with grid
  2470. ((AbstractGridColumn<?, T>) column).setGrid(null);
  2471. columns.remove(columnIndex);
  2472. }
  2473. /**
  2474. * Returns the amount of columns in the grid.
  2475. *
  2476. * @return The number of columns in the grid
  2477. */
  2478. public int getColumnCount() {
  2479. return columns.size();
  2480. }
  2481. /**
  2482. * Returns a list of columns in the grid.
  2483. *
  2484. * @return A unmodifiable list of the columns in the grid
  2485. */
  2486. public List<GridColumn<?, T>> getColumns() {
  2487. return Collections.unmodifiableList(new ArrayList<GridColumn<?, T>>(
  2488. columns));
  2489. }
  2490. /**
  2491. * Returns a column by its index in the grid.
  2492. *
  2493. * @param index
  2494. * the index of the column
  2495. * @return The column in the given index
  2496. * @throws IllegalArgumentException
  2497. * if the column index does not exist in the grid
  2498. */
  2499. public GridColumn<?, T> getColumn(int index)
  2500. throws IllegalArgumentException {
  2501. if (index < 0 || index >= columns.size()) {
  2502. throw new IllegalStateException("Column not found.");
  2503. }
  2504. return columns.get(index);
  2505. }
  2506. /**
  2507. * Returns current index of given column
  2508. *
  2509. * @param column
  2510. * column in grid
  2511. * @return column index, or <code>-1</code> if not in this Grid
  2512. */
  2513. protected int indexOfColumn(GridColumn<?, T> column) {
  2514. return columns.indexOf(column);
  2515. }
  2516. /**
  2517. * Returns the header section of this grid. The default header contains a
  2518. * single row displaying the column captions.
  2519. *
  2520. * @return the header
  2521. */
  2522. protected Header getHeader() {
  2523. return header;
  2524. }
  2525. /**
  2526. * Gets the header row at given index.
  2527. *
  2528. * @param rowIndex
  2529. * 0 based index for row. Counted from top to bottom
  2530. * @return header row at given index
  2531. * @throws IllegalArgumentException
  2532. * if no row exists at given index
  2533. */
  2534. public HeaderRow getHeaderRow(int rowIndex) {
  2535. return header.getRow(rowIndex);
  2536. }
  2537. /**
  2538. * Inserts a new row at the given position to the header section. Shifts the
  2539. * row currently at that position and any subsequent rows down (adds one to
  2540. * their indices).
  2541. *
  2542. * @param index
  2543. * the position at which to insert the row
  2544. * @return the new row
  2545. *
  2546. * @throws IllegalArgumentException
  2547. * if the index is less than 0 or greater than row count
  2548. * @see #appendHeaderRow()
  2549. * @see #prependHeaderRow()
  2550. * @see #removeHeaderRow(HeaderRow)
  2551. * @see #removeHeaderRow(int)
  2552. */
  2553. public HeaderRow addHeaderRowAt(int index) {
  2554. return header.addRowAt(index);
  2555. }
  2556. /**
  2557. * Adds a new row at the bottom of the header section.
  2558. *
  2559. * @return the new row
  2560. * @see #prependHeaderRow()
  2561. * @see #addHeaderRowAt(int)
  2562. * @see #removeHeaderRow(HeaderRow)
  2563. * @see #removeHeaderRow(int)
  2564. */
  2565. public HeaderRow appendHeaderRow() {
  2566. return header.appendRow();
  2567. }
  2568. /**
  2569. * Returns the current default row of the header section. The default row is
  2570. * a special header row providing a user interface for sorting columns.
  2571. * Setting a header text for column updates cells in the default header.
  2572. *
  2573. * @return the default row or null if no default row set
  2574. */
  2575. public HeaderRow getDefaultHeaderRow() {
  2576. return header.getDefaultRow();
  2577. }
  2578. /**
  2579. * Gets the row count for the header section.
  2580. *
  2581. * @return row count
  2582. */
  2583. public int getHeaderRowCount() {
  2584. return header.getRowCount();
  2585. }
  2586. /**
  2587. * Adds a new row at the top of the header section.
  2588. *
  2589. * @return the new row
  2590. * @see #appendHeaderRow()
  2591. * @see #addHeaderRowAt(int)
  2592. * @see #removeHeaderRow(HeaderRow)
  2593. * @see #removeHeaderRow(int)
  2594. */
  2595. public HeaderRow prependHeaderRow() {
  2596. return header.prependRow();
  2597. }
  2598. /**
  2599. * Removes the given row from the header section.
  2600. *
  2601. * @param row
  2602. * the row to be removed
  2603. *
  2604. * @throws IllegalArgumentException
  2605. * if the row does not exist in this section
  2606. * @see #removeHeaderRow(int)
  2607. * @see #addHeaderRowAt(int)
  2608. * @see #appendHeaderRow()
  2609. * @see #prependHeaderRow()
  2610. */
  2611. public void removeHeaderRow(HeaderRow row) {
  2612. header.removeRow(row);
  2613. }
  2614. /**
  2615. * Removes the row at the given position from the header section.
  2616. *
  2617. * @param index
  2618. * the position of the row
  2619. *
  2620. * @throws IllegalArgumentException
  2621. * if no row exists at given index
  2622. * @see #removeHeaderRow(HeaderRow)
  2623. * @see #addHeaderRowAt(int)
  2624. * @see #appendHeaderRow()
  2625. * @see #prependHeaderRow()
  2626. */
  2627. public void removeHeaderRow(int rowIndex) {
  2628. header.removeRow(rowIndex);
  2629. }
  2630. /**
  2631. * Sets the default row of the header. The default row is a special header
  2632. * row providing a user interface for sorting columns.
  2633. *
  2634. * @param row
  2635. * the new default row, or null for no default row
  2636. *
  2637. * @throws IllegalArgumentException
  2638. * header does not contain the row
  2639. */
  2640. public void setDefaultHeaderRow(HeaderRow row) {
  2641. header.setDefaultRow(row);
  2642. }
  2643. /**
  2644. * Sets the visibility of the header section.
  2645. *
  2646. * @param visible
  2647. * true to show header section, false to hide
  2648. */
  2649. public void setHeaderVisible(boolean visible) {
  2650. header.setVisible(visible);
  2651. }
  2652. /**
  2653. * Returns the visibility of the header section.
  2654. *
  2655. * @return true if visible, false otherwise.
  2656. */
  2657. public boolean isHeaderVisible() {
  2658. return header.isVisible();
  2659. }
  2660. /* Grid Footers */
  2661. /**
  2662. * Returns the footer section of this grid. The default footer is empty.
  2663. *
  2664. * @return the footer
  2665. */
  2666. protected Footer getFooter() {
  2667. return footer;
  2668. }
  2669. /**
  2670. * Gets the footer row at given index.
  2671. *
  2672. * @param rowIndex
  2673. * 0 based index for row. Counted from top to bottom
  2674. * @return footer row at given index
  2675. * @throws IllegalArgumentException
  2676. * if no row exists at given index
  2677. */
  2678. public FooterRow getFooterRow(int rowIndex) {
  2679. return footer.getRow(rowIndex);
  2680. }
  2681. /**
  2682. * Inserts a new row at the given position to the footer section. Shifts the
  2683. * row currently at that position and any subsequent rows down (adds one to
  2684. * their indices).
  2685. *
  2686. * @param index
  2687. * the position at which to insert the row
  2688. * @return the new row
  2689. *
  2690. * @throws IllegalArgumentException
  2691. * if the index is less than 0 or greater than row count
  2692. * @see #appendFooterRow()
  2693. * @see #prependFooterRow()
  2694. * @see #removeFooterRow(FooterRow)
  2695. * @see #removeFooterRow(int)
  2696. */
  2697. public FooterRow addFooterRowAt(int index) {
  2698. return footer.addRowAt(index);
  2699. }
  2700. /**
  2701. * Adds a new row at the bottom of the footer section.
  2702. *
  2703. * @return the new row
  2704. * @see #prependFooterRow()
  2705. * @see #addFooterRowAt(int)
  2706. * @see #removeFooterRow(FooterRow)
  2707. * @see #removeFooterRow(int)
  2708. */
  2709. public FooterRow appendFooterRow() {
  2710. return footer.appendRow();
  2711. }
  2712. /**
  2713. * Gets the row count for the footer.
  2714. *
  2715. * @return row count
  2716. */
  2717. public int getFooterRowCount() {
  2718. return footer.getRowCount();
  2719. }
  2720. /**
  2721. * Adds a new row at the top of the footer section.
  2722. *
  2723. * @return the new row
  2724. * @see #appendFooterRow()
  2725. * @see #addFooterRowAt(int)
  2726. * @see #removeFooterRow(FooterRow)
  2727. * @see #removeFooterRow(int)
  2728. */
  2729. public FooterRow prependFooterRow() {
  2730. return footer.prependRow();
  2731. }
  2732. /**
  2733. * Removes the given row from the footer section.
  2734. *
  2735. * @param row
  2736. * the row to be removed
  2737. *
  2738. * @throws IllegalArgumentException
  2739. * if the row does not exist in this section
  2740. * @see #removeFooterRow(int)
  2741. * @see #addFooterRowAt(int)
  2742. * @see #appendFooterRow()
  2743. * @see #prependFooterRow()
  2744. */
  2745. public void removeFooterRow(FooterRow row) {
  2746. footer.removeRow(row);
  2747. }
  2748. /**
  2749. * Removes the row at the given position from the footer section.
  2750. *
  2751. * @param index
  2752. * the position of the row
  2753. *
  2754. * @throws IllegalArgumentException
  2755. * if no row exists at given index
  2756. * @see #removeFooterRow(FooterRow)
  2757. * @see #addFooterRowAt(int)
  2758. * @see #appendFooterRow()
  2759. * @see #prependFooterRow()
  2760. */
  2761. public void removeFooterRow(int rowIndex) {
  2762. footer.removeRow(rowIndex);
  2763. }
  2764. /**
  2765. * Sets the visibility of the footer section.
  2766. *
  2767. * @param visible
  2768. * true to show footer section, false to hide
  2769. */
  2770. public void setFooterVisible(boolean visible) {
  2771. footer.setVisible(visible);
  2772. }
  2773. /**
  2774. * Returns the visibility of the footer section.
  2775. *
  2776. * @return true if visible, false otherwise.
  2777. */
  2778. public boolean isFooterVisible() {
  2779. return footer.isVisible();
  2780. }
  2781. public EditorRow<T> getEditorRow() {
  2782. return editorRow;
  2783. }
  2784. protected Escalator getEscalator() {
  2785. return escalator;
  2786. }
  2787. /**
  2788. * {@inheritDoc}
  2789. * <p>
  2790. * <em>Note:</em> This method will change the widget's size in the browser
  2791. * only if {@link #getHeightMode()} returns {@link HeightMode#CSS}.
  2792. *
  2793. * @see #setHeightMode(HeightMode)
  2794. */
  2795. @Override
  2796. public void setHeight(String height) {
  2797. escalator.setHeight(height);
  2798. }
  2799. @Override
  2800. public void setWidth(String width) {
  2801. escalator.setWidth(width);
  2802. }
  2803. /**
  2804. * Sets the data source used by this grid.
  2805. *
  2806. * @param dataSource
  2807. * the data source to use, not null
  2808. * @throws IllegalArgumentException
  2809. * if <code>dataSource</code> is <code>null</code>
  2810. */
  2811. public void setDataSource(final DataSource<T> dataSource)
  2812. throws IllegalArgumentException {
  2813. if (dataSource == null) {
  2814. throw new IllegalArgumentException("dataSource can't be null.");
  2815. }
  2816. selectionModel.reset();
  2817. if (this.dataSource != null) {
  2818. this.dataSource.setDataChangeHandler(null);
  2819. }
  2820. this.dataSource = dataSource;
  2821. dataSource.setDataChangeHandler(new DataChangeHandler() {
  2822. @Override
  2823. public void dataUpdated(int firstIndex, int numberOfItems) {
  2824. escalator.getBody().refreshRows(firstIndex, numberOfItems);
  2825. }
  2826. @Override
  2827. public void dataRemoved(int firstIndex, int numberOfItems) {
  2828. escalator.getBody().removeRows(firstIndex, numberOfItems);
  2829. Range removed = Range.withLength(firstIndex, numberOfItems);
  2830. cellFocusHandler.rowsRemovedFromBody(removed);
  2831. }
  2832. @Override
  2833. public void dataAdded(int firstIndex, int numberOfItems) {
  2834. escalator.getBody().insertRows(firstIndex, numberOfItems);
  2835. Range added = Range.withLength(firstIndex, numberOfItems);
  2836. cellFocusHandler.rowsAddedToBody(added);
  2837. }
  2838. @Override
  2839. public void dataAvailable(int firstIndex, int numberOfItems) {
  2840. currentDataAvailable = Range.withLength(firstIndex,
  2841. numberOfItems);
  2842. fireEvent(new DataAvailableEvent(currentDataAvailable));
  2843. }
  2844. @Override
  2845. public void resetDataAndSize(int newSize) {
  2846. RowContainer body = escalator.getBody();
  2847. int oldSize = body.getRowCount();
  2848. if (newSize > oldSize) {
  2849. body.insertRows(oldSize, newSize - oldSize);
  2850. } else if (newSize < oldSize) {
  2851. body.removeRows(newSize, oldSize - newSize);
  2852. }
  2853. dataIsBeingFetched = true;
  2854. Range visibleRowRange = escalator.getVisibleRowRange();
  2855. dataSource.ensureAvailability(visibleRowRange.getStart(),
  2856. visibleRowRange.length());
  2857. assert body.getRowCount() == newSize;
  2858. }
  2859. });
  2860. int previousRowCount = escalator.getBody().getRowCount();
  2861. if (previousRowCount != 0) {
  2862. escalator.getBody().removeRows(0, previousRowCount);
  2863. }
  2864. int size = dataSource.size();
  2865. if (size > 0) {
  2866. escalator.getBody().insertRows(0, size);
  2867. }
  2868. }
  2869. /**
  2870. * Gets the {@Link DataSource} for this Grid.
  2871. *
  2872. * @return the data source used by this grid
  2873. */
  2874. public DataSource<T> getDataSource() {
  2875. return dataSource;
  2876. }
  2877. /**
  2878. * Sets the number of frozen columns in this grid. Setting the count to 0
  2879. * means that no data columns will be frozen, but the built-in selection
  2880. * checkbox column will still be frozen if it's in use. Setting the count to
  2881. * -1 will also disable the selection column.
  2882. * <p>
  2883. * The default value is 0.
  2884. *
  2885. * @param numberOfColumns
  2886. * the number of columns that should be frozen
  2887. *
  2888. * @throws IllegalArgumentException
  2889. * if the column count is < -1 or > the number of visible
  2890. * columns
  2891. */
  2892. public void setFrozenColumnCount(int numberOfColumns) {
  2893. if (numberOfColumns < -1 || numberOfColumns > getColumnCount()) {
  2894. throw new IllegalArgumentException(
  2895. "count must be between -1 and the current number of columns ("
  2896. + getColumnCount() + ")");
  2897. }
  2898. this.frozenColumnCount = numberOfColumns;
  2899. updateFrozenColumns();
  2900. }
  2901. private void updateFrozenColumns() {
  2902. int numberOfColumns = frozenColumnCount;
  2903. if (numberOfColumns == -1) {
  2904. numberOfColumns = 0;
  2905. } else if (selectionColumn != null) {
  2906. numberOfColumns++;
  2907. }
  2908. escalator.getColumnConfiguration()
  2909. .setFrozenColumnCount(numberOfColumns);
  2910. }
  2911. /**
  2912. * Gets the number of frozen columns in this grid. 0 means that no data
  2913. * columns will be frozen, but the built-in selection checkbox column will
  2914. * still be frozen if it's in use. -1 means that not even the selection
  2915. * column is frozen.
  2916. *
  2917. * @return the number of frozen columns
  2918. */
  2919. public int getFrozenColumnCount() {
  2920. return frozenColumnCount;
  2921. }
  2922. public HandlerRegistration addRowVisibilityChangeHandler(
  2923. RowVisibilityChangeHandler handler) {
  2924. /*
  2925. * Reusing Escalator's RowVisibilityChangeHandler, since a scroll
  2926. * concept is too abstract. e.g. the event needs to be re-sent when the
  2927. * widget is resized.
  2928. */
  2929. return escalator.addRowVisibilityChangeHandler(handler);
  2930. }
  2931. /**
  2932. * Scrolls to a certain row, using {@link ScrollDestination#ANY}.
  2933. *
  2934. * @param rowIndex
  2935. * zero-based index of the row to scroll to.
  2936. * @throws IllegalArgumentException
  2937. * if rowIndex is below zero, or above the maximum value
  2938. * supported by the data source.
  2939. */
  2940. public void scrollToRow(int rowIndex) throws IllegalArgumentException {
  2941. scrollToRow(rowIndex, ScrollDestination.ANY,
  2942. GridConstants.DEFAULT_PADDING);
  2943. }
  2944. /**
  2945. * Scrolls to a certain row, using user-specified scroll destination.
  2946. *
  2947. * @param rowIndex
  2948. * zero-based index of the row to scroll to.
  2949. * @param destination
  2950. * desired destination placement of scrolled-to-row. See
  2951. * {@link ScrollDestination} for more information.
  2952. * @throws IllegalArgumentException
  2953. * if rowIndex is below zero, or above the maximum value
  2954. * supported by the data source.
  2955. */
  2956. public void scrollToRow(int rowIndex, ScrollDestination destination)
  2957. throws IllegalArgumentException {
  2958. scrollToRow(rowIndex, destination,
  2959. destination == ScrollDestination.MIDDLE ? 0
  2960. : GridConstants.DEFAULT_PADDING);
  2961. }
  2962. /**
  2963. * Scrolls to a certain row using only user-specified parameters.
  2964. *
  2965. * @param rowIndex
  2966. * zero-based index of the row to scroll to.
  2967. * @param destination
  2968. * desired destination placement of scrolled-to-row. See
  2969. * {@link ScrollDestination} for more information.
  2970. * @param paddingPx
  2971. * number of pixels to overscroll. Behavior depends on
  2972. * destination.
  2973. * @throws IllegalArgumentException
  2974. * if {@code destination} is {@link ScrollDestination#MIDDLE}
  2975. * and padding is nonzero, because having a padding on a
  2976. * centered row is undefined behavior, or if rowIndex is below
  2977. * zero or above the row count of the data source.
  2978. */
  2979. private void scrollToRow(int rowIndex, ScrollDestination destination,
  2980. int paddingPx) throws IllegalArgumentException {
  2981. int maxsize = escalator.getBody().getRowCount() - 1;
  2982. if (rowIndex < 0) {
  2983. throw new IllegalArgumentException("Row index (" + rowIndex
  2984. + ") is below zero!");
  2985. }
  2986. if (rowIndex > maxsize) {
  2987. throw new IllegalArgumentException("Row index (" + rowIndex
  2988. + ") is above maximum (" + maxsize + ")!");
  2989. }
  2990. escalator.scrollToRow(rowIndex, destination, paddingPx);
  2991. }
  2992. /**
  2993. * Scrolls to the beginning of the very first row.
  2994. */
  2995. public void scrollToStart() {
  2996. scrollToRow(0, ScrollDestination.START);
  2997. }
  2998. /**
  2999. * Scrolls to the end of the very last row.
  3000. */
  3001. public void scrollToEnd() {
  3002. scrollToRow(escalator.getBody().getRowCount() - 1,
  3003. ScrollDestination.END);
  3004. }
  3005. /**
  3006. * Sets the vertical scroll offset.
  3007. *
  3008. * @param px
  3009. * the number of pixels this grid should be scrolled down
  3010. */
  3011. public void setScrollTop(double px) {
  3012. escalator.setScrollTop(px);
  3013. }
  3014. /**
  3015. * Gets the vertical scroll offset
  3016. *
  3017. * @return the number of pixels this grid is scrolled down
  3018. */
  3019. public double getScrollTop() {
  3020. return escalator.getScrollTop();
  3021. }
  3022. /**
  3023. * Gets the horizontal scroll offset
  3024. *
  3025. * @return the number of pixels this grid is scrolled to the right
  3026. */
  3027. public double getScrollLeft() {
  3028. return escalator.getScrollLeft();
  3029. }
  3030. private static final Logger getLogger() {
  3031. return Logger.getLogger(Grid.class.getName());
  3032. }
  3033. /**
  3034. * Sets the number of rows that should be visible in Grid's body, while
  3035. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  3036. * <p>
  3037. * If Grid is currently not in {@link HeightMode#ROW}, the given value is
  3038. * remembered, and applied once the mode is applied.
  3039. *
  3040. * @param rows
  3041. * The height in terms of number of rows displayed in Grid's
  3042. * body. If Grid doesn't contain enough rows, white space is
  3043. * displayed instead.
  3044. * @throws IllegalArgumentException
  3045. * if {@code rows} is zero or less
  3046. * @throws IllegalArgumentException
  3047. * if {@code rows} is {@link Double#isInifinite(double)
  3048. * infinite}
  3049. * @throws IllegalArgumentException
  3050. * if {@code rows} is {@link Double#isNaN(double) NaN}
  3051. *
  3052. * @see #setHeightMode(HeightMode)
  3053. */
  3054. public void setHeightByRows(double rows) throws IllegalArgumentException {
  3055. escalator.setHeightByRows(rows);
  3056. }
  3057. /**
  3058. * Gets the amount of rows in Grid's body that are shown, while
  3059. * {@link #getHeightMode()} is {@link HeightMode#ROW}.
  3060. * <p>
  3061. * By default, it is {@value Escalator#DEFAULT_HEIGHT_BY_ROWS}.
  3062. *
  3063. * @return the amount of rows that should be shown in Grid's body, while in
  3064. * {@link HeightMode#ROW}.
  3065. * @see #setHeightByRows(double)
  3066. */
  3067. public double getHeightByRows() {
  3068. return escalator.getHeightByRows();
  3069. }
  3070. /**
  3071. * Defines the mode in which the Grid widget's height is calculated.
  3072. * <p>
  3073. * If {@link HeightMode#CSS} is given, Grid will respect the values given
  3074. * via {@link #setHeight(String)}, and behave as a traditional Widget.
  3075. * <p>
  3076. * If {@link HeightMode#ROW} is given, Grid will make sure that the body
  3077. * will display as many rows as {@link #getHeightByRows()} defines.
  3078. * <em>Note:</em> If headers/footers are inserted or removed, the widget
  3079. * will resize itself to still display the required amount of rows in its
  3080. * body. It also takes the horizontal scrollbar into account.
  3081. *
  3082. * @param heightMode
  3083. * the mode in to which Grid should be set
  3084. */
  3085. public void setHeightMode(HeightMode heightMode) {
  3086. /*
  3087. * This method is a workaround for the fact that Vaadin re-applies
  3088. * widget dimensions (height/width) on each state change event. The
  3089. * original design was to have setHeight an setHeightByRow be equals,
  3090. * and whichever was called the latest was considered in effect.
  3091. *
  3092. * But, because of Vaadin always calling setHeight on the widget, this
  3093. * approach doesn't work.
  3094. */
  3095. escalator.setHeightMode(heightMode);
  3096. }
  3097. /**
  3098. * Returns the current {@link HeightMode} the Grid is in.
  3099. * <p>
  3100. * Defaults to {@link HeightMode#CSS}.
  3101. *
  3102. * @return the current HeightMode
  3103. */
  3104. public HeightMode getHeightMode() {
  3105. return escalator.getHeightMode();
  3106. }
  3107. private Set<String> getConsumedEventsForRenderer(Renderer<?> renderer) {
  3108. Set<String> events = new HashSet<String>();
  3109. if (renderer instanceof ComplexRenderer) {
  3110. Collection<String> consumedEvents = ((ComplexRenderer<?>) renderer)
  3111. .getConsumedEvents();
  3112. if (consumedEvents != null) {
  3113. events.addAll(consumedEvents);
  3114. }
  3115. }
  3116. return events;
  3117. }
  3118. @Override
  3119. public void onBrowserEvent(Event event) {
  3120. EventTarget target = event.getEventTarget();
  3121. if (!Element.is(target)) {
  3122. return;
  3123. }
  3124. Element e = Element.as(target);
  3125. RowContainer container = escalator.findRowContainer(e);
  3126. Cell cell;
  3127. String eventType = event.getType();
  3128. if (container == null) {
  3129. if (eventType.equals(BrowserEvents.KEYDOWN)
  3130. || eventType.equals(BrowserEvents.KEYUP)
  3131. || eventType.equals(BrowserEvents.KEYPRESS)) {
  3132. cell = cellFocusHandler.getFocusedCell();
  3133. container = cellFocusHandler.containerWithFocus;
  3134. } else {
  3135. // Click in a location that does not contain cells.
  3136. return;
  3137. }
  3138. } else {
  3139. cell = container.getCell(e);
  3140. if (eventType.equals(BrowserEvents.MOUSEDOWN)) {
  3141. cellOnPrevMouseDown = cell;
  3142. } else if (cell == null && eventType.equals(BrowserEvents.CLICK)) {
  3143. /*
  3144. * Chrome has an interesting idea on click targets (see
  3145. * cellOnPrevMouseDown javadoc). Firefox, on the other hand, has
  3146. * the mousedown target as the click target.
  3147. */
  3148. cell = cellOnPrevMouseDown;
  3149. }
  3150. }
  3151. assert cell != null : "received " + eventType
  3152. + "-event with a null cell target";
  3153. // Editor Row can steal focus from Grid and is still handled
  3154. if (handleEditorRowEvent(event, container, cell)) {
  3155. return;
  3156. }
  3157. // Fire GridKeyEvents and GridClickEvents. Pass the event to escalator.
  3158. super.onBrowserEvent(event);
  3159. if (!isElementInChildWidget(e)) {
  3160. // Sorting through header Click / KeyUp
  3161. if (handleHeaderDefaultRowEvent(event, container, cell)) {
  3162. return;
  3163. }
  3164. if (handleRendererEvent(event, container, cell)) {
  3165. return;
  3166. }
  3167. if (handleNavigationEvent(event, container, cell)) {
  3168. return;
  3169. }
  3170. if (handleCellFocusEvent(event, container, cell)) {
  3171. return;
  3172. }
  3173. }
  3174. }
  3175. private boolean isElementInChildWidget(Element e) {
  3176. Widget w = Util.findWidget(e, null);
  3177. if (w == this) {
  3178. return false;
  3179. }
  3180. /*
  3181. * If e is directly inside this grid, but the grid is wrapped in a
  3182. * Composite, findWidget is not going to find this, only the wrapper.
  3183. * Thus we need to check its parents to see if we encounter this; if we
  3184. * don't, the found widget is actually a parent of this, so we should
  3185. * return false.
  3186. */
  3187. while (w != null && w != this) {
  3188. w = w.getParent();
  3189. }
  3190. return w != null;
  3191. }
  3192. private boolean handleEditorRowEvent(Event event, RowContainer container,
  3193. Cell cell) {
  3194. if (editorRow.getState() != State.INACTIVE) {
  3195. if (event.getTypeInt() == Event.ONKEYDOWN
  3196. && event.getKeyCode() == EditorRow.KEYCODE_HIDE) {
  3197. editorRow.cancel();
  3198. }
  3199. return true;
  3200. }
  3201. if (container == escalator.getBody() && editorRow.isEnabled()) {
  3202. if (event.getTypeInt() == Event.ONDBLCLICK) {
  3203. if (cell != null) {
  3204. editorRow.editRow(cell.getRow());
  3205. return true;
  3206. }
  3207. } else if (event.getTypeInt() == Event.ONKEYDOWN
  3208. && event.getKeyCode() == EditorRow.KEYCODE_SHOW) {
  3209. editorRow.editRow(cellFocusHandler.rowWithFocus);
  3210. return true;
  3211. }
  3212. }
  3213. return false;
  3214. }
  3215. private boolean handleRendererEvent(Event event, RowContainer container,
  3216. Cell cell) {
  3217. if (container == escalator.getBody() && cell != null) {
  3218. GridColumn<?, T> gridColumn = getColumn(cell.getColumn());
  3219. boolean enterKey = event.getType().equals(BrowserEvents.KEYDOWN)
  3220. && event.getKeyCode() == KeyCodes.KEY_ENTER;
  3221. boolean doubleClick = event.getType()
  3222. .equals(BrowserEvents.DBLCLICK);
  3223. if (gridColumn.getRenderer() instanceof ComplexRenderer) {
  3224. ComplexRenderer<?> cplxRenderer = (ComplexRenderer<?>) gridColumn
  3225. .getRenderer();
  3226. if (cplxRenderer.getConsumedEvents().contains(event.getType())) {
  3227. if (cplxRenderer.onBrowserEvent(cell, event)) {
  3228. return true;
  3229. }
  3230. }
  3231. // Calls onActivate if KeyDown and Enter or double click
  3232. if ((enterKey || doubleClick) && cplxRenderer.onActivate(cell)) {
  3233. return true;
  3234. }
  3235. }
  3236. }
  3237. return false;
  3238. }
  3239. private boolean handleCellFocusEvent(Event event, RowContainer container,
  3240. Cell cell) {
  3241. Collection<String> navigation = cellFocusHandler.getNavigationEvents();
  3242. if (navigation.contains(event.getType())) {
  3243. cellFocusHandler.handleNavigationEvent(event, cell);
  3244. }
  3245. return false;
  3246. }
  3247. private boolean handleNavigationEvent(Event event, RowContainer unused,
  3248. Cell cell) {
  3249. if (!event.getType().equals(BrowserEvents.KEYDOWN)) {
  3250. // Only handle key downs
  3251. return false;
  3252. }
  3253. int newRow = -1;
  3254. RowContainer container = escalator.getBody();
  3255. switch (event.getKeyCode()) {
  3256. case KeyCodes.KEY_HOME:
  3257. if (container.getRowCount() > 0) {
  3258. newRow = 0;
  3259. }
  3260. break;
  3261. case KeyCodes.KEY_END:
  3262. if (container.getRowCount() > 0) {
  3263. newRow = container.getRowCount() - 1;
  3264. }
  3265. break;
  3266. case KeyCodes.KEY_PAGEUP: {
  3267. Range range = escalator.getVisibleRowRange();
  3268. if (!range.isEmpty()) {
  3269. int firstIndex = getFirstVisibleRowIndex();
  3270. newRow = firstIndex - range.length();
  3271. if (newRow < 0) {
  3272. newRow = 0;
  3273. }
  3274. }
  3275. break;
  3276. }
  3277. case KeyCodes.KEY_PAGEDOWN: {
  3278. Range range = escalator.getVisibleRowRange();
  3279. if (!range.isEmpty()) {
  3280. int lastIndex = getLastVisibleRowIndex();
  3281. newRow = lastIndex + range.length();
  3282. if (newRow >= container.getRowCount()) {
  3283. newRow = container.getRowCount() - 1;
  3284. }
  3285. }
  3286. break;
  3287. }
  3288. default:
  3289. return false;
  3290. }
  3291. scrollToRow(newRow);
  3292. return true;
  3293. }
  3294. private Point rowEventTouchStartingPoint;
  3295. private CellStyleGenerator<T> cellStyleGenerator;
  3296. private boolean handleHeaderDefaultRowEvent(Event event,
  3297. RowContainer container, final Cell cell) {
  3298. if (container != escalator.getHeader()) {
  3299. return false;
  3300. }
  3301. if (!getHeader().getRow(cell.getRow()).isDefault()) {
  3302. return false;
  3303. }
  3304. if (!getColumn(cell.getColumn()).isSortable()) {
  3305. // Only handle sorting events if the column is sortable
  3306. return false;
  3307. }
  3308. if (BrowserEvents.TOUCHSTART.equals(event.getType())) {
  3309. if (event.getTouches().length() > 1) {
  3310. return false;
  3311. }
  3312. event.preventDefault();
  3313. Touch touch = event.getChangedTouches().get(0);
  3314. rowEventTouchStartingPoint = new Point(touch.getClientX(),
  3315. touch.getClientY());
  3316. sorter.sortAfterDelay(GridConstants.LONG_TAP_DELAY, cell, true);
  3317. return true;
  3318. } else if (BrowserEvents.TOUCHMOVE.equals(event.getType())) {
  3319. if (event.getTouches().length() > 1) {
  3320. return false;
  3321. }
  3322. event.preventDefault();
  3323. Touch touch = event.getChangedTouches().get(0);
  3324. double diffX = Math.abs(touch.getClientX()
  3325. - rowEventTouchStartingPoint.getX());
  3326. double diffY = Math.abs(touch.getClientY()
  3327. - rowEventTouchStartingPoint.getY());
  3328. // Cancel long tap if finger strays too far from
  3329. // starting point
  3330. if (diffX > GridConstants.LONG_TAP_THRESHOLD
  3331. || diffY > GridConstants.LONG_TAP_THRESHOLD) {
  3332. sorter.cancelDelayedSort();
  3333. }
  3334. return true;
  3335. } else if (BrowserEvents.TOUCHEND.equals(event.getType())) {
  3336. if (event.getTouches().length() > 1) {
  3337. return false;
  3338. }
  3339. if (sorter.isDelayedSortScheduled()) {
  3340. // Not a long tap yet, perform single sort
  3341. sorter.cancelDelayedSort();
  3342. sorter.sort(cell, false);
  3343. }
  3344. return true;
  3345. } else if (BrowserEvents.TOUCHCANCEL.equals(event.getType())) {
  3346. if (event.getTouches().length() > 1) {
  3347. return false;
  3348. }
  3349. sorter.cancelDelayedSort();
  3350. return true;
  3351. } else if (BrowserEvents.CLICK.equals(event.getType())) {
  3352. sorter.sort(cell, event.getShiftKey());
  3353. // Click events should go onward to cell focus logic
  3354. return false;
  3355. } else {
  3356. return false;
  3357. }
  3358. }
  3359. @Override
  3360. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  3361. // Parse SubPart string to type and indices
  3362. String[] splitArgs = subPart.split("\\[");
  3363. String type = splitArgs[0];
  3364. int[] indices = new int[splitArgs.length - 1];
  3365. for (int i = 0; i < indices.length; ++i) {
  3366. String tmp = splitArgs[i + 1];
  3367. indices[i] = Integer.parseInt(tmp.substring(0, tmp.length() - 1));
  3368. }
  3369. // Get correct RowContainer for type from Escalator
  3370. RowContainer container = null;
  3371. if (type.equalsIgnoreCase("header")) {
  3372. container = escalator.getHeader();
  3373. } else if (type.equalsIgnoreCase("cell")) {
  3374. // If wanted row is not visible, we need to scroll there.
  3375. Range visibleRowRange = escalator.getVisibleRowRange();
  3376. if (indices.length > 0 && !visibleRowRange.contains(indices[0])) {
  3377. try {
  3378. scrollToRow(indices[0]);
  3379. } catch (IllegalArgumentException e) {
  3380. getLogger().log(Level.SEVERE, e.getMessage());
  3381. }
  3382. // Scrolling causes a lazy loading event. No element can
  3383. // currently be retrieved.
  3384. return null;
  3385. }
  3386. container = escalator.getBody();
  3387. } else if (type.equalsIgnoreCase("footer")) {
  3388. container = escalator.getFooter();
  3389. }
  3390. if (null != container) {
  3391. if (indices.length == 0) {
  3392. // No indexing. Just return the wanted container element
  3393. return DOM.asOld(container.getElement());
  3394. } else {
  3395. try {
  3396. return DOM.asOld(getSubPart(container, indices));
  3397. } catch (Exception e) {
  3398. getLogger().log(Level.SEVERE, e.getMessage());
  3399. }
  3400. }
  3401. }
  3402. return null;
  3403. }
  3404. private Element getSubPart(RowContainer container, int[] indices) {
  3405. Element targetElement = container.getRowElement(indices[0]);
  3406. // Scroll wanted column to view if able
  3407. if (indices.length > 1 && targetElement != null) {
  3408. if (escalator.getColumnConfiguration().getFrozenColumnCount() <= indices[1]) {
  3409. escalator.scrollToColumn(indices[1], ScrollDestination.ANY, 0);
  3410. }
  3411. targetElement = getCellFromRow(TableRowElement.as(targetElement),
  3412. indices[1]);
  3413. for (int i = 2; i < indices.length && targetElement != null; ++i) {
  3414. targetElement = (Element) targetElement.getChild(indices[i]);
  3415. }
  3416. }
  3417. return targetElement;
  3418. }
  3419. private Element getCellFromRow(TableRowElement rowElement, int index) {
  3420. int childCount = rowElement.getCells().getLength();
  3421. if (index < 0 || index >= childCount) {
  3422. return null;
  3423. }
  3424. TableCellElement currentCell = null;
  3425. boolean indexInColspan = false;
  3426. int i = 0;
  3427. while (!indexInColspan) {
  3428. currentCell = rowElement.getCells().getItem(i);
  3429. // Calculate if this is the cell we are looking for
  3430. int colSpan = currentCell.getColSpan();
  3431. indexInColspan = index < colSpan + i;
  3432. // Increment by colspan to skip over hidden cells
  3433. i += colSpan;
  3434. }
  3435. return currentCell;
  3436. }
  3437. @Override
  3438. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  3439. // Containers and matching SubPart types
  3440. List<RowContainer> containers = Arrays.asList(escalator.getHeader(),
  3441. escalator.getBody(), escalator.getFooter());
  3442. List<String> containerType = Arrays.asList("header", "cell", "footer");
  3443. for (int i = 0; i < containers.size(); ++i) {
  3444. RowContainer container = containers.get(i);
  3445. boolean containerRow = (subElement.getTagName().equalsIgnoreCase(
  3446. "tr") && subElement.getParentElement() == container
  3447. .getElement());
  3448. if (containerRow) {
  3449. // Wanted SubPart is row that is a child of containers root
  3450. // To get indices, we use a cell that is a child of this row
  3451. subElement = DOM.asOld(subElement.getFirstChildElement());
  3452. }
  3453. Cell cell = container.getCell(subElement);
  3454. if (cell != null) {
  3455. // Skip the column index if subElement was a child of root
  3456. return containerType.get(i) + "[" + cell.getRow()
  3457. + (containerRow ? "]" : "][" + cell.getColumn() + "]");
  3458. }
  3459. }
  3460. return null;
  3461. }
  3462. private void setSelectColumnRenderer(
  3463. final Renderer<Boolean> selectColumnRenderer) {
  3464. if (this.selectColumnRenderer == selectColumnRenderer) {
  3465. return;
  3466. }
  3467. if (this.selectColumnRenderer != null) {
  3468. if (this.selectColumnRenderer instanceof ComplexRenderer) {
  3469. // End of Life for the old selection column renderer.
  3470. ((ComplexRenderer<?>) this.selectColumnRenderer).destroy();
  3471. }
  3472. // Clear field so frozen column logic in the remove method knows
  3473. // what to do
  3474. GridColumn<?, T> colToRemove = selectionColumn;
  3475. selectionColumn = null;
  3476. removeColumnSkipSelectionColumnCheck(colToRemove);
  3477. cellFocusHandler.offsetRangeBy(-1);
  3478. }
  3479. this.selectColumnRenderer = selectColumnRenderer;
  3480. if (selectColumnRenderer != null) {
  3481. cellFocusHandler.offsetRangeBy(1);
  3482. selectionColumn = new SelectionColumn(selectColumnRenderer);
  3483. addColumnSkipSelectionColumnCheck(selectionColumn, 0);
  3484. selectionColumn.initDone();
  3485. } else {
  3486. selectionColumn = null;
  3487. refreshBody();
  3488. }
  3489. updateFrozenColumns();
  3490. }
  3491. /**
  3492. * Sets the current selection model.
  3493. * <p>
  3494. * This function will call {@link SelectionModel#setGrid(Grid)}.
  3495. *
  3496. * @param selectionModel
  3497. * a selection model implementation.
  3498. * @throws IllegalArgumentException
  3499. * if selection model argument is null
  3500. */
  3501. public void setSelectionModel(SelectionModel<T> selectionModel) {
  3502. if (selectionModel == null) {
  3503. throw new IllegalArgumentException("Selection model can't be null");
  3504. }
  3505. if (this.selectionModel != null) {
  3506. // Detach selection model from Grid.
  3507. this.selectionModel.setGrid(null);
  3508. }
  3509. this.selectionModel = selectionModel;
  3510. selectionModel.setGrid(this);
  3511. setSelectColumnRenderer(this.selectionModel
  3512. .getSelectionColumnRenderer());
  3513. }
  3514. /**
  3515. * Gets a reference to the current selection model.
  3516. *
  3517. * @return the currently used SelectionModel instance.
  3518. */
  3519. public SelectionModel<T> getSelectionModel() {
  3520. return selectionModel;
  3521. }
  3522. /**
  3523. * Sets current selection mode.
  3524. * <p>
  3525. * This is a shorthand method for {@link Grid#setSelectionModel}.
  3526. *
  3527. * @param mode
  3528. * a selection mode value
  3529. * @see {@link SelectionMode}.
  3530. */
  3531. public void setSelectionMode(SelectionMode mode) {
  3532. SelectionModel<T> model = mode.createModel();
  3533. setSelectionModel(model);
  3534. }
  3535. /**
  3536. * Test if a row is selected.
  3537. *
  3538. * @param row
  3539. * a row object
  3540. * @return true, if the current selection model considers the provided row
  3541. * object selected.
  3542. */
  3543. public boolean isSelected(T row) {
  3544. return selectionModel.isSelected(row);
  3545. }
  3546. /**
  3547. * Select a row using the current selection model.
  3548. * <p>
  3549. * Only selection models implementing {@link SelectionModel.Single} and
  3550. * {@link SelectionModel.Multi} are supported; for anything else, an
  3551. * exception will be thrown.
  3552. *
  3553. * @param row
  3554. * a row object
  3555. * @return <code>true</code> iff the current selection changed
  3556. * @throws IllegalStateException
  3557. * if the current selection model is not an instance of
  3558. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  3559. */
  3560. @SuppressWarnings("unchecked")
  3561. public boolean select(T row) {
  3562. if (selectionModel instanceof SelectionModel.Single<?>) {
  3563. return ((SelectionModel.Single<T>) selectionModel).select(row);
  3564. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  3565. return ((SelectionModel.Multi<T>) selectionModel).select(row);
  3566. } else {
  3567. throw new IllegalStateException("Unsupported selection model");
  3568. }
  3569. }
  3570. /**
  3571. * Deselect a row using the current selection model.
  3572. * <p>
  3573. * Only selection models implementing {@link SelectionModel.Single} and
  3574. * {@link SelectionModel.Multi} are supported; for anything else, an
  3575. * exception will be thrown.
  3576. *
  3577. * @param row
  3578. * a row object
  3579. * @return <code>true</code> iff the current selection changed
  3580. * @throws IllegalStateException
  3581. * if the current selection model is not an instance of
  3582. * {@link SelectionModel.Single} or {@link SelectionModel.Multi}
  3583. */
  3584. @SuppressWarnings("unchecked")
  3585. public boolean deselect(T row) {
  3586. if (selectionModel instanceof SelectionModel.Single<?>) {
  3587. return ((SelectionModel.Single<T>) selectionModel).deselect(row);
  3588. } else if (selectionModel instanceof SelectionModel.Multi<?>) {
  3589. return ((SelectionModel.Multi<T>) selectionModel).deselect(row);
  3590. } else {
  3591. throw new IllegalStateException("Unsupported selection model");
  3592. }
  3593. }
  3594. /**
  3595. * Gets last selected row from the current SelectionModel.
  3596. * <p>
  3597. * Only selection models implementing {@link SelectionModel.Single} are
  3598. * valid for this method; for anything else, use the
  3599. * {@link Grid#getSelectedRows()} method.
  3600. *
  3601. * @return a selected row reference, or null, if no row is selected
  3602. * @throws IllegalStateException
  3603. * if the current selection model is not an instance of
  3604. * {@link SelectionModel.Single}
  3605. */
  3606. public T getSelectedRow() {
  3607. if (selectionModel instanceof SelectionModel.Single<?>) {
  3608. return ((SelectionModel.Single<T>) selectionModel).getSelectedRow();
  3609. } else {
  3610. throw new IllegalStateException(
  3611. "Unsupported selection model; can not get single selected row");
  3612. }
  3613. }
  3614. /**
  3615. * Gets currently selected rows from the current selection model.
  3616. *
  3617. * @return a non-null collection containing all currently selected rows.
  3618. */
  3619. public Collection<T> getSelectedRows() {
  3620. return selectionModel.getSelectedRows();
  3621. }
  3622. @Override
  3623. public HandlerRegistration addSelectionChangeHandler(
  3624. final SelectionChangeHandler<T> handler) {
  3625. return addHandler(handler, SelectionChangeEvent.getType());
  3626. }
  3627. /**
  3628. * Sets the current sort order using the fluid Sort API. Read the
  3629. * documentation for {@link Sort} for more information.
  3630. *
  3631. * @param s
  3632. * a sort instance
  3633. */
  3634. public void sort(Sort s) {
  3635. setSortOrder(s.build());
  3636. }
  3637. /**
  3638. * Sorts the Grid data in ascending order along one column.
  3639. *
  3640. * @param column
  3641. * a grid column reference
  3642. */
  3643. public <C> void sort(GridColumn<C, T> column) {
  3644. sort(column, SortDirection.ASCENDING);
  3645. }
  3646. /**
  3647. * Sorts the Grid data along one column.
  3648. *
  3649. * @param column
  3650. * a grid column reference
  3651. * @param direction
  3652. * a sort direction value
  3653. */
  3654. public <C> void sort(GridColumn<C, T> column, SortDirection direction) {
  3655. sort(Sort.by(column, direction));
  3656. }
  3657. /**
  3658. * Sets the sort order to use. Setting this causes the Grid to re-sort
  3659. * itself.
  3660. *
  3661. * @param order
  3662. * a sort order list. If set to null, the sort order is cleared.
  3663. */
  3664. public void setSortOrder(List<SortOrder> order) {
  3665. setSortOrder(order, SortEventOriginator.API);
  3666. }
  3667. private void setSortOrder(List<SortOrder> order,
  3668. SortEventOriginator originator) {
  3669. if (order != sortOrder) {
  3670. sortOrder.clear();
  3671. if (order != null) {
  3672. sortOrder.addAll(order);
  3673. }
  3674. }
  3675. sort(originator);
  3676. }
  3677. /**
  3678. * Get a copy of the current sort order array.
  3679. *
  3680. * @return a copy of the current sort order array
  3681. */
  3682. public List<SortOrder> getSortOrder() {
  3683. return Collections.unmodifiableList(sortOrder);
  3684. }
  3685. /**
  3686. * Finds the sorting order for this column
  3687. */
  3688. private SortOrder getSortOrder(GridColumn<?, ?> column) {
  3689. for (SortOrder order : getSortOrder()) {
  3690. if (order.getColumn() == column) {
  3691. return order;
  3692. }
  3693. }
  3694. return null;
  3695. }
  3696. /**
  3697. * Register a GWT event handler for a sorting event. This handler gets
  3698. * called whenever this Grid needs its data source to provide data sorted in
  3699. * a specific order.
  3700. *
  3701. * @param handler
  3702. * a sort event handler
  3703. * @return the registration for the event
  3704. */
  3705. public HandlerRegistration addSortHandler(SortHandler<T> handler) {
  3706. return addHandler(handler, SortEvent.getType());
  3707. }
  3708. /**
  3709. * Register a GWT event handler for a select all event. This handler gets
  3710. * called whenever Grid needs all rows selected.
  3711. *
  3712. * @param handler
  3713. * a select all event handler
  3714. */
  3715. public HandlerRegistration addSelectAllHandler(SelectAllHandler<T> handler) {
  3716. return addHandler(handler, SelectAllEvent.getType());
  3717. }
  3718. /**
  3719. * Register a GWT event handler for a data available event. This handler
  3720. * gets called whenever the {@link DataSource} for this Grid has new data
  3721. * available.
  3722. * <p>
  3723. * This handle will be fired with the current available data after
  3724. * registration is done.
  3725. *
  3726. * @param handler
  3727. * a data available event handler
  3728. * @return the registartion for the event
  3729. */
  3730. public HandlerRegistration addDataAvailableHandler(
  3731. final DataAvailableHandler handler) {
  3732. // Deferred call to handler with current row range
  3733. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  3734. @Override
  3735. public void execute() {
  3736. if (!dataIsBeingFetched) {
  3737. handler.onDataAvailable(new DataAvailableEvent(
  3738. currentDataAvailable));
  3739. }
  3740. }
  3741. });
  3742. return addHandler(handler, DataAvailableEvent.TYPE);
  3743. }
  3744. /**
  3745. * Register a BodyKeyDownHandler to this Grid. The event for this handler is
  3746. * fired when a KeyDown event occurs while cell focus is in the Body of this
  3747. * Grid.
  3748. *
  3749. * @param handler
  3750. * the key handler to register
  3751. * @return the registration for the event
  3752. */
  3753. public HandlerRegistration addBodyKeyDownHandler(BodyKeyDownHandler handler) {
  3754. return addHandler(handler, keyDown.getAssociatedType());
  3755. }
  3756. /**
  3757. * Register a BodyKeyUpHandler to this Grid. The event for this handler is
  3758. * fired when a KeyUp event occurs while cell focus is in the Body of this
  3759. * Grid.
  3760. *
  3761. * @param handler
  3762. * the key handler to register
  3763. * @return the registration for the event
  3764. */
  3765. public HandlerRegistration addBodyKeyUpHandler(BodyKeyUpHandler handler) {
  3766. return addHandler(handler, keyUp.getAssociatedType());
  3767. }
  3768. /**
  3769. * Register a BodyKeyPressHandler to this Grid. The event for this handler
  3770. * is fired when a KeyPress event occurs while cell focus is in the Body of
  3771. * this Grid.
  3772. *
  3773. * @param handler
  3774. * the key handler to register
  3775. * @return the registration for the event
  3776. */
  3777. public HandlerRegistration addBodyKeyPressHandler(
  3778. BodyKeyPressHandler handler) {
  3779. return addHandler(handler, keyPress.getAssociatedType());
  3780. }
  3781. /**
  3782. * Register a HeaderKeyDownHandler to this Grid. The event for this handler
  3783. * is fired when a KeyDown event occurs while cell focus is in the Header of
  3784. * this Grid.
  3785. *
  3786. * @param handler
  3787. * the key handler to register
  3788. * @return the registration for the event
  3789. */
  3790. public HandlerRegistration addHeaderKeyDownHandler(
  3791. HeaderKeyDownHandler handler) {
  3792. return addHandler(handler, keyDown.getAssociatedType());
  3793. }
  3794. /**
  3795. * Register a HeaderKeyUpHandler to this Grid. The event for this handler is
  3796. * fired when a KeyUp event occurs while cell focus is in the Header of this
  3797. * Grid.
  3798. *
  3799. * @param handler
  3800. * the key handler to register
  3801. * @return the registration for the event
  3802. */
  3803. public HandlerRegistration addHeaderKeyUpHandler(HeaderKeyUpHandler handler) {
  3804. return addHandler(handler, keyUp.getAssociatedType());
  3805. }
  3806. /**
  3807. * Register a HeaderKeyPressHandler to this Grid. The event for this handler
  3808. * is fired when a KeyPress event occurs while cell focus is in the Header
  3809. * of this Grid.
  3810. *
  3811. * @param handler
  3812. * the key handler to register
  3813. * @return the registration for the event
  3814. */
  3815. public HandlerRegistration addHeaderKeyPressHandler(
  3816. HeaderKeyPressHandler handler) {
  3817. return addHandler(handler, keyPress.getAssociatedType());
  3818. }
  3819. /**
  3820. * Register a FooterKeyDownHandler to this Grid. The event for this handler
  3821. * is fired when a KeyDown event occurs while cell focus is in the Footer of
  3822. * this Grid.
  3823. *
  3824. * @param handler
  3825. * the key handler to register
  3826. * @return the registration for the event
  3827. */
  3828. public HandlerRegistration addFooterKeyDownHandler(
  3829. FooterKeyDownHandler handler) {
  3830. return addHandler(handler, keyDown.getAssociatedType());
  3831. }
  3832. /**
  3833. * Register a FooterKeyUpHandler to this Grid. The event for this handler is
  3834. * fired when a KeyUp event occurs while cell focus is in the Footer of this
  3835. * Grid.
  3836. *
  3837. * @param handler
  3838. * the key handler to register
  3839. * @return the registration for the event
  3840. */
  3841. public HandlerRegistration addFooterKeyUpHandler(FooterKeyUpHandler handler) {
  3842. return addHandler(handler, keyUp.getAssociatedType());
  3843. }
  3844. /**
  3845. * Register a FooterKeyPressHandler to this Grid. The event for this handler
  3846. * is fired when a KeyPress event occurs while cell focus is in the Footer
  3847. * of this Grid.
  3848. *
  3849. * @param handler
  3850. * the key handler to register
  3851. * @return the registration for the event
  3852. */
  3853. public HandlerRegistration addFooterKeyPressHandler(
  3854. FooterKeyPressHandler handler) {
  3855. return addHandler(handler, keyPress.getAssociatedType());
  3856. }
  3857. /**
  3858. * Register a BodyClickHandler to this Grid. The event for this handler is
  3859. * fired when a Click event occurs in the Body of this Grid.
  3860. *
  3861. * @param handler
  3862. * the click handler to register
  3863. * @return the registration for the event
  3864. */
  3865. public HandlerRegistration addBodyClickHandler(BodyClickHandler handler) {
  3866. return addHandler(handler, clickEvent.getAssociatedType());
  3867. }
  3868. /**
  3869. * Register a HeaderClickHandler to this Grid. The event for this handler is
  3870. * fired when a Click event occurs in the Header of this Grid.
  3871. *
  3872. * @param handler
  3873. * the click handler to register
  3874. * @return the registration for the event
  3875. */
  3876. public HandlerRegistration addHeaderClickHandler(HeaderClickHandler handler) {
  3877. return addHandler(handler, clickEvent.getAssociatedType());
  3878. }
  3879. /**
  3880. * Register a FooterClickHandler to this Grid. The event for this handler is
  3881. * fired when a Click event occurs in the Footer of this Grid.
  3882. *
  3883. * @param handler
  3884. * the click handler to register
  3885. * @return the registration for the event
  3886. */
  3887. public HandlerRegistration addFooterClickHandler(FooterClickHandler handler) {
  3888. return addHandler(handler, clickEvent.getAssociatedType());
  3889. }
  3890. /**
  3891. * Apply sorting to data source.
  3892. */
  3893. private void sort(SortEventOriginator originator) {
  3894. refreshHeader();
  3895. fireEvent(new SortEvent<T>(this,
  3896. Collections.unmodifiableList(sortOrder), originator));
  3897. }
  3898. private int getLastVisibleRowIndex() {
  3899. int lastRowIndex = escalator.getVisibleRowRange().getEnd();
  3900. int footerTop = escalator.getFooter().getElement().getAbsoluteTop();
  3901. Element lastRow;
  3902. do {
  3903. lastRow = escalator.getBody().getRowElement(--lastRowIndex);
  3904. } while (lastRow.getAbsoluteBottom() > footerTop);
  3905. return lastRowIndex;
  3906. }
  3907. private int getFirstVisibleRowIndex() {
  3908. int firstRowIndex = escalator.getVisibleRowRange().getStart();
  3909. int headerBottom = escalator.getHeader().getElement()
  3910. .getAbsoluteBottom();
  3911. Element firstRow = escalator.getBody().getRowElement(firstRowIndex);
  3912. while (firstRow.getAbsoluteTop() < headerBottom) {
  3913. firstRow = escalator.getBody().getRowElement(++firstRowIndex);
  3914. }
  3915. return firstRowIndex;
  3916. }
  3917. /**
  3918. * Adds a scroll handler to this grid
  3919. *
  3920. * @param handler
  3921. * the scroll handler to add
  3922. * @return a handler registration for the registered scroll handler
  3923. */
  3924. public HandlerRegistration addScrollHandler(ScrollHandler handler) {
  3925. return addHandler(handler, ScrollEvent.TYPE);
  3926. }
  3927. @Override
  3928. public boolean isWorkPending() {
  3929. return escalator.isWorkPending() || dataIsBeingFetched
  3930. || anyColumnIsBeingResized();
  3931. }
  3932. private boolean anyColumnIsBeingResized() {
  3933. for (AbstractGridColumn<?, ?> column : columns) {
  3934. if (column.widthCalculationPending()) {
  3935. return true;
  3936. }
  3937. }
  3938. return false;
  3939. }
  3940. /**
  3941. * Sets a new column order for the grid. All columns which are not ordered
  3942. * here will remain in the order they were before as the last columns of
  3943. * grid.
  3944. *
  3945. * @param orderedColumns
  3946. * array of columns in wanted order
  3947. */
  3948. public void setColumnOrder(GridColumn<?, T>... orderedColumns) {
  3949. ColumnConfiguration conf = getEscalator().getColumnConfiguration();
  3950. // Trigger ComplexRenderer.destroy for old content
  3951. conf.removeColumns(0, conf.getColumnCount());
  3952. List<GridColumn<?, T>> newOrder = new ArrayList<GridColumn<?, T>>();
  3953. if (selectionColumn != null) {
  3954. newOrder.add(selectionColumn);
  3955. }
  3956. int i = 0;
  3957. for (GridColumn<?, T> column : orderedColumns) {
  3958. if (columns.contains(column)) {
  3959. newOrder.add(column);
  3960. ++i;
  3961. } else {
  3962. throw new IllegalArgumentException("Given column at index " + i
  3963. + " does not exist in Grid");
  3964. }
  3965. }
  3966. if (columns.size() != newOrder.size()) {
  3967. columns.removeAll(newOrder);
  3968. newOrder.addAll(columns);
  3969. }
  3970. columns = newOrder;
  3971. // Do ComplexRenderer.init and render new content
  3972. conf.insertColumns(0, columns.size());
  3973. // Update column widths.
  3974. for (GridColumn<?, T> column : columns) {
  3975. column.reapplyWidth();
  3976. }
  3977. // Recalculate all the colspans
  3978. for (HeaderRow row : header.getRows()) {
  3979. row.calculateColspans();
  3980. }
  3981. for (FooterRow row : footer.getRows()) {
  3982. row.calculateColspans();
  3983. }
  3984. }
  3985. /**
  3986. * Sets the cell style generator that is used for generating styles for rows
  3987. * and cells.
  3988. *
  3989. * @param cellStyleGenerator
  3990. * the cell style generator to set, or <code>null</code> to
  3991. * remove a previously set generator
  3992. */
  3993. public void setCellStyleGenerator(CellStyleGenerator<T> cellStyleGenerator) {
  3994. this.cellStyleGenerator = cellStyleGenerator;
  3995. refreshBody();
  3996. }
  3997. /**
  3998. * Gets the cell style generator that is used for generating styles for rows
  3999. * and cells.
  4000. *
  4001. * @return the cell style generator, or <code>null</code> if no generator is
  4002. * set
  4003. */
  4004. public CellStyleGenerator<T> getCellStyleGenerator() {
  4005. return cellStyleGenerator;
  4006. }
  4007. private static void setCustomStyleName(Element element, String styleName) {
  4008. assert element != null;
  4009. String oldStyleName = element
  4010. .getPropertyString(CUSTOM_STYLE_PROPERTY_NAME);
  4011. if (!SharedUtil.equals(oldStyleName, styleName)) {
  4012. if (oldStyleName != null) {
  4013. element.removeClassName(oldStyleName);
  4014. }
  4015. if (styleName != null) {
  4016. element.addClassName(styleName);
  4017. }
  4018. element.setPropertyString(CUSTOM_STYLE_PROPERTY_NAME, styleName);
  4019. }
  4020. }
  4021. }