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

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