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.

VFilterSelect.java 76KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  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;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Date;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Set;
  24. import com.google.gwt.aria.client.Roles;
  25. import com.google.gwt.core.client.Scheduler;
  26. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  27. import com.google.gwt.dom.client.Element;
  28. import com.google.gwt.dom.client.Style;
  29. import com.google.gwt.dom.client.Style.Display;
  30. import com.google.gwt.dom.client.Style.Unit;
  31. import com.google.gwt.event.dom.client.BlurEvent;
  32. import com.google.gwt.event.dom.client.BlurHandler;
  33. import com.google.gwt.event.dom.client.ClickEvent;
  34. import com.google.gwt.event.dom.client.ClickHandler;
  35. import com.google.gwt.event.dom.client.FocusEvent;
  36. import com.google.gwt.event.dom.client.FocusHandler;
  37. import com.google.gwt.event.dom.client.KeyCodes;
  38. import com.google.gwt.event.dom.client.KeyDownEvent;
  39. import com.google.gwt.event.dom.client.KeyDownHandler;
  40. import com.google.gwt.event.dom.client.KeyUpEvent;
  41. import com.google.gwt.event.dom.client.KeyUpHandler;
  42. import com.google.gwt.event.dom.client.LoadEvent;
  43. import com.google.gwt.event.dom.client.LoadHandler;
  44. import com.google.gwt.event.logical.shared.CloseEvent;
  45. import com.google.gwt.event.logical.shared.CloseHandler;
  46. import com.google.gwt.i18n.client.HasDirection.Direction;
  47. import com.google.gwt.user.client.Command;
  48. import com.google.gwt.user.client.DOM;
  49. import com.google.gwt.user.client.Event;
  50. import com.google.gwt.user.client.Timer;
  51. import com.google.gwt.user.client.Window;
  52. import com.google.gwt.user.client.ui.Composite;
  53. import com.google.gwt.user.client.ui.FlowPanel;
  54. import com.google.gwt.user.client.ui.HTML;
  55. import com.google.gwt.user.client.ui.PopupPanel;
  56. import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
  57. import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
  58. import com.google.gwt.user.client.ui.TextBox;
  59. import com.google.gwt.user.client.ui.Widget;
  60. import com.vaadin.client.ApplicationConnection;
  61. import com.vaadin.client.BrowserInfo;
  62. import com.vaadin.client.ComponentConnector;
  63. import com.vaadin.client.ComputedStyle;
  64. import com.vaadin.client.ConnectorMap;
  65. import com.vaadin.client.Focusable;
  66. import com.vaadin.client.UIDL;
  67. import com.vaadin.client.VConsole;
  68. import com.vaadin.client.WidgetUtil;
  69. import com.vaadin.client.ui.aria.AriaHelper;
  70. import com.vaadin.client.ui.aria.HandlesAriaCaption;
  71. import com.vaadin.client.ui.aria.HandlesAriaInvalid;
  72. import com.vaadin.client.ui.aria.HandlesAriaRequired;
  73. import com.vaadin.client.ui.menubar.MenuBar;
  74. import com.vaadin.client.ui.menubar.MenuItem;
  75. import com.vaadin.shared.AbstractComponentState;
  76. import com.vaadin.shared.EventId;
  77. import com.vaadin.shared.ui.ComponentStateUtil;
  78. import com.vaadin.shared.ui.combobox.FilteringMode;
  79. import com.vaadin.shared.util.SharedUtil;
  80. /**
  81. * Client side implementation of the Select component.
  82. *
  83. * TODO needs major refactoring (to be extensible etc)
  84. */
  85. @SuppressWarnings("deprecation")
  86. public class VFilterSelect extends Composite implements Field, KeyDownHandler,
  87. KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable,
  88. SubPartAware, HandlesAriaCaption, HandlesAriaInvalid,
  89. HandlesAriaRequired {
  90. /**
  91. * Represents a suggestion in the suggestion popup box
  92. */
  93. public class FilterSelectSuggestion implements Suggestion, Command {
  94. private final String key;
  95. private final String caption;
  96. private String untranslatedIconUri;
  97. /**
  98. * Constructor
  99. *
  100. * @param uidl
  101. * The UIDL recieved from the server
  102. */
  103. public FilterSelectSuggestion(UIDL uidl) {
  104. key = uidl.getStringAttribute("key");
  105. caption = uidl.getStringAttribute("caption");
  106. if (uidl.hasAttribute("icon")) {
  107. untranslatedIconUri = uidl.getStringAttribute("icon");
  108. }
  109. }
  110. /**
  111. * Gets the visible row in the popup as a HTML string. The string
  112. * contains an image tag with the rows icon (if an icon has been
  113. * specified) and the caption of the item
  114. */
  115. @Override
  116. public String getDisplayString() {
  117. final StringBuffer sb = new StringBuffer();
  118. final Icon icon = client.getIcon(client
  119. .translateVaadinUri(untranslatedIconUri));
  120. if (icon != null) {
  121. sb.append(icon.getElement().getString());
  122. }
  123. String content;
  124. if ("".equals(caption)) {
  125. // Ensure that empty options use the same height as other
  126. // options and are not collapsed (#7506)
  127. content = " ";
  128. } else {
  129. content = WidgetUtil.escapeHTML(caption);
  130. }
  131. sb.append("<span>" + content + "</span>");
  132. return sb.toString();
  133. }
  134. /**
  135. * Get a string that represents this item. This is used in the text box.
  136. */
  137. @Override
  138. public String getReplacementString() {
  139. return caption;
  140. }
  141. /**
  142. * Get the option key which represents the item on the server side.
  143. *
  144. * @return The key of the item
  145. */
  146. public String getOptionKey() {
  147. return key;
  148. }
  149. /**
  150. * Get the URI of the icon. Used when constructing the displayed option.
  151. *
  152. * @return
  153. */
  154. public String getIconUri() {
  155. return client.translateVaadinUri(untranslatedIconUri);
  156. }
  157. /**
  158. * Executes a selection of this item.
  159. */
  160. @Override
  161. public void execute() {
  162. onSuggestionSelected(this);
  163. }
  164. @Override
  165. public boolean equals(Object obj) {
  166. if (!(obj instanceof FilterSelectSuggestion)) {
  167. return false;
  168. }
  169. FilterSelectSuggestion other = (FilterSelectSuggestion) obj;
  170. if ((key == null && other.key != null)
  171. || (key != null && !key.equals(other.key))) {
  172. return false;
  173. }
  174. if ((caption == null && other.caption != null)
  175. || (caption != null && !caption.equals(other.caption))) {
  176. return false;
  177. }
  178. if (!SharedUtil.equals(untranslatedIconUri,
  179. other.untranslatedIconUri)) {
  180. return false;
  181. }
  182. return true;
  183. }
  184. }
  185. /**
  186. * Represents the popup box with the selection options. Wraps a suggestion
  187. * menu.
  188. */
  189. public class SuggestionPopup extends VOverlay implements PositionCallback,
  190. CloseHandler<PopupPanel> {
  191. private static final int Z_INDEX = 30000;
  192. /** For internal use only. May be removed or replaced in the future. */
  193. public final SuggestionMenu menu;
  194. private final Element up = DOM.createDiv();
  195. private final Element down = DOM.createDiv();
  196. private final Element status = DOM.createDiv();
  197. private boolean isPagingEnabled = true;
  198. private long lastAutoClosed;
  199. private int popupOuterPadding = -1;
  200. private int topPosition;
  201. /**
  202. * Default constructor
  203. */
  204. SuggestionPopup() {
  205. super(true, false, true);
  206. debug("VFS.SP: constructor()");
  207. setOwner(VFilterSelect.this);
  208. menu = new SuggestionMenu();
  209. setWidget(menu);
  210. getElement().getStyle().setZIndex(Z_INDEX);
  211. final Element root = getContainerElement();
  212. up.setInnerHTML("<span>Prev</span>");
  213. DOM.sinkEvents(up, Event.ONCLICK);
  214. down.setInnerHTML("<span>Next</span>");
  215. DOM.sinkEvents(down, Event.ONCLICK);
  216. root.insertFirst(up);
  217. root.appendChild(down);
  218. root.appendChild(status);
  219. DOM.sinkEvents(root, Event.ONMOUSEDOWN | Event.ONMOUSEWHEEL);
  220. addCloseHandler(this);
  221. Roles.getListRole().set(getElement());
  222. setPreviewingAllNativeEvents(true);
  223. }
  224. /**
  225. * Shows the popup where the user can see the filtered options
  226. *
  227. * @param currentSuggestions
  228. * The filtered suggestions
  229. * @param currentPage
  230. * The current page number
  231. * @param totalSuggestions
  232. * The total amount of suggestions
  233. */
  234. public void showSuggestions(
  235. final Collection<FilterSelectSuggestion> currentSuggestions,
  236. final int currentPage, final int totalSuggestions) {
  237. debug("VFS.SP: showSuggestions(" + currentSuggestions + ", "
  238. + currentPage + ", " + totalSuggestions + ")");
  239. /*
  240. * We need to defer the opening of the popup so that the parent DOM
  241. * has stabilized so we can calculate an absolute top and left
  242. * correctly. This issue manifests when a Combobox is placed in
  243. * another popupView which also needs to calculate the absoluteTop()
  244. * to position itself. #9768
  245. *
  246. * After deferring the showSuggestions method, a problem with
  247. * navigating in the combo box occurs. Because of that the method
  248. * navigateItemAfterPageChange in ComboBoxConnector class, which
  249. * navigates to the exact item after page was changed also was
  250. * marked as deferred. #11333
  251. */
  252. final SuggestionPopup popup = this;
  253. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  254. @Override
  255. public void execute() {
  256. // Add TT anchor point
  257. getElement().setId("VAADIN_COMBOBOX_OPTIONLIST");
  258. menu.setSuggestions(currentSuggestions);
  259. final int x = VFilterSelect.this.getAbsoluteLeft();
  260. topPosition = tb.getAbsoluteTop();
  261. topPosition += tb.getOffsetHeight();
  262. setPopupPosition(x, topPosition);
  263. int nullOffset = (nullSelectionAllowed
  264. && "".equals(lastFilter) ? 1 : 0);
  265. boolean firstPage = (currentPage == 0);
  266. final int first = currentPage * pageLength + 1
  267. - (firstPage ? 0 : nullOffset);
  268. final int last = first
  269. + currentSuggestions.size()
  270. - 1
  271. - (firstPage && "".equals(lastFilter) ? nullOffset
  272. : 0);
  273. final int matches = totalSuggestions - nullOffset;
  274. if (last > 0) {
  275. // nullsel not counted, as requested by user
  276. status.setInnerText((matches == 0 ? 0 : first) + "-"
  277. + last + "/" + matches);
  278. } else {
  279. status.setInnerText("");
  280. }
  281. // We don't need to show arrows or statusbar if there is
  282. // only one page
  283. if (totalSuggestions <= pageLength || pageLength == 0) {
  284. setPagingEnabled(false);
  285. } else {
  286. setPagingEnabled(true);
  287. }
  288. setPrevButtonActive(first > 1);
  289. setNextButtonActive(last < matches);
  290. // clear previously fixed width
  291. menu.setWidth("");
  292. menu.getElement().getFirstChildElement().getStyle()
  293. .clearWidth();
  294. setPopupPositionAndShow(popup);
  295. // Fix for #14173
  296. // IE9 and IE10 have a bug, when resize an a element with
  297. // box-shadow.
  298. // IE9 and IE10 need explicit update to remove extra
  299. // box-shadows
  300. if (BrowserInfo.get().isIE9() || BrowserInfo.get().isIE10()) {
  301. forceReflow();
  302. }
  303. }
  304. });
  305. }
  306. /**
  307. * Should the next page button be visible to the user?
  308. *
  309. * @param active
  310. */
  311. private void setNextButtonActive(boolean active) {
  312. if (enableDebug) {
  313. debug("VFS.SP: setNextButtonActive(" + active + ")");
  314. }
  315. if (active) {
  316. DOM.sinkEvents(down, Event.ONCLICK);
  317. down.setClassName(VFilterSelect.this.getStylePrimaryName()
  318. + "-nextpage");
  319. } else {
  320. DOM.sinkEvents(down, 0);
  321. down.setClassName(VFilterSelect.this.getStylePrimaryName()
  322. + "-nextpage-off");
  323. }
  324. }
  325. /**
  326. * Should the previous page button be visible to the user
  327. *
  328. * @param active
  329. */
  330. private void setPrevButtonActive(boolean active) {
  331. if (enableDebug) {
  332. debug("VFS.SP: setPrevButtonActive(" + active + ")");
  333. }
  334. if (active) {
  335. DOM.sinkEvents(up, Event.ONCLICK);
  336. up.setClassName(VFilterSelect.this.getStylePrimaryName()
  337. + "-prevpage");
  338. } else {
  339. DOM.sinkEvents(up, 0);
  340. up.setClassName(VFilterSelect.this.getStylePrimaryName()
  341. + "-prevpage-off");
  342. }
  343. }
  344. /**
  345. * Selects the next item in the filtered selections
  346. */
  347. public void selectNextItem() {
  348. debug("VFS.SP: selectNextItem()");
  349. final int index = menu.getSelectedIndex() + 1;
  350. if (menu.getItems().size() > index) {
  351. selectItem(menu.getItems().get(index));
  352. } else {
  353. selectNextPage();
  354. }
  355. }
  356. /**
  357. * Selects the previous item in the filtered selections
  358. */
  359. public void selectPrevItem() {
  360. debug("VFS.SP: selectPrevItem()");
  361. final int index = menu.getSelectedIndex() - 1;
  362. if (index > -1) {
  363. selectItem(menu.getItems().get(index));
  364. } else if (index == -1) {
  365. selectPrevPage();
  366. } else {
  367. if(!menu.getItems().isEmpty()) {
  368. selectLastItem();
  369. }
  370. }
  371. }
  372. /**
  373. * Select the first item of the suggestions list popup.
  374. *
  375. * @since 7.2.6
  376. */
  377. public void selectFirstItem() {
  378. debug("VFS.SP: selectFirstItem()");
  379. selectItem(menu.getFirstItem());
  380. }
  381. /**
  382. * Select the last item of the suggestions list popup.
  383. *
  384. * @since 7.2.6
  385. */
  386. public void selectLastItem() {
  387. debug("VFS.SP: selectLastItem()");
  388. selectItem(menu.getLastItem());
  389. }
  390. /*
  391. * Sets the selected item in the popup menu.
  392. */
  393. private void selectItem(final MenuItem newSelectedItem) {
  394. menu.selectItem(newSelectedItem);
  395. // Set the icon.
  396. FilterSelectSuggestion suggestion = (FilterSelectSuggestion) newSelectedItem
  397. .getCommand();
  398. setSelectedItemIcon(suggestion.getIconUri());
  399. // Set the text.
  400. setText(suggestion.getReplacementString());
  401. }
  402. /*
  403. * Using a timer to scroll up or down the pages so when we receive lots
  404. * of consecutive mouse wheel events the pages does not flicker.
  405. */
  406. private LazyPageScroller lazyPageScroller = new LazyPageScroller();
  407. private class LazyPageScroller extends Timer {
  408. private int pagesToScroll = 0;
  409. @Override
  410. public void run() {
  411. debug("VFS.SP.LPS: run()");
  412. if (pagesToScroll != 0) {
  413. if (!waitingForFilteringResponse) {
  414. /*
  415. * Avoid scrolling while we are waiting for a response
  416. * because otherwise the waiting flag will be reset in
  417. * the first response and the second response will be
  418. * ignored, causing an empty popup...
  419. *
  420. * As long as the scrolling delay is suitable
  421. * double/triple clicks will work by scrolling two or
  422. * three pages at a time and this should not be a
  423. * problem.
  424. */
  425. filterOptions(currentPage + pagesToScroll, lastFilter);
  426. }
  427. pagesToScroll = 0;
  428. }
  429. }
  430. public void scrollUp() {
  431. debug("VFS.SP.LPS: scrollUp()");
  432. if (pageLength > 0 && currentPage + pagesToScroll > 0) {
  433. pagesToScroll--;
  434. cancel();
  435. schedule(200);
  436. }
  437. }
  438. public void scrollDown() {
  439. debug("VFS.SP.LPS: scrollDown()");
  440. if (pageLength > 0
  441. && totalMatches > (currentPage + pagesToScroll + 1)
  442. * pageLength) {
  443. pagesToScroll++;
  444. cancel();
  445. schedule(200);
  446. }
  447. }
  448. }
  449. @Override
  450. public void onBrowserEvent(Event event) {
  451. debug("VFS.SP: onBrowserEvent()");
  452. if (event.getTypeInt() == Event.ONCLICK) {
  453. final Element target = DOM.eventGetTarget(event);
  454. if (target == up || target == DOM.getChild(up, 0)) {
  455. lazyPageScroller.scrollUp();
  456. } else if (target == down || target == DOM.getChild(down, 0)) {
  457. lazyPageScroller.scrollDown();
  458. }
  459. } else if (event.getTypeInt() == Event.ONMOUSEWHEEL) {
  460. boolean scrollNotActive = !menu.isScrollActive();
  461. debug("VFS.SP: onBrowserEvent() scrollNotActive: "
  462. + scrollNotActive);
  463. if (scrollNotActive) {
  464. int velocity = event.getMouseWheelVelocityY();
  465. debug("VFS.SP: onBrowserEvent() velocity: " + velocity);
  466. if (velocity > 0) {
  467. lazyPageScroller.scrollDown();
  468. } else {
  469. lazyPageScroller.scrollUp();
  470. }
  471. }
  472. }
  473. /*
  474. * Prevent the keyboard focus from leaving the textfield by
  475. * preventing the default behaviour of the browser. Fixes #4285.
  476. */
  477. handleMouseDownEvent(event);
  478. }
  479. /**
  480. * Should paging be enabled. If paging is enabled then only a certain
  481. * amount of items are visible at a time and a scrollbar or buttons are
  482. * visible to change page. If paging is turned of then all options are
  483. * rendered into the popup menu.
  484. *
  485. * @param paging
  486. * Should the paging be turned on?
  487. */
  488. public void setPagingEnabled(boolean paging) {
  489. debug("VFS.SP: setPagingEnabled(" + paging + ")");
  490. if (isPagingEnabled == paging) {
  491. return;
  492. }
  493. if (paging) {
  494. down.getStyle().clearDisplay();
  495. up.getStyle().clearDisplay();
  496. status.getStyle().clearDisplay();
  497. } else {
  498. down.getStyle().setDisplay(Display.NONE);
  499. up.getStyle().setDisplay(Display.NONE);
  500. status.getStyle().setDisplay(Display.NONE);
  501. }
  502. isPagingEnabled = paging;
  503. }
  504. @Override
  505. public void setPosition(int offsetWidth, int offsetHeight) {
  506. debug("VFS.SP: setPosition(" + offsetWidth + ", " + offsetHeight
  507. + ")");
  508. int top = topPosition;
  509. int left = getPopupLeft();
  510. // reset menu size and retrieve its "natural" size
  511. menu.setHeight("");
  512. if (currentPage > 0 && !hasNextPage()) {
  513. // fix height to avoid height change when getting to last page
  514. menu.fixHeightTo(pageLength);
  515. }
  516. final int desiredHeight = offsetHeight = getOffsetHeight();
  517. final int desiredWidth = getMainWidth();
  518. debug("VFS.SP: desired[" + desiredWidth + ", " + desiredHeight
  519. + "]");
  520. Element menuFirstChild = menu.getElement().getFirstChildElement();
  521. final int naturalMenuWidth = menuFirstChild.getOffsetWidth();
  522. if (popupOuterPadding == -1) {
  523. popupOuterPadding = WidgetUtil
  524. .measureHorizontalPaddingAndBorder(getElement(), 2);
  525. }
  526. if (naturalMenuWidth < desiredWidth) {
  527. menu.setWidth((desiredWidth - popupOuterPadding) + "px");
  528. menuFirstChild.getStyle().setWidth(100, Unit.PCT);
  529. }
  530. if (BrowserInfo.get().isIE()) {
  531. /*
  532. * IE requires us to specify the width for the container
  533. * element. Otherwise it will be 100% wide
  534. */
  535. int rootWidth = Math.max(desiredWidth, naturalMenuWidth)
  536. - popupOuterPadding;
  537. getContainerElement().getStyle().setWidth(rootWidth, Unit.PX);
  538. }
  539. final int vfsHeight = VFilterSelect.this.getOffsetHeight();
  540. final int spaceAvailableAbove = top - vfsHeight;
  541. final int spaceAvailableBelow = Window.getClientHeight() - top;
  542. if (spaceAvailableBelow < offsetHeight
  543. && spaceAvailableBelow < spaceAvailableAbove) {
  544. // popup on top of input instead
  545. top -= offsetHeight + vfsHeight;
  546. if (top < 0) {
  547. offsetHeight += top;
  548. top = 0;
  549. }
  550. } else {
  551. offsetHeight = Math.min(offsetHeight, spaceAvailableBelow);
  552. }
  553. // fetch real width (mac FF bugs here due GWT popups overflow:auto )
  554. offsetWidth = menuFirstChild.getOffsetWidth();
  555. if (offsetHeight < desiredHeight) {
  556. int menuHeight = offsetHeight;
  557. if (isPagingEnabled) {
  558. menuHeight -= up.getOffsetHeight() + down.getOffsetHeight()
  559. + status.getOffsetHeight();
  560. } else {
  561. final ComputedStyle s = new ComputedStyle(menu.getElement());
  562. menuHeight -= s.getIntProperty("marginBottom")
  563. + s.getIntProperty("marginTop");
  564. }
  565. // If the available page height is really tiny then this will be
  566. // negative and an exception will be thrown on setHeight.
  567. int menuElementHeight = menu.getItemOffsetHeight();
  568. if (menuHeight < menuElementHeight) {
  569. menuHeight = menuElementHeight;
  570. }
  571. menu.setHeight(menuHeight + "px");
  572. final int naturalMenuWidthPlusScrollBar = naturalMenuWidth
  573. + WidgetUtil.getNativeScrollbarSize();
  574. if (offsetWidth < naturalMenuWidthPlusScrollBar) {
  575. menu.setWidth(naturalMenuWidthPlusScrollBar + "px");
  576. }
  577. }
  578. if (offsetWidth + left > Window.getClientWidth()) {
  579. left = VFilterSelect.this.getAbsoluteLeft()
  580. + VFilterSelect.this.getOffsetWidth() - offsetWidth;
  581. if (left < 0) {
  582. left = 0;
  583. menu.setWidth(Window.getClientWidth() + "px");
  584. }
  585. }
  586. setPopupPosition(left, top);
  587. menu.scrollSelectionIntoView();
  588. }
  589. /**
  590. * Was the popup just closed?
  591. *
  592. * @return true if popup was just closed
  593. */
  594. public boolean isJustClosed() {
  595. debug("VFS.SP: justClosed()");
  596. final long now = (new Date()).getTime();
  597. return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
  598. }
  599. /*
  600. * (non-Javadoc)
  601. *
  602. * @see
  603. * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google
  604. * .gwt.event.logical.shared.CloseEvent)
  605. */
  606. @Override
  607. public void onClose(CloseEvent<PopupPanel> event) {
  608. if (enableDebug) {
  609. debug("VFS.SP: onClose(" + event.isAutoClosed() + ")");
  610. }
  611. if (event.isAutoClosed()) {
  612. lastAutoClosed = (new Date()).getTime();
  613. }
  614. }
  615. /**
  616. * Updates style names in suggestion popup to help theme building.
  617. *
  618. * @param uidl
  619. * UIDL for the whole combo box
  620. * @param componentState
  621. * shared state of the combo box
  622. */
  623. public void updateStyleNames(UIDL uidl,
  624. AbstractComponentState componentState) {
  625. debug("VFS.SP: updateStyleNames()");
  626. setStyleName(VFilterSelect.this.getStylePrimaryName()
  627. + "-suggestpopup");
  628. menu.setStyleName(VFilterSelect.this.getStylePrimaryName()
  629. + "-suggestmenu");
  630. status.setClassName(VFilterSelect.this.getStylePrimaryName()
  631. + "-status");
  632. if (ComponentStateUtil.hasStyles(componentState)) {
  633. for (String style : componentState.styles) {
  634. if (!"".equals(style)) {
  635. addStyleDependentName(style);
  636. }
  637. }
  638. }
  639. }
  640. }
  641. /**
  642. * The menu where the suggestions are rendered
  643. */
  644. public class SuggestionMenu extends MenuBar implements SubPartAware,
  645. LoadHandler {
  646. private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor(
  647. 100, new ScheduledCommand() {
  648. @Override
  649. public void execute() {
  650. debug("VFS.SM: delayedImageLoadExecutioner()");
  651. if (suggestionPopup.isVisible()
  652. && suggestionPopup.isAttached()) {
  653. setWidth("");
  654. getElement().getFirstChildElement().getStyle()
  655. .clearWidth();
  656. suggestionPopup
  657. .setPopupPositionAndShow(suggestionPopup);
  658. }
  659. }
  660. });
  661. /**
  662. * Default constructor
  663. */
  664. SuggestionMenu() {
  665. super(true);
  666. debug("VFS.SM: constructor()");
  667. addDomHandler(this, LoadEvent.getType());
  668. setScrollEnabled(true);
  669. }
  670. /**
  671. * Fixes menus height to use same space as full page would use. Needed
  672. * to avoid height changes when quickly "scrolling" to last page.
  673. */
  674. public void fixHeightTo(int pageItemsCount) {
  675. setHeight(getPreferredHeight(pageItemsCount));
  676. }
  677. /*
  678. * Gets the preferred height of the menu including pageItemsCount items.
  679. */
  680. String getPreferredHeight(int pageItemsCount) {
  681. if (currentSuggestions.size() > 0) {
  682. final int pixels = (getPreferredHeight() / currentSuggestions
  683. .size()) * pageItemsCount;
  684. return pixels + "px";
  685. } else {
  686. return "";
  687. }
  688. }
  689. /**
  690. * Sets the suggestions rendered in the menu
  691. *
  692. * @param suggestions
  693. * The suggestions to be rendered in the menu
  694. */
  695. public void setSuggestions(
  696. Collection<FilterSelectSuggestion> suggestions) {
  697. if (enableDebug) {
  698. debug("VFS.SM: setSuggestions(" + suggestions + ")");
  699. }
  700. clearItems();
  701. final Iterator<FilterSelectSuggestion> it = suggestions.iterator();
  702. boolean isFirstIteration = true;
  703. while (it.hasNext()) {
  704. final FilterSelectSuggestion s = it.next();
  705. final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
  706. Roles.getListitemRole().set(mi.getElement());
  707. WidgetUtil.sinkOnloadForImages(mi.getElement());
  708. this.addItem(mi);
  709. // By default, first item on the list is always highlighted,
  710. // unless adding new items is allowed.
  711. if (isFirstIteration && !allowNewItem) {
  712. selectItem(mi);
  713. }
  714. // If the filter matches the current selection, highlight that
  715. // instead of the first item.
  716. if (tb.getText().equals(s.getReplacementString())
  717. && s == currentSuggestion) {
  718. selectItem(mi);
  719. }
  720. isFirstIteration = false;
  721. }
  722. }
  723. /**
  724. * Send the current selection to the server. Triggered when a selection
  725. * is made or on a blur event.
  726. */
  727. public void doSelectedItemAction() {
  728. debug("VFS.SM: doSelectedItemAction()");
  729. // do not send a value change event if null was and stays selected
  730. final String enteredItemValue = tb.getText();
  731. if (nullSelectionAllowed && "".equals(enteredItemValue)
  732. && selectedOptionKey != null
  733. && !"".equals(selectedOptionKey)) {
  734. if (nullSelectItem) {
  735. reset();
  736. return;
  737. }
  738. // null is not visible on pages != 0, and not visible when
  739. // filtering: handle separately
  740. client.updateVariable(paintableId, "filter", "", false);
  741. client.updateVariable(paintableId, "page", 0, false);
  742. client.updateVariable(paintableId, "selected", new String[] {},
  743. immediate);
  744. afterUpdateClientVariables();
  745. suggestionPopup.hide();
  746. return;
  747. }
  748. updateSelectionWhenReponseIsReceived = waitingForFilteringResponse;
  749. if (!waitingForFilteringResponse) {
  750. doPostFilterSelectedItemAction();
  751. }
  752. }
  753. /**
  754. * Triggered after a selection has been made
  755. */
  756. public void doPostFilterSelectedItemAction() {
  757. debug("VFS.SM: doPostFilterSelectedItemAction()");
  758. final MenuItem item = getSelectedItem();
  759. final String enteredItemValue = tb.getText();
  760. updateSelectionWhenReponseIsReceived = false;
  761. // check for exact match in menu
  762. int p = getItems().size();
  763. if (p > 0) {
  764. for (int i = 0; i < p; i++) {
  765. final MenuItem potentialExactMatch = getItems().get(i);
  766. if (potentialExactMatch.getText().equals(enteredItemValue)) {
  767. selectItem(potentialExactMatch);
  768. // do not send a value change event if null was and
  769. // stays selected
  770. if (!"".equals(enteredItemValue)
  771. || (selectedOptionKey != null && !""
  772. .equals(selectedOptionKey))) {
  773. doItemAction(potentialExactMatch, true);
  774. }
  775. suggestionPopup.hide();
  776. return;
  777. }
  778. }
  779. }
  780. if (allowNewItem) {
  781. if (!prompting && !enteredItemValue.equals(lastNewItemString)) {
  782. /*
  783. * Store last sent new item string to avoid double sends
  784. */
  785. lastNewItemString = enteredItemValue;
  786. client.updateVariable(paintableId, "newitem",
  787. enteredItemValue, immediate);
  788. afterUpdateClientVariables();
  789. }
  790. } else if (item != null
  791. && !"".equals(lastFilter)
  792. && (filteringmode == FilteringMode.CONTAINS ? item
  793. .getText().toLowerCase()
  794. .contains(lastFilter.toLowerCase()) : item
  795. .getText().toLowerCase()
  796. .startsWith(lastFilter.toLowerCase()))) {
  797. doItemAction(item, true);
  798. } else {
  799. // currentSuggestion has key="" for nullselection
  800. if (currentSuggestion != null
  801. && !currentSuggestion.key.equals("")) {
  802. // An item (not null) selected
  803. String text = currentSuggestion.getReplacementString();
  804. setText(text);
  805. selectedOptionKey = currentSuggestion.key;
  806. } else {
  807. // Null selected
  808. setText("");
  809. selectedOptionKey = null;
  810. }
  811. }
  812. suggestionPopup.hide();
  813. }
  814. private static final String SUBPART_PREFIX = "item";
  815. @Override
  816. public com.google.gwt.user.client.Element getSubPartElement(
  817. String subPart) {
  818. int index = Integer.parseInt(subPart.substring(SUBPART_PREFIX
  819. .length()));
  820. MenuItem item = getItems().get(index);
  821. return item.getElement();
  822. }
  823. @Override
  824. public String getSubPartName(
  825. com.google.gwt.user.client.Element subElement) {
  826. if (!getElement().isOrHasChild(subElement)) {
  827. return null;
  828. }
  829. Element menuItemRoot = subElement;
  830. while (menuItemRoot != null
  831. && !menuItemRoot.getTagName().equalsIgnoreCase("td")) {
  832. menuItemRoot = menuItemRoot.getParentElement().cast();
  833. }
  834. // "menuItemRoot" is now the root of the menu item
  835. final int itemCount = getItems().size();
  836. for (int i = 0; i < itemCount; i++) {
  837. if (getItems().get(i).getElement() == menuItemRoot) {
  838. String name = SUBPART_PREFIX + i;
  839. return name;
  840. }
  841. }
  842. return null;
  843. }
  844. @Override
  845. public void onLoad(LoadEvent event) {
  846. debug("VFS.SM: onLoad()");
  847. // Handle icon onload events to ensure shadow is resized
  848. // correctly
  849. delayedImageLoadExecutioner.trigger();
  850. }
  851. /**
  852. * @deprecated use {@link SuggestionPopup#selectFirstItem()} instead.
  853. */
  854. @Deprecated
  855. public void selectFirstItem() {
  856. debug("VFS.SM: selectFirstItem()");
  857. MenuItem firstItem = getItems().get(0);
  858. selectItem(firstItem);
  859. }
  860. /**
  861. * @deprecated use {@link SuggestionPopup#selectLastItem()} instead.
  862. */
  863. @Deprecated
  864. public void selectLastItem() {
  865. debug("VFS.SM: selectLastItem()");
  866. List<MenuItem> items = getItems();
  867. MenuItem lastItem = items.get(items.size() - 1);
  868. selectItem(lastItem);
  869. }
  870. /*
  871. * Gets the height of one menu item.
  872. */
  873. int getItemOffsetHeight() {
  874. List<MenuItem> items = getItems();
  875. return items != null && items.size() > 0 ? items.get(0)
  876. .getOffsetHeight() : 0;
  877. }
  878. /*
  879. * Gets the width of one menu item.
  880. */
  881. int getItemOffsetWidth() {
  882. List<MenuItem> items = getItems();
  883. return items != null && items.size() > 0 ? items.get(0)
  884. .getOffsetWidth() : 0;
  885. }
  886. /**
  887. * Returns true if the scroll is active on the menu element or if the
  888. * menu currently displays the last page with less items then the
  889. * maximum visibility (in which case the scroll is not active, but the
  890. * scroll is active for any other page in general).
  891. *
  892. * @since 7.2.6
  893. */
  894. @Override
  895. public boolean isScrollActive() {
  896. String height = getElement().getStyle().getHeight();
  897. String preferredHeight = getPreferredHeight(pageLength);
  898. return !(height == null || height.length() == 0 || height
  899. .equals(preferredHeight));
  900. }
  901. }
  902. /**
  903. * TextBox variant used as input element for filter selects, which prevents
  904. * selecting text when disabled.
  905. *
  906. * @since 7.1.5
  907. */
  908. public class FilterSelectTextBox extends TextBox {
  909. /**
  910. * Overridden to avoid selecting text when text input is disabled
  911. */
  912. @Override
  913. public void setSelectionRange(int pos, int length) {
  914. if (textInputEnabled) {
  915. /*
  916. * set selection range with a backwards direction: anchor at the
  917. * back, focus at the front. This means that items that are too
  918. * long to display will display from the start and not the end
  919. * even on Firefox.
  920. *
  921. * We need the JSNI function to set selection range so that we
  922. * can use the optional direction attribute to set the anchor to
  923. * the end and the focus to the start. This makes Firefox work
  924. * the same way as other browsers (#13477)
  925. */
  926. WidgetUtil.setSelectionRange(getElement(), pos, length,
  927. "backward");
  928. } else {
  929. /*
  930. * Setting the selectionrange for an uneditable textbox leads to
  931. * unwanted behaviour when the width of the textbox is narrower
  932. * than the width of the entry: the end of the entry is shown
  933. * instead of the beginning. (see #13477)
  934. *
  935. * To avoid this, we set the caret to the beginning of the line.
  936. */
  937. super.setSelectionRange(0, 0);
  938. }
  939. }
  940. }
  941. @Deprecated
  942. public static final FilteringMode FILTERINGMODE_OFF = FilteringMode.OFF;
  943. @Deprecated
  944. public static final FilteringMode FILTERINGMODE_STARTSWITH = FilteringMode.STARTSWITH;
  945. @Deprecated
  946. public static final FilteringMode FILTERINGMODE_CONTAINS = FilteringMode.CONTAINS;
  947. public static final String CLASSNAME = "v-filterselect";
  948. private static final String STYLE_NO_INPUT = "no-input";
  949. /** For internal use only. May be removed or replaced in the future. */
  950. public int pageLength = 10;
  951. private boolean enableDebug = false;
  952. private final FlowPanel panel = new FlowPanel();
  953. /**
  954. * The text box where the filter is written
  955. * <p>
  956. * For internal use only. May be removed or replaced in the future.
  957. */
  958. public final TextBox tb;
  959. /** For internal use only. May be removed or replaced in the future. */
  960. public final SuggestionPopup suggestionPopup;
  961. /**
  962. * Used when measuring the width of the popup
  963. */
  964. private final HTML popupOpener = new HTML("") {
  965. /*
  966. * (non-Javadoc)
  967. *
  968. * @see
  969. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt
  970. * .user.client.Event)
  971. */
  972. @Override
  973. public void onBrowserEvent(Event event) {
  974. super.onBrowserEvent(event);
  975. /*
  976. * Prevent the keyboard focus from leaving the textfield by
  977. * preventing the default behaviour of the browser. Fixes #4285.
  978. */
  979. handleMouseDownEvent(event);
  980. }
  981. };
  982. private class IconWidget extends Widget {
  983. IconWidget(Icon icon) {
  984. setElement(icon.getElement());
  985. addDomHandler(VFilterSelect.this, ClickEvent.getType());
  986. }
  987. }
  988. private IconWidget selectedItemIcon;
  989. /** For internal use only. May be removed or replaced in the future. */
  990. public ApplicationConnection client;
  991. /** For internal use only. May be removed or replaced in the future. */
  992. public String paintableId;
  993. /** For internal use only. May be removed or replaced in the future. */
  994. public int currentPage;
  995. /**
  996. * A collection of available suggestions (options) as received from the
  997. * server.
  998. * <p>
  999. * For internal use only. May be removed or replaced in the future.
  1000. */
  1001. public final List<FilterSelectSuggestion> currentSuggestions = new ArrayList<FilterSelectSuggestion>();
  1002. /** For internal use only. May be removed or replaced in the future. */
  1003. public boolean immediate;
  1004. /** For internal use only. May be removed or replaced in the future. */
  1005. public String selectedOptionKey;
  1006. /** For internal use only. May be removed or replaced in the future. */
  1007. public boolean waitingForFilteringResponse = false;
  1008. /** For internal use only. May be removed or replaced in the future. */
  1009. public boolean updateSelectionWhenReponseIsReceived = false;
  1010. /** For internal use only. May be removed or replaced in the future. */
  1011. public boolean initDone = false;
  1012. /** For internal use only. May be removed or replaced in the future. */
  1013. public String lastFilter = "";
  1014. /** For internal use only. May be removed or replaced in the future. */
  1015. public enum Select {
  1016. NONE, FIRST, LAST
  1017. }
  1018. /** For internal use only. May be removed or replaced in the future. */
  1019. public Select selectPopupItemWhenResponseIsReceived = Select.NONE;
  1020. /**
  1021. * The current suggestion selected from the dropdown. This is one of the
  1022. * values in currentSuggestions except when filtering, in this case
  1023. * currentSuggestion might not be in currentSuggestions.
  1024. * <p>
  1025. * For internal use only. May be removed or replaced in the future.
  1026. */
  1027. public FilterSelectSuggestion currentSuggestion;
  1028. /** For internal use only. May be removed or replaced in the future. */
  1029. public boolean allowNewItem;
  1030. /** For internal use only. May be removed or replaced in the future. */
  1031. public int totalMatches;
  1032. /** For internal use only. May be removed or replaced in the future. */
  1033. public boolean nullSelectionAllowed;
  1034. /** For internal use only. May be removed or replaced in the future. */
  1035. public boolean nullSelectItem;
  1036. /** For internal use only. May be removed or replaced in the future. */
  1037. public boolean enabled;
  1038. /** For internal use only. May be removed or replaced in the future. */
  1039. public boolean readonly;
  1040. /** For internal use only. May be removed or replaced in the future. */
  1041. public FilteringMode filteringmode = FilteringMode.OFF;
  1042. // shown in unfocused empty field, disappears on focus (e.g "Search here")
  1043. private static final String CLASSNAME_PROMPT = "prompt";
  1044. /** For internal use only. May be removed or replaced in the future. */
  1045. public String inputPrompt = "";
  1046. /** For internal use only. May be removed or replaced in the future. */
  1047. public boolean prompting = false;
  1048. /**
  1049. * Set true when popupopened has been clicked. Cleared on each UIDL-update.
  1050. * This handles the special case where are not filtering yet and the
  1051. * selected value has changed on the server-side. See #2119
  1052. * <p>
  1053. * For internal use only. May be removed or replaced in the future.
  1054. */
  1055. public boolean popupOpenerClicked;
  1056. /** For internal use only. May be removed or replaced in the future. */
  1057. public int suggestionPopupMinWidth = 0;
  1058. private int popupWidth = -1;
  1059. /**
  1060. * Stores the last new item string to avoid double submissions. Cleared on
  1061. * uidl updates.
  1062. * <p>
  1063. * For internal use only. May be removed or replaced in the future.
  1064. */
  1065. public String lastNewItemString;
  1066. /** For internal use only. May be removed or replaced in the future. */
  1067. public boolean focused = false;
  1068. /**
  1069. * If set to false, the component should not allow entering text to the
  1070. * field even for filtering.
  1071. */
  1072. private boolean textInputEnabled = true;
  1073. /**
  1074. * Default constructor.
  1075. */
  1076. public VFilterSelect() {
  1077. tb = createTextBox();
  1078. suggestionPopup = createSuggestionPopup();
  1079. popupOpener.sinkEvents(Event.ONMOUSEDOWN);
  1080. Roles.getButtonRole()
  1081. .setAriaHiddenState(popupOpener.getElement(), true);
  1082. Roles.getButtonRole().set(popupOpener.getElement());
  1083. panel.add(tb);
  1084. panel.add(popupOpener);
  1085. initWidget(panel);
  1086. Roles.getComboboxRole().set(panel.getElement());
  1087. tb.addKeyDownHandler(this);
  1088. tb.addKeyUpHandler(this);
  1089. tb.addFocusHandler(this);
  1090. tb.addBlurHandler(this);
  1091. tb.addClickHandler(this);
  1092. popupOpener.addClickHandler(this);
  1093. setStyleName(CLASSNAME);
  1094. sinkEvents(Event.ONPASTE);
  1095. }
  1096. /*
  1097. * (non-Javadoc)
  1098. *
  1099. * @see
  1100. * com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt
  1101. * .user.client.Event)
  1102. */
  1103. @Override
  1104. public void onBrowserEvent(Event event) {
  1105. super.onBrowserEvent(event);
  1106. if (event.getTypeInt() == Event.ONPASTE) {
  1107. if (textInputEnabled) {
  1108. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1109. @Override
  1110. public void execute() {
  1111. filterOptions(currentPage);
  1112. }
  1113. });
  1114. }
  1115. }
  1116. }
  1117. /**
  1118. * This method will create the TextBox used by the VFilterSelect instance.
  1119. * It is invoked during the Constructor and should only be overridden if a
  1120. * custom TextBox shall be used. The overriding method cannot use any
  1121. * instance variables.
  1122. *
  1123. * @since 7.1.5
  1124. * @return TextBox instance used by this VFilterSelect
  1125. */
  1126. protected TextBox createTextBox() {
  1127. return new FilterSelectTextBox();
  1128. }
  1129. /**
  1130. * This method will create the SuggestionPopup used by the VFilterSelect
  1131. * instance. It is invoked during the Constructor and should only be
  1132. * overridden if a custom SuggestionPopup shall be used. The overriding
  1133. * method cannot use any instance variables.
  1134. *
  1135. * @since 7.1.5
  1136. * @return SuggestionPopup instance used by this VFilterSelect
  1137. */
  1138. protected SuggestionPopup createSuggestionPopup() {
  1139. return new SuggestionPopup();
  1140. }
  1141. @Override
  1142. public void setStyleName(String style) {
  1143. super.setStyleName(style);
  1144. updateStyleNames();
  1145. }
  1146. @Override
  1147. public void setStylePrimaryName(String style) {
  1148. super.setStylePrimaryName(style);
  1149. updateStyleNames();
  1150. }
  1151. protected void updateStyleNames() {
  1152. tb.setStyleName(getStylePrimaryName() + "-input");
  1153. popupOpener.setStyleName(getStylePrimaryName() + "-button");
  1154. suggestionPopup.setStyleName(getStylePrimaryName() + "-suggestpopup");
  1155. }
  1156. /**
  1157. * Does the Select have more pages?
  1158. *
  1159. * @return true if a next page exists, else false if the current page is the
  1160. * last page
  1161. */
  1162. public boolean hasNextPage() {
  1163. if (pageLength > 0 && totalMatches > (currentPage + 1) * pageLength) {
  1164. return true;
  1165. } else {
  1166. return false;
  1167. }
  1168. }
  1169. /**
  1170. * Filters the options at a certain page. Uses the text box input as a
  1171. * filter
  1172. *
  1173. * @param page
  1174. * The page which items are to be filtered
  1175. */
  1176. public void filterOptions(int page) {
  1177. filterOptions(page, tb.getText());
  1178. }
  1179. /**
  1180. * Filters the options at certain page using the given filter
  1181. *
  1182. * @param page
  1183. * The page to filter
  1184. * @param filter
  1185. * The filter to apply to the components
  1186. */
  1187. public void filterOptions(int page, String filter) {
  1188. filterOptions(page, filter, true);
  1189. }
  1190. /**
  1191. * Filters the options at certain page using the given filter
  1192. *
  1193. * @param page
  1194. * The page to filter
  1195. * @param filter
  1196. * The filter to apply to the options
  1197. * @param immediate
  1198. * Whether to send the options request immediately
  1199. */
  1200. private void filterOptions(int page, String filter, boolean immediate) {
  1201. debug("VFS: filterOptions(" + page + ", " + filter + ", " + immediate
  1202. + ")");
  1203. if (filter.equals(lastFilter) && currentPage == page) {
  1204. if (!suggestionPopup.isAttached()) {
  1205. suggestionPopup.showSuggestions(currentSuggestions,
  1206. currentPage, totalMatches);
  1207. }
  1208. return;
  1209. }
  1210. if (!filter.equals(lastFilter)) {
  1211. // when filtering, let the server decide the page unless we've
  1212. // set the filter to empty and explicitly said that we want to see
  1213. // the results starting from page 0.
  1214. if ("".equals(filter) && page != 0) {
  1215. // let server decide
  1216. page = -1;
  1217. } else {
  1218. page = 0;
  1219. }
  1220. }
  1221. waitingForFilteringResponse = true;
  1222. client.updateVariable(paintableId, "filter", filter, false);
  1223. client.updateVariable(paintableId, "page", page, immediate);
  1224. afterUpdateClientVariables();
  1225. lastFilter = filter;
  1226. currentPage = page;
  1227. }
  1228. /** For internal use only. May be removed or replaced in the future. */
  1229. public void updateReadOnly() {
  1230. debug("VFS: updateReadOnly()");
  1231. tb.setReadOnly(readonly || !textInputEnabled);
  1232. }
  1233. public void setTextInputEnabled(boolean textInputEnabled) {
  1234. debug("VFS: setTextInputEnabled()");
  1235. // Always update styles as they might have been overwritten
  1236. if (textInputEnabled) {
  1237. removeStyleDependentName(STYLE_NO_INPUT);
  1238. Roles.getTextboxRole().removeAriaReadonlyProperty(tb.getElement());
  1239. } else {
  1240. addStyleDependentName(STYLE_NO_INPUT);
  1241. Roles.getTextboxRole().setAriaReadonlyProperty(tb.getElement(),
  1242. true);
  1243. }
  1244. if (this.textInputEnabled == textInputEnabled) {
  1245. return;
  1246. }
  1247. this.textInputEnabled = textInputEnabled;
  1248. updateReadOnly();
  1249. }
  1250. /**
  1251. * Sets the text in the text box.
  1252. *
  1253. * @param text
  1254. * the text to set in the text box
  1255. */
  1256. public void setTextboxText(final String text) {
  1257. if (enableDebug) {
  1258. debug("VFS: setTextboxText(" + text + ")");
  1259. }
  1260. setText(text);
  1261. }
  1262. private void setText(final String text) {
  1263. /**
  1264. * To leave caret in the beginning of the line. SetSelectionRange
  1265. * wouldn't work on IE (see #13477)
  1266. */
  1267. Direction previousDirection = tb.getDirection();
  1268. tb.setDirection(Direction.RTL);
  1269. tb.setText(text);
  1270. tb.setDirection(previousDirection);
  1271. }
  1272. /**
  1273. * Turns prompting on. When prompting is turned on a command prompt is shown
  1274. * in the text box if nothing has been entered.
  1275. */
  1276. public void setPromptingOn() {
  1277. debug("VFS: setPromptingOn()");
  1278. if (!prompting) {
  1279. prompting = true;
  1280. addStyleDependentName(CLASSNAME_PROMPT);
  1281. }
  1282. setTextboxText(inputPrompt);
  1283. }
  1284. /**
  1285. * Turns prompting off. When prompting is turned on a command prompt is
  1286. * shown in the text box if nothing has been entered.
  1287. * <p>
  1288. * For internal use only. May be removed or replaced in the future.
  1289. *
  1290. * @param text
  1291. * The text the text box should contain.
  1292. */
  1293. public void setPromptingOff(String text) {
  1294. debug("VFS: setPromptingOff()");
  1295. setTextboxText(text);
  1296. if (prompting) {
  1297. prompting = false;
  1298. removeStyleDependentName(CLASSNAME_PROMPT);
  1299. }
  1300. }
  1301. /**
  1302. * Triggered when a suggestion is selected
  1303. *
  1304. * @param suggestion
  1305. * The suggestion that just got selected.
  1306. */
  1307. public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
  1308. if (enableDebug) {
  1309. debug("VFS: onSuggestionSelected(" + suggestion.caption + ": "
  1310. + suggestion.key + ")");
  1311. }
  1312. updateSelectionWhenReponseIsReceived = false;
  1313. currentSuggestion = suggestion;
  1314. String newKey;
  1315. if (suggestion.key.equals("")) {
  1316. // "nullselection"
  1317. newKey = "";
  1318. } else {
  1319. // normal selection
  1320. newKey = suggestion.getOptionKey();
  1321. }
  1322. String text = suggestion.getReplacementString();
  1323. if ("".equals(newKey) && !focused) {
  1324. setPromptingOn();
  1325. } else {
  1326. setPromptingOff(text);
  1327. }
  1328. setSelectedItemIcon(suggestion.getIconUri());
  1329. if (!(newKey.equals(selectedOptionKey) || ("".equals(newKey) && selectedOptionKey == null))) {
  1330. selectedOptionKey = newKey;
  1331. client.updateVariable(paintableId, "selected",
  1332. new String[] { selectedOptionKey }, immediate);
  1333. afterUpdateClientVariables();
  1334. // currentPage = -1; // forget the page
  1335. }
  1336. suggestionPopup.hide();
  1337. }
  1338. /**
  1339. * Sets the icon URI of the selected item. The icon is shown on the left
  1340. * side of the item caption text. Set the URI to null to remove the icon.
  1341. *
  1342. * @param iconUri
  1343. * The URI of the icon
  1344. */
  1345. public void setSelectedItemIcon(String iconUri) {
  1346. if (iconUri == null || iconUri.length() == 0) {
  1347. if (selectedItemIcon != null) {
  1348. panel.remove(selectedItemIcon);
  1349. selectedItemIcon = null;
  1350. afterSelectedItemIconChange();
  1351. }
  1352. } else {
  1353. if (selectedItemIcon != null) {
  1354. panel.remove(selectedItemIcon);
  1355. }
  1356. selectedItemIcon = new IconWidget(client.getIcon(iconUri));
  1357. // Older IE versions don't scale icon correctly if DOM
  1358. // contains height and width attributes.
  1359. selectedItemIcon.getElement().removeAttribute("height");
  1360. selectedItemIcon.getElement().removeAttribute("width");
  1361. selectedItemIcon.addDomHandler(new LoadHandler() {
  1362. @Override
  1363. public void onLoad(LoadEvent event) {
  1364. afterSelectedItemIconChange();
  1365. }
  1366. }, LoadEvent.getType());
  1367. panel.insert(selectedItemIcon, 0);
  1368. afterSelectedItemIconChange();
  1369. }
  1370. }
  1371. private void afterSelectedItemIconChange() {
  1372. if (BrowserInfo.get().isWebkit() || BrowserInfo.get().isIE8()) {
  1373. // Some browsers need a nudge to reposition the text field
  1374. forceReflow();
  1375. }
  1376. updateRootWidth();
  1377. if (selectedItemIcon != null) {
  1378. updateSelectedIconPosition();
  1379. }
  1380. }
  1381. private void forceReflow() {
  1382. WidgetUtil.setStyleTemporarily(tb.getElement(), "zoom", "1");
  1383. }
  1384. /**
  1385. * Positions the icon vertically in the middle. Should be called after the
  1386. * icon has loaded
  1387. */
  1388. private void updateSelectedIconPosition() {
  1389. // Position icon vertically to middle
  1390. int availableHeight = 0;
  1391. availableHeight = getOffsetHeight();
  1392. int iconHeight = WidgetUtil.getRequiredHeight(selectedItemIcon);
  1393. int marginTop = (availableHeight - iconHeight) / 2;
  1394. selectedItemIcon.getElement().getStyle()
  1395. .setMarginTop(marginTop, Unit.PX);
  1396. }
  1397. private static Set<Integer> navigationKeyCodes = new HashSet<Integer>();
  1398. static {
  1399. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  1400. navigationKeyCodes.add(KeyCodes.KEY_UP);
  1401. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  1402. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  1403. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  1404. }
  1405. /*
  1406. * (non-Javadoc)
  1407. *
  1408. * @see
  1409. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1410. * .event.dom.client.KeyDownEvent)
  1411. */
  1412. @Override
  1413. public void onKeyDown(KeyDownEvent event) {
  1414. if (enabled && !readonly) {
  1415. int keyCode = event.getNativeKeyCode();
  1416. if (enableDebug) {
  1417. debug("VFS: key down: " + keyCode);
  1418. }
  1419. if (waitingForFilteringResponse
  1420. && navigationKeyCodes.contains(keyCode)) {
  1421. /*
  1422. * Keyboard navigation events should not be handled while we are
  1423. * waiting for a response. This avoids flickering, disappearing
  1424. * items, wrongly interpreted responses and more.
  1425. */
  1426. if (enableDebug) {
  1427. debug("Ignoring "
  1428. + keyCode
  1429. + " because we are waiting for a filtering response");
  1430. }
  1431. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1432. event.stopPropagation();
  1433. return;
  1434. }
  1435. if (suggestionPopup.isAttached()) {
  1436. if (enableDebug) {
  1437. debug("Keycode " + keyCode + " target is popup");
  1438. }
  1439. popupKeyDown(event);
  1440. } else {
  1441. if (enableDebug) {
  1442. debug("Keycode " + keyCode + " target is text field");
  1443. }
  1444. inputFieldKeyDown(event);
  1445. }
  1446. }
  1447. }
  1448. private void debug(String string) {
  1449. if (enableDebug) {
  1450. VConsole.error(string);
  1451. }
  1452. }
  1453. /**
  1454. * Triggered when a key is pressed in the text box
  1455. *
  1456. * @param event
  1457. * The KeyDownEvent
  1458. */
  1459. private void inputFieldKeyDown(KeyDownEvent event) {
  1460. if (enableDebug) {
  1461. debug("VFS: inputFieldKeyDown(" + event.getNativeKeyCode() + ")");
  1462. }
  1463. switch (event.getNativeKeyCode()) {
  1464. case KeyCodes.KEY_DOWN:
  1465. case KeyCodes.KEY_UP:
  1466. case KeyCodes.KEY_PAGEDOWN:
  1467. case KeyCodes.KEY_PAGEUP:
  1468. // open popup as from gadget
  1469. filterOptions(-1, "");
  1470. lastFilter = "";
  1471. tb.selectAll();
  1472. break;
  1473. case KeyCodes.KEY_ENTER:
  1474. /*
  1475. * This only handles the case when new items is allowed, a text is
  1476. * entered, the popup opener button is clicked to close the popup
  1477. * and enter is then pressed (see #7560).
  1478. */
  1479. if (!allowNewItem) {
  1480. return;
  1481. }
  1482. if (currentSuggestion != null
  1483. && tb.getText().equals(
  1484. currentSuggestion.getReplacementString())) {
  1485. // Retain behavior from #6686 by returning without stopping
  1486. // propagation if there's nothing to do
  1487. return;
  1488. }
  1489. suggestionPopup.menu.doSelectedItemAction();
  1490. event.stopPropagation();
  1491. break;
  1492. }
  1493. }
  1494. /**
  1495. * Triggered when a key was pressed in the suggestion popup.
  1496. *
  1497. * @param event
  1498. * The KeyDownEvent of the key
  1499. */
  1500. private void popupKeyDown(KeyDownEvent event) {
  1501. if (enableDebug) {
  1502. debug("VFS: popupKeyDown(" + event.getNativeKeyCode() + ")");
  1503. }
  1504. // Propagation of handled events is stopped so other handlers such as
  1505. // shortcut key handlers do not also handle the same events.
  1506. switch (event.getNativeKeyCode()) {
  1507. case KeyCodes.KEY_DOWN:
  1508. suggestionPopup.selectNextItem();
  1509. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1510. event.stopPropagation();
  1511. break;
  1512. case KeyCodes.KEY_UP:
  1513. suggestionPopup.selectPrevItem();
  1514. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1515. event.stopPropagation();
  1516. break;
  1517. case KeyCodes.KEY_PAGEDOWN:
  1518. selectNextPage();
  1519. event.stopPropagation();
  1520. break;
  1521. case KeyCodes.KEY_PAGEUP:
  1522. selectPrevPage();
  1523. event.stopPropagation();
  1524. break;
  1525. case KeyCodes.KEY_ESCAPE:
  1526. reset();
  1527. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1528. event.stopPropagation();
  1529. break;
  1530. case KeyCodes.KEY_TAB:
  1531. case KeyCodes.KEY_ENTER:
  1532. if (!allowNewItem) {
  1533. onSuggestionSelected(currentSuggestions
  1534. .get(suggestionPopup.menu.getSelectedIndex()));
  1535. } else {
  1536. // Handle addition of new items.
  1537. suggestionPopup.menu.doSelectedItemAction();
  1538. }
  1539. event.stopPropagation();
  1540. break;
  1541. }
  1542. }
  1543. /*
  1544. * Show the prev page.
  1545. */
  1546. private void selectPrevPage() {
  1547. if (currentPage > 0) {
  1548. filterOptions(currentPage - 1, lastFilter);
  1549. selectPopupItemWhenResponseIsReceived = Select.LAST;
  1550. }
  1551. }
  1552. /*
  1553. * Show the next page.
  1554. */
  1555. private void selectNextPage() {
  1556. if (hasNextPage()) {
  1557. filterOptions(currentPage + 1, lastFilter);
  1558. selectPopupItemWhenResponseIsReceived = Select.FIRST;
  1559. }
  1560. }
  1561. /**
  1562. * Triggered when a key was depressed
  1563. *
  1564. * @param event
  1565. * The KeyUpEvent of the key depressed
  1566. */
  1567. @Override
  1568. public void onKeyUp(KeyUpEvent event) {
  1569. if (enableDebug) {
  1570. debug("VFS: onKeyUp(" + event.getNativeKeyCode() + ")");
  1571. }
  1572. if (enabled && !readonly) {
  1573. switch (event.getNativeKeyCode()) {
  1574. case KeyCodes.KEY_ENTER:
  1575. case KeyCodes.KEY_TAB:
  1576. case KeyCodes.KEY_SHIFT:
  1577. case KeyCodes.KEY_CTRL:
  1578. case KeyCodes.KEY_ALT:
  1579. case KeyCodes.KEY_DOWN:
  1580. case KeyCodes.KEY_UP:
  1581. case KeyCodes.KEY_PAGEDOWN:
  1582. case KeyCodes.KEY_PAGEUP:
  1583. case KeyCodes.KEY_ESCAPE:
  1584. // NOP
  1585. break;
  1586. default:
  1587. if (textInputEnabled) {
  1588. // when filtering, we always want to see the results on the
  1589. // first page first.
  1590. filterOptions(0);
  1591. }
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. * Resets the Select to its initial state
  1598. */
  1599. private void reset() {
  1600. debug("VFS: reset()");
  1601. if (currentSuggestion != null) {
  1602. String text = currentSuggestion.getReplacementString();
  1603. setPromptingOff(text);
  1604. setSelectedItemIcon(currentSuggestion.getIconUri());
  1605. selectedOptionKey = currentSuggestion.key;
  1606. } else {
  1607. if (focused || readonly || !enabled) {
  1608. setPromptingOff("");
  1609. } else {
  1610. setPromptingOn();
  1611. }
  1612. setSelectedItemIcon(null);
  1613. selectedOptionKey = null;
  1614. }
  1615. lastFilter = "";
  1616. suggestionPopup.hide();
  1617. }
  1618. /**
  1619. * Listener for popupopener
  1620. */
  1621. @Override
  1622. public void onClick(ClickEvent event) {
  1623. debug("VFS: onClick()");
  1624. if (textInputEnabled
  1625. && event.getNativeEvent().getEventTarget().cast() == tb
  1626. .getElement()) {
  1627. // Don't process clicks on the text field if text input is enabled
  1628. return;
  1629. }
  1630. if (enabled && !readonly) {
  1631. // ask suggestionPopup if it was just closed, we are using GWT
  1632. // Popup's auto close feature
  1633. if (!suggestionPopup.isJustClosed()) {
  1634. // If a focus event is not going to be sent, send the options
  1635. // request immediately; otherwise queue in the same burst as the
  1636. // focus event. Fixes #8321.
  1637. boolean immediate = focused
  1638. || !client.hasEventListeners(this, EventId.FOCUS);
  1639. filterOptions(-1, "", immediate);
  1640. popupOpenerClicked = true;
  1641. lastFilter = "";
  1642. }
  1643. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1644. focus();
  1645. tb.selectAll();
  1646. }
  1647. }
  1648. /**
  1649. * Update minimum width for FilterSelect textarea based on input prompt and
  1650. * suggestions.
  1651. * <p>
  1652. * For internal use only. May be removed or replaced in the future.
  1653. */
  1654. public void updateSuggestionPopupMinWidth() {
  1655. // used only to calculate minimum width
  1656. String captions = WidgetUtil.escapeHTML(inputPrompt);
  1657. for (FilterSelectSuggestion suggestion : currentSuggestions) {
  1658. // Collect captions so we can calculate minimum width for
  1659. // textarea
  1660. if (captions.length() > 0) {
  1661. captions += "|";
  1662. }
  1663. captions += WidgetUtil
  1664. .escapeHTML(suggestion.getReplacementString());
  1665. }
  1666. // Calculate minimum textarea width
  1667. suggestionPopupMinWidth = minWidth(captions);
  1668. }
  1669. /**
  1670. * Calculate minimum width for FilterSelect textarea.
  1671. * <p>
  1672. * For internal use only. May be removed or replaced in the future.
  1673. */
  1674. public native int minWidth(String captions)
  1675. /*-{
  1676. if(!captions || captions.length <= 0)
  1677. return 0;
  1678. captions = captions.split("|");
  1679. var d = $wnd.document.createElement("div");
  1680. var html = "";
  1681. for(var i=0; i < captions.length; i++) {
  1682. html += "<div>" + captions[i] + "</div>";
  1683. // TODO apply same CSS classname as in suggestionmenu
  1684. }
  1685. d.style.position = "absolute";
  1686. d.style.top = "0";
  1687. d.style.left = "0";
  1688. d.style.visibility = "hidden";
  1689. d.innerHTML = html;
  1690. $wnd.document.body.appendChild(d);
  1691. var w = d.offsetWidth;
  1692. $wnd.document.body.removeChild(d);
  1693. return w;
  1694. }-*/;
  1695. /**
  1696. * A flag which prevents a focus event from taking place
  1697. */
  1698. boolean iePreventNextFocus = false;
  1699. /*
  1700. * (non-Javadoc)
  1701. *
  1702. * @see
  1703. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1704. * .dom.client.FocusEvent)
  1705. */
  1706. @Override
  1707. public void onFocus(FocusEvent event) {
  1708. debug("VFS: onFocus()");
  1709. /*
  1710. * When we disable a blur event in ie we need to refocus the textfield.
  1711. * This will cause a focus event we do not want to process, so in that
  1712. * case we just ignore it.
  1713. */
  1714. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  1715. iePreventNextFocus = false;
  1716. return;
  1717. }
  1718. focused = true;
  1719. if (prompting && !readonly) {
  1720. setPromptingOff("");
  1721. }
  1722. addStyleDependentName("focus");
  1723. if (client.hasEventListeners(this, EventId.FOCUS)) {
  1724. client.updateVariable(paintableId, EventId.FOCUS, "", true);
  1725. afterUpdateClientVariables();
  1726. }
  1727. ComponentConnector connector = ConnectorMap.get(client).getConnector(
  1728. this);
  1729. client.getVTooltip().showAssistive(
  1730. connector.getTooltipInfo(getElement()));
  1731. }
  1732. /**
  1733. * A flag which cancels the blur event and sets the focus back to the
  1734. * textfield if the Browser is IE
  1735. */
  1736. boolean preventNextBlurEventInIE = false;
  1737. /*
  1738. * (non-Javadoc)
  1739. *
  1740. * @see
  1741. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  1742. * .dom.client.BlurEvent)
  1743. */
  1744. @Override
  1745. public void onBlur(BlurEvent event) {
  1746. debug("VFS: onBlur()");
  1747. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  1748. /*
  1749. * Clicking in the suggestion popup or on the popup button in IE
  1750. * causes a blur event to be sent for the field. In other browsers
  1751. * this is prevented by canceling/preventing default behavior for
  1752. * the focus event, in IE we handle it here by refocusing the text
  1753. * field and ignoring the resulting focus event for the textfield
  1754. * (in onFocus).
  1755. */
  1756. preventNextBlurEventInIE = false;
  1757. Element focusedElement = WidgetUtil.getFocusedElement();
  1758. if (getElement().isOrHasChild(focusedElement)
  1759. || suggestionPopup.getElement()
  1760. .isOrHasChild(focusedElement)) {
  1761. // IF the suggestion popup or another part of the VFilterSelect
  1762. // was focused, move the focus back to the textfield and prevent
  1763. // the triggered focus event (in onFocus).
  1764. iePreventNextFocus = true;
  1765. tb.setFocus(true);
  1766. return;
  1767. }
  1768. }
  1769. focused = false;
  1770. if (!readonly) {
  1771. if (selectedOptionKey == null) {
  1772. setPromptingOn();
  1773. } else if (currentSuggestion != null) {
  1774. setPromptingOff(currentSuggestion.caption);
  1775. }
  1776. }
  1777. removeStyleDependentName("focus");
  1778. if (client.hasEventListeners(this, EventId.BLUR)) {
  1779. client.updateVariable(paintableId, EventId.BLUR, "", true);
  1780. afterUpdateClientVariables();
  1781. }
  1782. }
  1783. /*
  1784. * (non-Javadoc)
  1785. *
  1786. * @see com.vaadin.client.Focusable#focus()
  1787. */
  1788. @Override
  1789. public void focus() {
  1790. debug("VFS: focus()");
  1791. focused = true;
  1792. if (prompting && !readonly) {
  1793. setPromptingOff("");
  1794. }
  1795. tb.setFocus(true);
  1796. }
  1797. /**
  1798. * Calculates the width of the select if the select has undefined width.
  1799. * Should be called when the width changes or when the icon changes.
  1800. * <p>
  1801. * For internal use only. May be removed or replaced in the future.
  1802. */
  1803. public void updateRootWidth() {
  1804. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  1805. this);
  1806. if (paintable.isUndefinedWidth()) {
  1807. /*
  1808. * When the select has a undefined with we need to check that we are
  1809. * only setting the text box width relative to the first page width
  1810. * of the items. If this is not done the text box width will change
  1811. * when the popup is used to view longer items than the text box is
  1812. * wide.
  1813. */
  1814. int w = WidgetUtil.getRequiredWidth(this);
  1815. if ((!initDone || currentPage + 1 < 0)
  1816. && suggestionPopupMinWidth > w) {
  1817. /*
  1818. * We want to compensate for the paddings just to preserve the
  1819. * exact size as in Vaadin 6.x, but we get here before
  1820. * MeasuredSize has been initialized.
  1821. * Util.measureHorizontalPaddingAndBorder does not work with
  1822. * border-box, so we must do this the hard way.
  1823. */
  1824. Style style = getElement().getStyle();
  1825. String originalPadding = style.getPadding();
  1826. String originalBorder = style.getBorderWidth();
  1827. style.setPaddingLeft(0, Unit.PX);
  1828. style.setBorderWidth(0, Unit.PX);
  1829. style.setProperty("padding", originalPadding);
  1830. style.setProperty("borderWidth", originalBorder);
  1831. // Use util.getRequiredWidth instead of getOffsetWidth here
  1832. int iconWidth = selectedItemIcon == null ? 0 : WidgetUtil
  1833. .getRequiredWidth(selectedItemIcon);
  1834. int buttonWidth = popupOpener == null ? 0 : WidgetUtil
  1835. .getRequiredWidth(popupOpener);
  1836. /*
  1837. * Instead of setting the width of the wrapper, set the width of
  1838. * the combobox. Subtract the width of the icon and the
  1839. * popupopener
  1840. */
  1841. tb.setWidth((suggestionPopupMinWidth - iconWidth - buttonWidth)
  1842. + "px");
  1843. }
  1844. /*
  1845. * Lock the textbox width to its current value if it's not already
  1846. * locked
  1847. */
  1848. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  1849. int iconWidth = selectedItemIcon == null ? 0 : selectedItemIcon
  1850. .getOffsetWidth();
  1851. tb.setWidth((tb.getOffsetWidth() - iconWidth) + "px");
  1852. }
  1853. }
  1854. }
  1855. /**
  1856. * Get the width of the select in pixels where the text area and icon has
  1857. * been included.
  1858. *
  1859. * @return The width in pixels
  1860. */
  1861. private int getMainWidth() {
  1862. return getOffsetWidth();
  1863. }
  1864. @Override
  1865. public void setWidth(String width) {
  1866. super.setWidth(width);
  1867. if (width.length() != 0) {
  1868. tb.setWidth("100%");
  1869. }
  1870. }
  1871. /**
  1872. * Handles special behavior of the mouse down event
  1873. *
  1874. * @param event
  1875. */
  1876. private void handleMouseDownEvent(Event event) {
  1877. /*
  1878. * Prevent the keyboard focus from leaving the textfield by preventing
  1879. * the default behaviour of the browser. Fixes #4285.
  1880. */
  1881. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  1882. event.preventDefault();
  1883. event.stopPropagation();
  1884. /*
  1885. * In IE the above wont work, the blur event will still trigger. So,
  1886. * we set a flag here to prevent the next blur event from happening.
  1887. * This is not needed if do not already have focus, in that case
  1888. * there will not be any blur event and we should not cancel the
  1889. * next blur.
  1890. */
  1891. if (BrowserInfo.get().isIE() && focused) {
  1892. preventNextBlurEventInIE = true;
  1893. debug("VFS: Going to prevent next blur event on IE");
  1894. }
  1895. }
  1896. }
  1897. @Override
  1898. protected void onDetach() {
  1899. super.onDetach();
  1900. suggestionPopup.hide();
  1901. }
  1902. @Override
  1903. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  1904. if ("textbox".equals(subPart)) {
  1905. return tb.getElement();
  1906. } else if ("button".equals(subPart)) {
  1907. return popupOpener.getElement();
  1908. } else if ("popup".equals(subPart) && suggestionPopup.isAttached()) {
  1909. return suggestionPopup.getElement();
  1910. }
  1911. return null;
  1912. }
  1913. @Override
  1914. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  1915. if (tb.getElement().isOrHasChild(subElement)) {
  1916. return "textbox";
  1917. } else if (popupOpener.getElement().isOrHasChild(subElement)) {
  1918. return "button";
  1919. } else if (suggestionPopup.getElement().isOrHasChild(subElement)) {
  1920. return "popup";
  1921. }
  1922. return null;
  1923. }
  1924. @Override
  1925. public void setAriaRequired(boolean required) {
  1926. AriaHelper.handleInputRequired(tb, required);
  1927. }
  1928. @Override
  1929. public void setAriaInvalid(boolean invalid) {
  1930. AriaHelper.handleInputInvalid(tb, invalid);
  1931. }
  1932. @Override
  1933. public void bindAriaCaption(
  1934. com.google.gwt.user.client.Element captionElement) {
  1935. AriaHelper.bindCaption(tb, captionElement);
  1936. }
  1937. /*
  1938. * Anything that should be set after the client updates the server.
  1939. */
  1940. private void afterUpdateClientVariables() {
  1941. // We need this here to be consistent with the all the calls.
  1942. // Then set your specific selection type only after
  1943. // client.updateVariable() method call.
  1944. selectPopupItemWhenResponseIsReceived = Select.NONE;
  1945. }
  1946. }