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.

VUI.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 com.google.gwt.core.client.Scheduler;
  19. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  20. import com.google.gwt.dom.client.Element;
  21. import com.google.gwt.event.dom.client.HasScrollHandlers;
  22. import com.google.gwt.event.dom.client.ScrollEvent;
  23. import com.google.gwt.event.dom.client.ScrollHandler;
  24. import com.google.gwt.event.logical.shared.HasResizeHandlers;
  25. import com.google.gwt.event.logical.shared.ResizeEvent;
  26. import com.google.gwt.event.logical.shared.ResizeHandler;
  27. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  28. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  29. import com.google.gwt.event.shared.HandlerRegistration;
  30. import com.google.gwt.http.client.URL;
  31. import com.google.gwt.user.client.DOM;
  32. import com.google.gwt.user.client.Event;
  33. import com.google.gwt.user.client.History;
  34. import com.google.gwt.user.client.Timer;
  35. import com.google.gwt.user.client.Window;
  36. import com.google.gwt.user.client.ui.SimplePanel;
  37. import com.vaadin.client.ApplicationConnection;
  38. import com.vaadin.client.BrowserInfo;
  39. import com.vaadin.client.ComponentConnector;
  40. import com.vaadin.client.ConnectorMap;
  41. import com.vaadin.client.Focusable;
  42. import com.vaadin.client.LayoutManager;
  43. import com.vaadin.client.Profiler;
  44. import com.vaadin.client.Util;
  45. import com.vaadin.client.VConsole;
  46. import com.vaadin.client.ui.ShortcutActionHandler.ShortcutActionHandlerOwner;
  47. import com.vaadin.client.ui.TouchScrollDelegate.TouchScrollHandler;
  48. import com.vaadin.client.ui.ui.UIConnector;
  49. import com.vaadin.shared.ApplicationConstants;
  50. import com.vaadin.shared.ui.ui.UIConstants;
  51. /**
  52. *
  53. */
  54. public class VUI extends SimplePanel implements ResizeHandler,
  55. Window.ClosingHandler, ShortcutActionHandlerOwner, Focusable,
  56. com.google.gwt.user.client.ui.Focusable, HasResizeHandlers,
  57. HasScrollHandlers {
  58. private static int MONITOR_PARENT_TIMER_INTERVAL = 1000;
  59. /** For internal use only. May be removed or replaced in the future. */
  60. public String id;
  61. /** For internal use only. May be removed or replaced in the future. */
  62. public ShortcutActionHandler actionHandler;
  63. /*
  64. * Last known window size used to detect whether VView should be layouted
  65. * again. Detection must check window size, because the VView size might be
  66. * fixed and thus not automatically adapt to changed window sizes.
  67. */
  68. private int windowWidth;
  69. private int windowHeight;
  70. /*
  71. * Last know view size used to detect whether new dimensions should be sent
  72. * to the server.
  73. */
  74. private int viewWidth;
  75. private int viewHeight;
  76. /** For internal use only. May be removed or replaced in the future. */
  77. public ApplicationConnection connection;
  78. /**
  79. * Keep track of possible parent size changes when an embedded application.
  80. *
  81. * Uses {@link #parentWidth} and {@link #parentHeight} as an optimization to
  82. * keep track of when there is a real change.
  83. */
  84. private Timer resizeTimer;
  85. /** stored width of parent for embedded application auto-resize */
  86. private int parentWidth;
  87. /** stored height of parent for embedded application auto-resize */
  88. private int parentHeight;
  89. /** For internal use only. May be removed or replaced in the future. */
  90. public boolean immediate;
  91. /** For internal use only. May be removed or replaced in the future. */
  92. public boolean resizeLazy = false;
  93. private HandlerRegistration historyHandlerRegistration;
  94. private TouchScrollHandler touchScrollHandler;
  95. /**
  96. * The current URI fragment, used to avoid sending updates if nothing has
  97. * changed.
  98. * <p>
  99. * For internal use only. May be removed or replaced in the future.
  100. */
  101. public String currentFragment;
  102. /**
  103. * Listener for URI fragment changes. Notifies the server of the new value
  104. * whenever the value changes.
  105. */
  106. private final ValueChangeHandler<String> historyChangeHandler = new ValueChangeHandler<String>() {
  107. @Override
  108. public void onValueChange(ValueChangeEvent<String> event) {
  109. String newFragment = event.getValue();
  110. // Send the location to the server if the fragment has changed
  111. // and flush active connectors in UI.
  112. if (!newFragment.equals(currentFragment) && connection != null) {
  113. /*
  114. * Ensure the fragment is properly encoded in all browsers
  115. * (#10769)
  116. *
  117. * createUrlBuilder does not properly pass an empty fragment to
  118. * UrlBuilder on Webkit browsers so do it manually (#11686)
  119. */
  120. String location = Window.Location
  121. .createUrlBuilder()
  122. .setHash(
  123. URL.decodeQueryString(Window.Location.getHash()))
  124. .buildString();
  125. currentFragment = newFragment;
  126. connection.flushActiveConnector();
  127. connection.updateVariable(id, UIConstants.LOCATION_VARIABLE,
  128. location, true);
  129. }
  130. }
  131. };
  132. private VLazyExecutor delayedResizeExecutor = new VLazyExecutor(200,
  133. new ScheduledCommand() {
  134. @Override
  135. public void execute() {
  136. performSizeCheck();
  137. }
  138. });
  139. private Element storedFocus;
  140. public VUI() {
  141. super();
  142. // Allow focusing the view by using the focus() method, the view
  143. // should not be in the document focus flow
  144. getElement().setTabIndex(-1);
  145. makeScrollable();
  146. }
  147. /**
  148. * Start to periodically monitor for parent element resizes if embedded
  149. * application (e.g. portlet).
  150. */
  151. @Override
  152. protected void onLoad() {
  153. super.onLoad();
  154. if (isMonitoringParentSize()) {
  155. resizeTimer = new Timer() {
  156. @Override
  157. public void run() {
  158. // trigger check to see if parent size has changed,
  159. // recalculate layouts
  160. performSizeCheck();
  161. resizeTimer.schedule(MONITOR_PARENT_TIMER_INTERVAL);
  162. }
  163. };
  164. resizeTimer.schedule(MONITOR_PARENT_TIMER_INTERVAL);
  165. }
  166. }
  167. @Override
  168. protected void onAttach() {
  169. super.onAttach();
  170. historyHandlerRegistration = History
  171. .addValueChangeHandler(historyChangeHandler);
  172. currentFragment = History.getToken();
  173. }
  174. @Override
  175. protected void onDetach() {
  176. super.onDetach();
  177. historyHandlerRegistration.removeHandler();
  178. historyHandlerRegistration = null;
  179. }
  180. /**
  181. * Stop monitoring for parent element resizes.
  182. */
  183. @Override
  184. protected void onUnload() {
  185. if (resizeTimer != null) {
  186. resizeTimer.cancel();
  187. resizeTimer = null;
  188. }
  189. super.onUnload();
  190. }
  191. /**
  192. * Called when the window or parent div might have been resized.
  193. *
  194. * This immediately checks the sizes of the window and the parent div (if
  195. * monitoring it) and triggers layout recalculation if they have changed.
  196. */
  197. protected void performSizeCheck() {
  198. windowSizeMaybeChanged(Window.getClientWidth(),
  199. Window.getClientHeight());
  200. }
  201. /**
  202. * Called when the window or parent div might have been resized.
  203. *
  204. * This immediately checks the sizes of the window and the parent div (if
  205. * monitoring it) and triggers layout recalculation if they have changed.
  206. *
  207. * @param newWindowWidth
  208. * The new width of the window
  209. * @param newWindowHeight
  210. * The new height of the window
  211. *
  212. * @deprecated use {@link #performSizeCheck()}
  213. */
  214. @Deprecated
  215. protected void windowSizeMaybeChanged(int newWindowWidth,
  216. int newWindowHeight) {
  217. if (connection == null) {
  218. // Connection is null if the timer fires before the first UIDL
  219. // update
  220. return;
  221. }
  222. boolean changed = false;
  223. ComponentConnector connector = ConnectorMap.get(connection)
  224. .getConnector(this);
  225. if (windowWidth != newWindowWidth) {
  226. windowWidth = newWindowWidth;
  227. changed = true;
  228. connector.getLayoutManager().reportOuterWidth(connector,
  229. newWindowWidth);
  230. VConsole.log("New window width: " + windowWidth);
  231. }
  232. if (windowHeight != newWindowHeight) {
  233. windowHeight = newWindowHeight;
  234. changed = true;
  235. connector.getLayoutManager().reportOuterHeight(connector,
  236. newWindowHeight);
  237. VConsole.log("New window height: " + windowHeight);
  238. }
  239. Element parentElement = getElement().getParentElement();
  240. if (isMonitoringParentSize() && parentElement != null) {
  241. // check also for parent size changes
  242. int newParentWidth = parentElement.getClientWidth();
  243. int newParentHeight = parentElement.getClientHeight();
  244. if (parentWidth != newParentWidth) {
  245. parentWidth = newParentWidth;
  246. changed = true;
  247. VConsole.log("New parent width: " + parentWidth);
  248. }
  249. if (parentHeight != newParentHeight) {
  250. parentHeight = newParentHeight;
  251. changed = true;
  252. VConsole.log("New parent height: " + parentHeight);
  253. }
  254. }
  255. if (changed) {
  256. /*
  257. * If the window size has changed, layout the VView again and send
  258. * new size to the server if the size changed. (Just checking VView
  259. * size would cause us to ignore cases when a relatively sized VView
  260. * should shrink as the content's size is fixed and would thus not
  261. * automatically shrink.)
  262. */
  263. VConsole.log("Running layout functions due to window or parent resize");
  264. // update size to avoid (most) redundant re-layout passes
  265. // there can still be an extra layout recalculation if webkit
  266. // overflow fix updates the size in a deferred block
  267. if (isMonitoringParentSize() && parentElement != null) {
  268. parentWidth = parentElement.getClientWidth();
  269. parentHeight = parentElement.getClientHeight();
  270. }
  271. sendClientResized();
  272. LayoutManager layoutManager = connector.getLayoutManager();
  273. if (layoutManager.isLayoutRunning()) {
  274. layoutManager.layoutLater();
  275. } else {
  276. layoutManager.layoutNow();
  277. }
  278. }
  279. }
  280. /**
  281. * @return the name of the theme in use by this UI.
  282. * @deprecated as of 7.3. Use {@link UIConnector#getActiveTheme()} instead.
  283. */
  284. @Deprecated
  285. public String getTheme() {
  286. return ((UIConnector) ConnectorMap.get(connection).getConnector(this))
  287. .getActiveTheme();
  288. }
  289. /**
  290. * Returns true if the body is NOT generated, i.e if someone else has made
  291. * the page that we're running in. Otherwise we're in charge of the whole
  292. * page.
  293. *
  294. * @return true if we're running embedded
  295. */
  296. public boolean isEmbedded() {
  297. return !getElement().getOwnerDocument().getBody().getClassName()
  298. .contains(ApplicationConstants.GENERATED_BODY_CLASSNAME);
  299. }
  300. /**
  301. * Returns true if the size of the parent should be checked periodically and
  302. * the application should react to its changes.
  303. *
  304. * @return true if size of parent should be tracked
  305. */
  306. protected boolean isMonitoringParentSize() {
  307. // could also perform a more specific check (Liferay portlet)
  308. return isEmbedded();
  309. }
  310. @Override
  311. public void onBrowserEvent(Event event) {
  312. super.onBrowserEvent(event);
  313. int type = DOM.eventGetType(event);
  314. if (type == Event.ONKEYDOWN && actionHandler != null) {
  315. actionHandler.handleKeyboardEvent(event);
  316. return;
  317. }
  318. }
  319. /*
  320. * (non-Javadoc)
  321. *
  322. * @see
  323. * com.google.gwt.event.logical.shared.ResizeHandler#onResize(com.google
  324. * .gwt.event.logical.shared.ResizeEvent)
  325. */
  326. @Override
  327. public void onResize(ResizeEvent event) {
  328. triggerSizeChangeCheck();
  329. }
  330. /**
  331. * Called when a resize event is received.
  332. *
  333. * This may trigger a lazy refresh or perform the size check immediately
  334. * depending on the browser used and whether the server side requests
  335. * resizes to be lazy.
  336. */
  337. private void triggerSizeChangeCheck() {
  338. /*
  339. * IE (pre IE9 at least) will give us some false resize events due to
  340. * problems with scrollbars. Firefox 3 might also produce some extra
  341. * events. We postpone both the re-layouting and the server side event
  342. * for a while to deal with these issues.
  343. *
  344. * We may also postpone these events to avoid slowness when resizing the
  345. * browser window. Constantly recalculating the layout causes the resize
  346. * operation to be really slow with complex layouts.
  347. */
  348. boolean lazy = resizeLazy || BrowserInfo.get().isIE8();
  349. if (lazy) {
  350. delayedResizeExecutor.trigger();
  351. } else {
  352. performSizeCheck();
  353. }
  354. }
  355. /**
  356. * Send new dimensions to the server.
  357. * <p>
  358. * For internal use only. May be removed or replaced in the future.
  359. */
  360. public void sendClientResized() {
  361. Profiler.enter("VUI.sendClientResized");
  362. Element parentElement = getElement().getParentElement();
  363. int viewHeight = parentElement.getClientHeight();
  364. int viewWidth = parentElement.getClientWidth();
  365. ResizeEvent.fire(this, viewWidth, viewHeight);
  366. Profiler.leave("VUI.sendClientResized");
  367. }
  368. public native static void goTo(String url)
  369. /*-{
  370. $wnd.location = url;
  371. }-*/;
  372. @Override
  373. public void onWindowClosing(Window.ClosingEvent event) {
  374. // Change focus on this window in order to ensure that all state is
  375. // collected from textfields
  376. // TODO this is a naive hack, that only works with text fields and may
  377. // cause some odd issues. Should be replaced with a decent solution, see
  378. // also related BeforeShortcutActionListener interface. Same interface
  379. // might be usable here.
  380. VTextField.flushChangesFromFocusedTextField();
  381. }
  382. private native static void loadAppIdListFromDOM(ArrayList<String> list)
  383. /*-{
  384. var j;
  385. for(j in $wnd.vaadin.vaadinConfigurations) {
  386. // $entry not needed as function is not exported
  387. list.@java.util.Collection::add(Ljava/lang/Object;)(j);
  388. }
  389. }-*/;
  390. @Override
  391. public ShortcutActionHandler getShortcutActionHandler() {
  392. return actionHandler;
  393. }
  394. @Override
  395. public void focus() {
  396. setFocus(true);
  397. }
  398. /**
  399. * Ensures the widget is scrollable eg. after style name changes.
  400. * <p>
  401. * For internal use only. May be removed or replaced in the future.
  402. */
  403. public void makeScrollable() {
  404. if (touchScrollHandler == null) {
  405. touchScrollHandler = TouchScrollDelegate.enableTouchScrolling(this);
  406. }
  407. touchScrollHandler.addElement(getElement());
  408. }
  409. @Override
  410. public HandlerRegistration addResizeHandler(ResizeHandler resizeHandler) {
  411. return addHandler(resizeHandler, ResizeEvent.getType());
  412. }
  413. @Override
  414. public HandlerRegistration addScrollHandler(ScrollHandler scrollHandler) {
  415. return addHandler(scrollHandler, ScrollEvent.getType());
  416. }
  417. @Override
  418. public int getTabIndex() {
  419. return FocusUtil.getTabIndex(this);
  420. }
  421. @Override
  422. public void setAccessKey(char key) {
  423. FocusUtil.setAccessKey(this, key);
  424. }
  425. @Override
  426. public void setFocus(boolean focused) {
  427. FocusUtil.setFocus(this, focused);
  428. }
  429. @Override
  430. public void setTabIndex(int index) {
  431. FocusUtil.setTabIndex(this, index);
  432. }
  433. /**
  434. * Allows to store the currently focused Element.
  435. *
  436. * Current use case is to store the focus when a Window is opened. Does
  437. * currently handle only a single value. Needs to be extended for #12158
  438. *
  439. * @param focusedElement
  440. */
  441. public void storeFocus() {
  442. storedFocus = Util.getFocusedElement();
  443. }
  444. /**
  445. * Restores the previously stored focus Element.
  446. *
  447. * Current use case is to restore the focus when a Window is closed. Does
  448. * currently handle only a single value. Needs to be extended for #12158
  449. *
  450. * @return the lastFocusElementBeforeDialogOpened
  451. */
  452. public void focusStoredElement() {
  453. if (storedFocus != null) {
  454. storedFocus.focus();
  455. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  456. @Override
  457. public void execute() {
  458. storedFocus.focus();
  459. }
  460. });
  461. }
  462. }
  463. }