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

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