PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 1ms

/client/src/com/vaadin/client/ui/VScrollTable.java

https://gitlab.com/jforge/vaadin
Java | 8325 lines | 5466 code | 953 blank | 1906 comment | 1415 complexity | e5a41e48273a9459c0495e8de6bb5d1e MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0-no-copyleft-exception, 0BSD, EPL-1.0, LGPL-2.0, LGPL-2.1, BSD-3-Clause, JSON
  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.HashMap;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import com.google.gwt.core.client.JavaScriptObject;
  29. import com.google.gwt.core.client.Scheduler;
  30. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  31. import com.google.gwt.dom.client.Document;
  32. import com.google.gwt.dom.client.Element;
  33. import com.google.gwt.dom.client.NativeEvent;
  34. import com.google.gwt.dom.client.Node;
  35. import com.google.gwt.dom.client.NodeList;
  36. import com.google.gwt.dom.client.Style;
  37. import com.google.gwt.dom.client.Style.Display;
  38. import com.google.gwt.dom.client.Style.Overflow;
  39. import com.google.gwt.dom.client.Style.Position;
  40. import com.google.gwt.dom.client.Style.TextAlign;
  41. import com.google.gwt.dom.client.Style.Unit;
  42. import com.google.gwt.dom.client.Style.Visibility;
  43. import com.google.gwt.dom.client.TableCellElement;
  44. import com.google.gwt.dom.client.TableRowElement;
  45. import com.google.gwt.dom.client.TableSectionElement;
  46. import com.google.gwt.dom.client.Touch;
  47. import com.google.gwt.event.dom.client.BlurEvent;
  48. import com.google.gwt.event.dom.client.BlurHandler;
  49. import com.google.gwt.event.dom.client.FocusEvent;
  50. import com.google.gwt.event.dom.client.FocusHandler;
  51. import com.google.gwt.event.dom.client.KeyCodes;
  52. import com.google.gwt.event.dom.client.KeyDownEvent;
  53. import com.google.gwt.event.dom.client.KeyDownHandler;
  54. import com.google.gwt.event.dom.client.KeyPressEvent;
  55. import com.google.gwt.event.dom.client.KeyPressHandler;
  56. import com.google.gwt.event.dom.client.KeyUpEvent;
  57. import com.google.gwt.event.dom.client.KeyUpHandler;
  58. import com.google.gwt.event.dom.client.ScrollEvent;
  59. import com.google.gwt.event.dom.client.ScrollHandler;
  60. import com.google.gwt.event.logical.shared.CloseEvent;
  61. import com.google.gwt.event.logical.shared.CloseHandler;
  62. import com.google.gwt.event.shared.HandlerRegistration;
  63. import com.google.gwt.regexp.shared.MatchResult;
  64. import com.google.gwt.regexp.shared.RegExp;
  65. import com.google.gwt.user.client.Command;
  66. import com.google.gwt.user.client.DOM;
  67. import com.google.gwt.user.client.Event;
  68. import com.google.gwt.user.client.Event.NativePreviewEvent;
  69. import com.google.gwt.user.client.Event.NativePreviewHandler;
  70. import com.google.gwt.user.client.Timer;
  71. import com.google.gwt.user.client.Window;
  72. import com.google.gwt.user.client.ui.FlowPanel;
  73. import com.google.gwt.user.client.ui.HasWidgets;
  74. import com.google.gwt.user.client.ui.Panel;
  75. import com.google.gwt.user.client.ui.PopupPanel;
  76. import com.google.gwt.user.client.ui.UIObject;
  77. import com.google.gwt.user.client.ui.Widget;
  78. import com.vaadin.client.ApplicationConnection;
  79. import com.vaadin.client.BrowserInfo;
  80. import com.vaadin.client.ComponentConnector;
  81. import com.vaadin.client.ConnectorMap;
  82. import com.vaadin.client.DeferredWorker;
  83. import com.vaadin.client.Focusable;
  84. import com.vaadin.client.MouseEventDetailsBuilder;
  85. import com.vaadin.client.StyleConstants;
  86. import com.vaadin.client.TooltipInfo;
  87. import com.vaadin.client.UIDL;
  88. import com.vaadin.client.Util;
  89. import com.vaadin.client.VConsole;
  90. import com.vaadin.client.VTooltip;
  91. import com.vaadin.client.WidgetUtil;
  92. import com.vaadin.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
  93. import com.vaadin.client.ui.dd.DDUtil;
  94. import com.vaadin.client.ui.dd.VAbstractDropHandler;
  95. import com.vaadin.client.ui.dd.VAcceptCallback;
  96. import com.vaadin.client.ui.dd.VDragAndDropManager;
  97. import com.vaadin.client.ui.dd.VDragEvent;
  98. import com.vaadin.client.ui.dd.VHasDropHandler;
  99. import com.vaadin.client.ui.dd.VTransferable;
  100. import com.vaadin.shared.AbstractComponentState;
  101. import com.vaadin.shared.MouseEventDetails;
  102. import com.vaadin.shared.ui.dd.VerticalDropLocation;
  103. import com.vaadin.shared.ui.table.TableConstants;
  104. /**
  105. * VScrollTable
  106. *
  107. * VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
  108. * ScrollPanel
  109. *
  110. * TableHead contains table's header and widgets + logic for resizing,
  111. * reordering and hiding columns.
  112. *
  113. * ScrollPanel contains VScrollTableBody object which handles content. To save
  114. * some bandwidth and to improve clients responsiveness with loads of data, in
  115. * VScrollTableBody all rows are not necessary rendered. There are "spacers" in
  116. * VScrollTableBody to use the exact same space as non-rendered rows would use.
  117. * This way we can use seamlessly traditional scrollbars and scrolling to fetch
  118. * more rows instead of "paging".
  119. *
  120. * In VScrollTable we listen to scroll events. On horizontal scrolling we also
  121. * update TableHeads scroll position which has its scrollbars hidden. On
  122. * vertical scroll events we will check if we are reaching the end of area where
  123. * we have rows rendered and
  124. *
  125. * TODO implement unregistering for child components in Cells
  126. */
  127. public class VScrollTable extends FlowPanel implements HasWidgets,
  128. ScrollHandler, VHasDropHandler, FocusHandler, BlurHandler, Focusable,
  129. ActionOwner, SubPartAware, DeferredWorker {
  130. /**
  131. * Simple interface for parts of the table capable of owning a context menu.
  132. *
  133. * @since 7.2
  134. * @author Vaadin Ltd
  135. */
  136. private interface ContextMenuOwner {
  137. public void showContextMenu(Event event);
  138. }
  139. /**
  140. * Handles showing context menu on "long press" from a touch screen.
  141. *
  142. * @since 7.2
  143. * @author Vaadin Ltd
  144. */
  145. private class TouchContextProvider {
  146. private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
  147. private Timer contextTouchTimeout;
  148. private Event touchStart;
  149. private int touchStartY;
  150. private int touchStartX;
  151. private ContextMenuOwner target;
  152. /**
  153. * Initializes a handler for a certain context menu owner.
  154. *
  155. * @param target
  156. * the owner of the context menu
  157. */
  158. public TouchContextProvider(ContextMenuOwner target) {
  159. this.target = target;
  160. }
  161. /**
  162. * Cancels the current context touch timeout.
  163. */
  164. public void cancel() {
  165. if (contextTouchTimeout != null) {
  166. contextTouchTimeout.cancel();
  167. contextTouchTimeout = null;
  168. }
  169. touchStart = null;
  170. }
  171. /**
  172. * A function to handle touch context events in a table.
  173. *
  174. * @param event
  175. * browser event to handle
  176. */
  177. public void handleTouchEvent(final Event event) {
  178. int type = event.getTypeInt();
  179. switch (type) {
  180. case Event.ONCONTEXTMENU:
  181. target.showContextMenu(event);
  182. break;
  183. case Event.ONTOUCHSTART:
  184. // save position to fields, touches in events are same
  185. // instance during the operation.
  186. touchStart = event;
  187. Touch touch = event.getChangedTouches().get(0);
  188. touchStartX = touch.getClientX();
  189. touchStartY = touch.getClientY();
  190. if (contextTouchTimeout == null) {
  191. contextTouchTimeout = new Timer() {
  192. @Override
  193. public void run() {
  194. if (touchStart != null) {
  195. // Open the context menu if finger
  196. // is held in place long enough.
  197. target.showContextMenu(touchStart);
  198. event.preventDefault();
  199. touchStart = null;
  200. }
  201. }
  202. };
  203. }
  204. contextTouchTimeout.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  205. break;
  206. case Event.ONTOUCHCANCEL:
  207. case Event.ONTOUCHEND:
  208. cancel();
  209. break;
  210. case Event.ONTOUCHMOVE:
  211. if (isSignificantMove(event)) {
  212. // Moved finger before the context menu timer
  213. // expired, so let the browser handle the event.
  214. cancel();
  215. }
  216. }
  217. }
  218. /**
  219. * Calculates how many pixels away the user's finger has traveled. This
  220. * reduces the chance of small non-intentional movements from canceling
  221. * the long press detection.
  222. *
  223. * @param event
  224. * the Event for which to check the move distance
  225. * @return true if this is considered an intentional move by the user
  226. */
  227. protected boolean isSignificantMove(Event event) {
  228. if (touchStart == null) {
  229. // no touch start
  230. return false;
  231. }
  232. // Calculate the distance between touch start and the current touch
  233. // position
  234. Touch touch = event.getChangedTouches().get(0);
  235. int deltaX = touch.getClientX() - touchStartX;
  236. int deltaY = touch.getClientY() - touchStartY;
  237. int delta = deltaX * deltaX + deltaY * deltaY;
  238. // Compare to the square of the significant move threshold to remove
  239. // the need for a square root
  240. if (delta > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD
  241. * TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  242. return true;
  243. }
  244. return false;
  245. }
  246. }
  247. public static final String STYLENAME = "v-table";
  248. public enum SelectMode {
  249. NONE(0), SINGLE(1), MULTI(2);
  250. private int id;
  251. private SelectMode(int id) {
  252. this.id = id;
  253. }
  254. public int getId() {
  255. return id;
  256. }
  257. }
  258. private static final String ROW_HEADER_COLUMN_KEY = "0";
  259. private static final double CACHE_RATE_DEFAULT = 2;
  260. /**
  261. * The default multi select mode where simple left clicks only selects one
  262. * item, CTRL+left click selects multiple items and SHIFT-left click selects
  263. * a range of items.
  264. */
  265. private static final int MULTISELECT_MODE_DEFAULT = 0;
  266. /**
  267. * The simple multiselect mode is what the table used to have before
  268. * ctrl/shift selections were added. That is that when this is set clicking
  269. * on an item selects/deselects the item and no ctrl/shift selections are
  270. * available.
  271. */
  272. private static final int MULTISELECT_MODE_SIMPLE = 1;
  273. /**
  274. * multiple of pagelength which component will cache when requesting more
  275. * rows
  276. */
  277. private double cache_rate = CACHE_RATE_DEFAULT;
  278. /**
  279. * fraction of pageLenght which can be scrolled without making new request
  280. */
  281. private double cache_react_rate = 0.75 * cache_rate;
  282. public static final char ALIGN_CENTER = 'c';
  283. public static final char ALIGN_LEFT = 'b';
  284. public static final char ALIGN_RIGHT = 'e';
  285. private static final int CHARCODE_SPACE = 32;
  286. private int firstRowInViewPort = 0;
  287. private int pageLength = 15;
  288. private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
  289. private int firstvisibleOnLastPage = -1; // To detect if the first visible
  290. // is on the last page
  291. /** For internal use only. May be removed or replaced in the future. */
  292. public boolean showRowHeaders = false;
  293. private String[] columnOrder;
  294. protected ApplicationConnection client;
  295. /** For internal use only. May be removed or replaced in the future. */
  296. public String paintableId;
  297. /** For internal use only. May be removed or replaced in the future. */
  298. public boolean immediate;
  299. private boolean updatedReqRows = true;
  300. private boolean nullSelectionAllowed = true;
  301. private SelectMode selectMode = SelectMode.NONE;
  302. public final HashSet<String> selectedRowKeys = new HashSet<String>();
  303. /*
  304. * When scrolling and selecting at the same time, the selections are not in
  305. * sync with the server while retrieving new rows (until key is released).
  306. */
  307. private HashSet<Object> unSyncedselectionsBeforeRowFetch;
  308. /*
  309. * These are used when jumping between pages when pressing Home and End
  310. */
  311. /** For internal use only. May be removed or replaced in the future. */
  312. public boolean selectLastItemInNextRender = false;
  313. /** For internal use only. May be removed or replaced in the future. */
  314. public boolean selectFirstItemInNextRender = false;
  315. /** For internal use only. May be removed or replaced in the future. */
  316. public boolean focusFirstItemInNextRender = false;
  317. /** For internal use only. May be removed or replaced in the future. */
  318. public boolean focusLastItemInNextRender = false;
  319. /**
  320. * The currently focused row.
  321. * <p>
  322. * For internal use only. May be removed or replaced in the future.
  323. */
  324. public VScrollTableRow focusedRow;
  325. /**
  326. * Helper to store selection range start in when using the keyboard
  327. * <p>
  328. * For internal use only. May be removed or replaced in the future.
  329. */
  330. public VScrollTableRow selectionRangeStart;
  331. /**
  332. * Flag for notifying when the selection has changed and should be sent to
  333. * the server
  334. * <p>
  335. * For internal use only. May be removed or replaced in the future.
  336. */
  337. public boolean selectionChanged = false;
  338. /*
  339. * The speed (in pixels) which the scrolling scrolls vertically/horizontally
  340. */
  341. private int scrollingVelocity = 10;
  342. private Timer scrollingVelocityTimer = null;
  343. /** For internal use only. May be removed or replaced in the future. */
  344. public String[] bodyActionKeys;
  345. private boolean enableDebug = false;
  346. private static final boolean hasNativeTouchScrolling = BrowserInfo.get()
  347. .isTouchDevice()
  348. && !BrowserInfo.get().requiresTouchScrollDelegate();
  349. private Set<String> noncollapsibleColumns;
  350. /**
  351. * The last known row height used to preserve the height of a table with
  352. * custom row heights and a fixed page length after removing the last row
  353. * from the table.
  354. *
  355. * A new VScrollTableBody instance is created every time the number of rows
  356. * changes causing {@link VScrollTableBody#rowHeight} to be discarded and
  357. * the height recalculated by {@link VScrollTableBody#getRowHeight(boolean)}
  358. * to avoid some rounding problems, e.g. round(2 * 19.8) / 2 = 20 but
  359. * round(3 * 19.8) / 3 = 19.66.
  360. */
  361. private double lastKnownRowHeight = Double.NaN;
  362. /**
  363. * Remember scroll position when getting detached to properly scroll back to
  364. * the location that there is data for if getting attached again.
  365. */
  366. private int detachedScrollPosition = 0;
  367. /**
  368. * Represents a select range of rows
  369. */
  370. private class SelectionRange {
  371. private VScrollTableRow startRow;
  372. private final int length;
  373. /**
  374. * Constuctor.
  375. */
  376. public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
  377. VScrollTableRow endRow;
  378. if (row2.isBefore(row1)) {
  379. startRow = row2;
  380. endRow = row1;
  381. } else {
  382. startRow = row1;
  383. endRow = row2;
  384. }
  385. length = endRow.getIndex() - startRow.getIndex() + 1;
  386. }
  387. public SelectionRange(VScrollTableRow row, int length) {
  388. startRow = row;
  389. this.length = length;
  390. }
  391. /*
  392. * (non-Javadoc)
  393. *
  394. * @see java.lang.Object#toString()
  395. */
  396. @Override
  397. public String toString() {
  398. return startRow.getKey() + "-" + length;
  399. }
  400. private boolean inRange(VScrollTableRow row) {
  401. return row.getIndex() >= startRow.getIndex()
  402. && row.getIndex() < startRow.getIndex() + length;
  403. }
  404. public Collection<SelectionRange> split(VScrollTableRow row) {
  405. assert row.isAttached();
  406. ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
  407. int endOfFirstRange = row.getIndex() - 1;
  408. if (endOfFirstRange >= startRow.getIndex()) {
  409. // create range of first part unless its length is < 1
  410. ranges.add(new SelectionRange(startRow, endOfFirstRange
  411. - startRow.getIndex() + 1));
  412. }
  413. int startOfSecondRange = row.getIndex() + 1;
  414. if (getEndIndex() >= startOfSecondRange) {
  415. // create range of second part unless its length is < 1
  416. VScrollTableRow startOfRange = scrollBody
  417. .getRowByRowIndex(startOfSecondRange);
  418. if (startOfRange != null) {
  419. ranges.add(new SelectionRange(startOfRange, getEndIndex()
  420. - startOfSecondRange + 1));
  421. }
  422. }
  423. return ranges;
  424. }
  425. private int getEndIndex() {
  426. return startRow.getIndex() + length - 1;
  427. }
  428. }
  429. private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
  430. /** For internal use only. May be removed or replaced in the future. */
  431. public boolean initializedAndAttached = false;
  432. /**
  433. * Flag to indicate if a column width recalculation is needed due update.
  434. * <p>
  435. * For internal use only. May be removed or replaced in the future.
  436. */
  437. public boolean headerChangedDuringUpdate = false;
  438. /** For internal use only. May be removed or replaced in the future. */
  439. public final TableHead tHead = new TableHead();
  440. /** For internal use only. May be removed or replaced in the future. */
  441. public final TableFooter tFoot = new TableFooter();
  442. /** Handles context menu for table body */
  443. private ContextMenuOwner contextMenuOwner = new ContextMenuOwner() {
  444. @Override
  445. public void showContextMenu(Event event) {
  446. int left = WidgetUtil.getTouchOrMouseClientX(event);
  447. int top = WidgetUtil.getTouchOrMouseClientY(event);
  448. boolean menuShown = handleBodyContextMenu(left, top);
  449. if (menuShown) {
  450. event.stopPropagation();
  451. event.preventDefault();
  452. }
  453. }
  454. };
  455. /** Handles touch events to display a context menu for table body */
  456. private TouchContextProvider touchContextProvider = new TouchContextProvider(
  457. contextMenuOwner);
  458. /**
  459. * For internal use only. May be removed or replaced in the future.
  460. *
  461. * Overwrites onBrowserEvent function on FocusableScrollPanel to give event
  462. * access to touchContextProvider. Has to be public to give TableConnector
  463. * access to the scrollBodyPanel field.
  464. *
  465. * @since 7.2
  466. * @author Vaadin Ltd
  467. */
  468. public class FocusableScrollContextPanel extends FocusableScrollPanel {
  469. @Override
  470. public void onBrowserEvent(Event event) {
  471. super.onBrowserEvent(event);
  472. touchContextProvider.handleTouchEvent(event);
  473. };
  474. public FocusableScrollContextPanel(boolean useFakeFocusElement) {
  475. super(useFakeFocusElement);
  476. }
  477. }
  478. /** For internal use only. May be removed or replaced in the future. */
  479. public final FocusableScrollContextPanel scrollBodyPanel = new FocusableScrollContextPanel(
  480. true);
  481. private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
  482. @Override
  483. public void onKeyPress(KeyPressEvent keyPressEvent) {
  484. // This is used for Firefox only, since Firefox auto-repeat
  485. // works correctly only if we use a key press handler, other
  486. // browsers handle it correctly when using a key down handler
  487. if (!BrowserInfo.get().isGecko()) {
  488. return;
  489. }
  490. NativeEvent event = keyPressEvent.getNativeEvent();
  491. if (!enabled) {
  492. // Cancel default keyboard events on a disabled Table
  493. // (prevents scrolling)
  494. event.preventDefault();
  495. } else if (hasFocus) {
  496. // Key code in Firefox/onKeyPress is present only for
  497. // special keys, otherwise 0 is returned
  498. int keyCode = event.getKeyCode();
  499. if (keyCode == 0 && event.getCharCode() == ' ') {
  500. // Provide a keyCode for space to be compatible with
  501. // FireFox keypress event
  502. keyCode = CHARCODE_SPACE;
  503. }
  504. if (handleNavigation(keyCode,
  505. event.getCtrlKey() || event.getMetaKey(),
  506. event.getShiftKey())) {
  507. event.preventDefault();
  508. }
  509. startScrollingVelocityTimer();
  510. }
  511. }
  512. };
  513. private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
  514. @Override
  515. public void onKeyUp(KeyUpEvent keyUpEvent) {
  516. NativeEvent event = keyUpEvent.getNativeEvent();
  517. int keyCode = event.getKeyCode();
  518. if (!isFocusable()) {
  519. cancelScrollingVelocityTimer();
  520. } else if (isNavigationKey(keyCode)) {
  521. if (keyCode == getNavigationDownKey()
  522. || keyCode == getNavigationUpKey()) {
  523. /*
  524. * in multiselect mode the server may still have value from
  525. * previous page. Clear it unless doing multiselection or
  526. * just moving focus.
  527. */
  528. if (!event.getShiftKey() && !event.getCtrlKey()) {
  529. instructServerToForgetPreviousSelections();
  530. }
  531. sendSelectedRows();
  532. }
  533. cancelScrollingVelocityTimer();
  534. navKeyDown = false;
  535. }
  536. }
  537. };
  538. private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
  539. @Override
  540. public void onKeyDown(KeyDownEvent keyDownEvent) {
  541. NativeEvent event = keyDownEvent.getNativeEvent();
  542. // This is not used for Firefox
  543. if (BrowserInfo.get().isGecko()) {
  544. return;
  545. }
  546. if (!enabled) {
  547. // Cancel default keyboard events on a disabled Table
  548. // (prevents scrolling)
  549. event.preventDefault();
  550. } else if (hasFocus) {
  551. if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
  552. || event.getMetaKey(), event.getShiftKey())) {
  553. navKeyDown = true;
  554. event.preventDefault();
  555. }
  556. startScrollingVelocityTimer();
  557. }
  558. }
  559. };
  560. /** For internal use only. May be removed or replaced in the future. */
  561. public int totalRows;
  562. private Set<String> collapsedColumns;
  563. /** For internal use only. May be removed or replaced in the future. */
  564. public final RowRequestHandler rowRequestHandler;
  565. /** For internal use only. May be removed or replaced in the future. */
  566. public VScrollTableBody scrollBody;
  567. private int firstvisible = 0;
  568. private boolean sortAscending;
  569. private String sortColumn;
  570. private String oldSortColumn;
  571. private boolean columnReordering;
  572. /**
  573. * This map contains captions and icon urls for actions like: * "33_c" ->
  574. * "Edit" * "33_i" -> "http://dom.com/edit.png"
  575. */
  576. private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
  577. private String[] visibleColOrder;
  578. private boolean initialContentReceived = false;
  579. private Element scrollPositionElement;
  580. /** For internal use only. May be removed or replaced in the future. */
  581. public boolean enabled;
  582. /** For internal use only. May be removed or replaced in the future. */
  583. public boolean showColHeaders;
  584. /** For internal use only. May be removed or replaced in the future. */
  585. public boolean showColFooters;
  586. /** flag to indicate that table body has changed */
  587. private boolean isNewBody = true;
  588. /**
  589. * Read from the "recalcWidths" -attribute. When it is true, the table will
  590. * recalculate the widths for columns - desirable in some cases. For #1983,
  591. * marked experimental. See also variable <code>refreshContentWidths</code>
  592. * in method {@link TableHead#updateCellsFromUIDL(UIDL)}.
  593. * <p>
  594. * For internal use only. May be removed or replaced in the future.
  595. */
  596. public boolean recalcWidths = false;
  597. /** For internal use only. May be removed or replaced in the future. */
  598. public boolean rendering = false;
  599. private boolean hasFocus = false;
  600. private int dragmode;
  601. private int multiselectmode;
  602. /** For internal use only. May be removed or replaced in the future. */
  603. public int tabIndex;
  604. private TouchScrollDelegate touchScrollDelegate;
  605. /** For internal use only. May be removed or replaced in the future. */
  606. public int lastRenderedHeight;
  607. /**
  608. * Values (serverCacheFirst+serverCacheLast) sent by server that tells which
  609. * rows (indexes) are in the server side cache (page buffer). -1 means
  610. * unknown. The server side cache row MUST MATCH the client side cache rows.
  611. *
  612. * If the client side cache contains additional rows with e.g. buttons, it
  613. * will cause out of sync when such a button is pressed.
  614. *
  615. * If the server side cache contains additional rows with e.g. buttons,
  616. * scrolling in the client will cause empty buttons to be rendered
  617. * (cached=true request for non-existing components)
  618. *
  619. * For internal use only. May be removed or replaced in the future.
  620. */
  621. public int serverCacheFirst = -1;
  622. public int serverCacheLast = -1;
  623. /**
  624. * In several cases TreeTable depends on the scrollBody.lastRendered being
  625. * 'out of sync' while the update is being done. In those cases the sanity
  626. * check must be performed afterwards.
  627. */
  628. public boolean postponeSanityCheckForLastRendered;
  629. /** For internal use only. May be removed or replaced in the future. */
  630. public boolean sizeNeedsInit = true;
  631. /**
  632. * Used to recall the position of an open context menu if we need to close
  633. * and reopen it during a row update.
  634. * <p>
  635. * For internal use only. May be removed or replaced in the future.
  636. */
  637. public class ContextMenuDetails implements CloseHandler<PopupPanel> {
  638. public String rowKey;
  639. public int left;
  640. public int top;
  641. HandlerRegistration closeRegistration;
  642. public ContextMenuDetails(VContextMenu menu, String rowKey, int left,
  643. int top) {
  644. this.rowKey = rowKey;
  645. this.left = left;
  646. this.top = top;
  647. closeRegistration = menu.addCloseHandler(this);
  648. }
  649. @Override
  650. public void onClose(CloseEvent<PopupPanel> event) {
  651. contextMenu = null;
  652. closeRegistration.removeHandler();
  653. }
  654. }
  655. /** For internal use only. May be removed or replaced in the future. */
  656. public ContextMenuDetails contextMenu = null;
  657. private boolean hadScrollBars = false;
  658. private HandlerRegistration addCloseHandler;
  659. /**
  660. * Changes to manage mouseDown and mouseUp
  661. */
  662. /**
  663. * The element where the last mouse down event was registered.
  664. */
  665. private Element lastMouseDownTarget;
  666. /**
  667. * Set to true by {@link #mouseUpPreviewHandler} if it gets a mouseup at the
  668. * same element as {@link #lastMouseDownTarget}.
  669. */
  670. private boolean mouseUpPreviewMatched = false;
  671. private HandlerRegistration mouseUpEventPreviewRegistration;
  672. /**
  673. * Previews events after a mousedown to detect where the following mouseup
  674. * hits.
  675. */
  676. private final NativePreviewHandler mouseUpPreviewHandler = new NativePreviewHandler() {
  677. @Override
  678. public void onPreviewNativeEvent(NativePreviewEvent event) {
  679. if (event.getTypeInt() == Event.ONMOUSEUP) {
  680. mouseUpEventPreviewRegistration.removeHandler();
  681. // Event's reported target not always correct if event
  682. // capture is in use
  683. Element elementUnderMouse = WidgetUtil
  684. .getElementUnderMouse(event.getNativeEvent());
  685. if (lastMouseDownTarget != null
  686. && lastMouseDownTarget.isOrHasChild(elementUnderMouse)) {
  687. mouseUpPreviewMatched = true;
  688. } else {
  689. getLogger().log(
  690. Level.FINEST,
  691. "Ignoring mouseup from " + elementUnderMouse
  692. + " when mousedown was on "
  693. + lastMouseDownTarget);
  694. }
  695. }
  696. }
  697. };
  698. public VScrollTable() {
  699. setMultiSelectMode(MULTISELECT_MODE_DEFAULT);
  700. scrollBodyPanel.addFocusHandler(this);
  701. scrollBodyPanel.addBlurHandler(this);
  702. scrollBodyPanel.addScrollHandler(this);
  703. /*
  704. * Firefox auto-repeat works correctly only if we use a key press
  705. * handler, other browsers handle it correctly when using a key down
  706. * handler
  707. */
  708. if (BrowserInfo.get().isGecko()) {
  709. scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
  710. } else {
  711. scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
  712. }
  713. scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
  714. scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS | Event.ONCONTEXTMENU);
  715. setStyleName(STYLENAME);
  716. add(tHead);
  717. add(scrollBodyPanel);
  718. add(tFoot);
  719. rowRequestHandler = new RowRequestHandler();
  720. }
  721. @Override
  722. public void setStyleName(String style) {
  723. updateStyleNames(style, false);
  724. }
  725. @Override
  726. public void setStylePrimaryName(String style) {
  727. updateStyleNames(style, true);
  728. }
  729. private void updateStyleNames(String newStyle, boolean isPrimary) {
  730. scrollBodyPanel
  731. .removeStyleName(getStylePrimaryName() + "-body-wrapper");
  732. scrollBodyPanel.removeStyleName(getStylePrimaryName() + "-body");
  733. if (scrollBody != null) {
  734. scrollBody.removeStyleName(getStylePrimaryName()
  735. + "-body-noselection");
  736. }
  737. if (isPrimary) {
  738. super.setStylePrimaryName(newStyle);
  739. } else {
  740. super.setStyleName(newStyle);
  741. }
  742. scrollBodyPanel.addStyleName(getStylePrimaryName() + "-body-wrapper");
  743. scrollBodyPanel.addStyleName(getStylePrimaryName() + "-body");
  744. tHead.updateStyleNames(getStylePrimaryName());
  745. tFoot.updateStyleNames(getStylePrimaryName());
  746. if (scrollBody != null) {
  747. scrollBody.updateStyleNames(getStylePrimaryName());
  748. }
  749. }
  750. public void init(ApplicationConnection client) {
  751. this.client = client;
  752. // Add a handler to clear saved context menu details when the menu
  753. // closes. See #8526.
  754. addCloseHandler = client.getContextMenu().addCloseHandler(
  755. new CloseHandler<PopupPanel>() {
  756. @Override
  757. public void onClose(CloseEvent<PopupPanel> event) {
  758. contextMenu = null;
  759. }
  760. });
  761. }
  762. /**
  763. * Handles a context menu event on table body.
  764. *
  765. * @param left
  766. * left position of the context menu
  767. * @param top
  768. * top position of the context menu
  769. * @return true if a context menu was shown, otherwise false
  770. */
  771. private boolean handleBodyContextMenu(int left, int top) {
  772. if (enabled && bodyActionKeys != null) {
  773. top += Window.getScrollTop();
  774. left += Window.getScrollLeft();
  775. client.getContextMenu().showAt(this, left, top);
  776. return true;
  777. }
  778. return false;
  779. }
  780. /**
  781. * Fires a column resize event which sends the resize information to the
  782. * server.
  783. *
  784. * @param columnId
  785. * The columnId of the column which was resized
  786. * @param originalWidth
  787. * The width in pixels of the column before the resize event
  788. * @param newWidth
  789. * The width in pixels of the column after the resize event
  790. */
  791. private void fireColumnResizeEvent(String columnId, int originalWidth,
  792. int newWidth) {
  793. client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
  794. false);
  795. client.updateVariable(paintableId, "columnResizeEventPrev",
  796. originalWidth, false);
  797. client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
  798. immediate);
  799. }
  800. /**
  801. * Non-immediate variable update of column widths for a collection of
  802. * columns.
  803. *
  804. * @param columns
  805. * the columns to trigger the events for.
  806. */
  807. private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
  808. String[] newSizes = new String[columns.size()];
  809. int ix = 0;
  810. for (HeaderCell cell : columns) {
  811. newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
  812. }
  813. client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
  814. false);
  815. }
  816. /**
  817. * Moves the focus one step down
  818. *
  819. * @return Returns true if succeeded
  820. */
  821. private boolean moveFocusDown() {
  822. return moveFocusDown(0);
  823. }
  824. /**
  825. * Moves the focus down by 1+offset rows
  826. *
  827. * @return Returns true if succeeded, else false if the selection could not
  828. * be move downwards
  829. */
  830. private boolean moveFocusDown(int offset) {
  831. if (isSelectable()) {
  832. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  833. // FIXME should focus first visible from top, not first rendered
  834. // ??
  835. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  836. .next());
  837. } else {
  838. VScrollTableRow next = getNextRow(focusedRow, offset);
  839. if (next != null) {
  840. return setRowFocus(next);
  841. }
  842. }
  843. }
  844. return false;
  845. }
  846. /**
  847. * Moves the selection one step up
  848. *
  849. * @return Returns true if succeeded
  850. */
  851. private boolean moveFocusUp() {
  852. return moveFocusUp(0);
  853. }
  854. /**
  855. * Moves the focus row upwards
  856. *
  857. * @return Returns true if succeeded, else false if the selection could not
  858. * be move upwards
  859. *
  860. */
  861. private boolean moveFocusUp(int offset) {
  862. if (isSelectable()) {
  863. if (focusedRow == null && scrollBody.iterator().hasNext()) {
  864. // FIXME logic is exactly the same as in moveFocusDown, should
  865. // be the opposite??
  866. return setRowFocus((VScrollTableRow) scrollBody.iterator()
  867. .next());
  868. } else {
  869. VScrollTableRow prev = getPreviousRow(focusedRow, offset);
  870. if (prev != null) {
  871. return setRowFocus(prev);
  872. } else {
  873. VConsole.log("no previous available");
  874. }
  875. }
  876. }
  877. return false;
  878. }
  879. /**
  880. * Selects a row where the current selection head is
  881. *
  882. * @param ctrlSelect
  883. * Is the selection a ctrl+selection
  884. * @param shiftSelect
  885. * Is the selection a shift+selection
  886. * @return Returns truw
  887. */
  888. private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
  889. if (focusedRow != null) {
  890. // Arrows moves the selection and clears previous selections
  891. if (isSelectable() && !ctrlSelect && !shiftSelect) {
  892. deselectAll();
  893. focusedRow.toggleSelection();
  894. selectionRangeStart = focusedRow;
  895. } else if (isSelectable() && ctrlSelect && !shiftSelect) {
  896. // Ctrl+arrows moves selection head
  897. selectionRangeStart = focusedRow;
  898. // No selection, only selection head is moved
  899. } else if (isMultiSelectModeAny() && !ctrlSelect && shiftSelect) {
  900. // Shift+arrows selection selects a range
  901. focusedRow.toggleShiftSelection(shiftSelect);
  902. }
  903. }
  904. }
  905. /**
  906. * Sends the selection to the server if changed since the last update/visit.
  907. */
  908. protected void sendSelectedRows() {
  909. sendSelectedRows(immediate);
  910. }
  911. private void updateFirstVisibleAndSendSelectedRows() {
  912. updateFirstVisibleRow();
  913. sendSelectedRows(immediate);
  914. }
  915. /**
  916. * Sends the selection to the server if it has been changed since the last
  917. * update/visit.
  918. *
  919. * @param immediately
  920. * set to true to immediately send the rows
  921. */
  922. protected void sendSelectedRows(boolean immediately) {
  923. // Don't send anything if selection has not changed
  924. if (!selectionChanged) {
  925. return;
  926. }
  927. // Reset selection changed flag
  928. selectionChanged = false;
  929. // Note: changing the immediateness of this might require changes to
  930. // "clickEvent" immediateness also.
  931. if (isMultiSelectModeDefault()) {
  932. // Convert ranges to a set of strings
  933. Set<String> ranges = new HashSet<String>();
  934. for (SelectionRange range : selectedRowRanges) {
  935. ranges.add(range.toString());
  936. }
  937. // Send the selected row ranges
  938. client.updateVariable(paintableId, "selectedRanges",
  939. ranges.toArray(new String[selectedRowRanges.size()]), false);
  940. selectedRowRanges.clear();
  941. // clean selectedRowKeys so that they don't contain excess values
  942. for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
  943. .hasNext();) {
  944. String key = iterator.next();
  945. VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
  946. if (renderedRowByKey != null) {
  947. for (SelectionRange range : selectedRowRanges) {
  948. if (range.inRange(renderedRowByKey)) {
  949. iterator.remove();
  950. }
  951. }
  952. } else {
  953. // orphaned selected key, must be in a range, ignore
  954. iterator.remove();
  955. }
  956. }
  957. }
  958. // Send the selected rows
  959. client.updateVariable(paintableId, "selected",
  960. selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
  961. immediately);
  962. }
  963. /**
  964. * Get the key that moves the selection head upwards. By default it is the
  965. * up arrow key but by overriding this you can change the key to whatever
  966. * you want.
  967. *
  968. * @return The keycode of the key
  969. */
  970. protected int getNavigationUpKey() {
  971. return KeyCodes.KEY_UP;
  972. }
  973. /**
  974. * Get the key that moves the selection head downwards. By default it is the
  975. * down arrow key but by overriding this you can change the key to whatever
  976. * you want.
  977. *
  978. * @return The keycode of the key
  979. */
  980. protected int getNavigationDownKey() {
  981. return KeyCodes.KEY_DOWN;
  982. }
  983. /**
  984. * Get the key that scrolls to the left in the table. By default it is the
  985. * left arrow key but by overriding this you can change the key to whatever
  986. * you want.
  987. *
  988. * @return The keycode of the key
  989. */
  990. protected int getNavigationLeftKey() {
  991. return KeyCodes.KEY_LEFT;
  992. }
  993. /**
  994. * Get the key that scroll to the right on the table. By default it is the
  995. * right arrow key but by overriding this you can change the key to whatever
  996. * you want.
  997. *
  998. * @return The keycode of the key
  999. */
  1000. protected int getNavigationRightKey() {
  1001. return KeyCodes.KEY_RIGHT;
  1002. }
  1003. /**
  1004. * Get the key that selects an item in the table. By default it is the space
  1005. * bar key but by overriding this you can change the key to whatever you
  1006. * want.
  1007. *
  1008. * @return
  1009. */
  1010. protected int getNavigationSelectKey() {
  1011. return CHARCODE_SPACE;
  1012. }
  1013. /**
  1014. * Get the key the moves the selection one page up in the table. By default
  1015. * this is the Page Up key but by overriding this you can change the key to
  1016. * whatever you want.
  1017. *
  1018. * @return
  1019. */
  1020. protected int getNavigationPageUpKey() {
  1021. return KeyCodes.KEY_PAGEUP;
  1022. }
  1023. /**
  1024. * Get the key the moves the selection one page down in the table. By
  1025. * default this is the Page Down key but by overriding this you can change
  1026. * the key to whatever you want.
  1027. *
  1028. * @return
  1029. */
  1030. protected int getNavigationPageDownKey() {
  1031. return KeyCodes.KEY_PAGEDOWN;
  1032. }
  1033. /**
  1034. * Get the key the moves the selection to the beginning of the table. By
  1035. * default this is the Home key but by overriding this you can change the
  1036. * key to whatever you want.
  1037. *
  1038. * @return
  1039. */
  1040. protected int getNavigationStartKey() {
  1041. return KeyCodes.KEY_HOME;
  1042. }
  1043. /**
  1044. * Get the key the moves the selection to the end of the table. By default
  1045. * this is the End key but by overriding this you can change the key to
  1046. * whatever you want.
  1047. *
  1048. * @return
  1049. */
  1050. protected int getNavigationEndKey() {
  1051. return KeyCodes.KEY_END;
  1052. }
  1053. /** For internal use only. May be removed or replaced in the future. */
  1054. public void initializeRows(UIDL uidl, UIDL rowData) {
  1055. if (scrollBody != null) {
  1056. scrollBody.removeFromParent();
  1057. }
  1058. // Without this call the scroll position is messed up in IE even after
  1059. // the lazy scroller has set the scroll position to the first visible
  1060. // item
  1061. int pos = scrollBodyPanel.getScrollPosition();
  1062. // Reset first row in view port so client requests correct last row.
  1063. if (pos == 0) {
  1064. firstRowInViewPort = 0;
  1065. }
  1066. scrollBody = createScrollBody();
  1067. scrollBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"),
  1068. uidl.getIntAttribute("rows"));
  1069. scrollBodyPanel.add(scrollBody);
  1070. // New body starts scrolled to the left, make sure the header and footer
  1071. // are also scrolled to the left
  1072. tHead.setHorizontalScrollPosition(0);
  1073. tFoot.setHorizontalScrollPosition(0);
  1074. initialContentReceived = true;
  1075. sizeNeedsInit = true;
  1076. scrollBody.restoreRowVisibility();
  1077. }
  1078. /** For internal use only. May be removed or replaced in the future. */
  1079. public void updateColumnProperties(UIDL uidl) {
  1080. updateColumnOrder(uidl);
  1081. updateCollapsedColumns(uidl);
  1082. UIDL vc = uidl.getChildByTagName("visiblecolumns");
  1083. if (vc != null) {
  1084. tHead.updateCellsFromUIDL(vc);
  1085. tFoot.updateCellsFromUIDL(vc);
  1086. }
  1087. updateHeader(uidl.getStringArrayAttribute("vcolorder"));
  1088. updateFooter(uidl.getStringArrayAttribute("vcolorder"));
  1089. if (uidl.hasVariable("noncollapsiblecolumns")) {
  1090. noncollapsibleColumns = uidl
  1091. .getStringArrayVariableAsSet("noncollapsiblecolumns");
  1092. }
  1093. }
  1094. private void updateCollapsedColumns(UIDL uidl) {
  1095. if (uidl.hasVariable("collapsedcolumns")) {
  1096. tHead.setColumnCollapsingAllowed(true);
  1097. collapsedColumns = uidl
  1098. .getStringArrayVariableAsSet("collapsedcolumns");
  1099. } else {
  1100. tHead.setColumnCollapsingAllowed(false);
  1101. }
  1102. }
  1103. private void updateColumnOrder(UIDL uidl) {
  1104. if (uidl.hasVariable("columnorder")) {
  1105. columnReordering = true;
  1106. columnOrder = uidl.getStringArrayVariable("columnorder");
  1107. } else {
  1108. columnReordering = false;
  1109. columnOrder = null;
  1110. }
  1111. }
  1112. /** For internal use only. May be removed or replaced in the future. */
  1113. public boolean selectSelectedRows(UIDL uidl) {
  1114. boolean keyboardSelectionOverRowFetchInProgress = false;
  1115. if (uidl.hasVariable("selected")) {
  1116. final Set<String> selectedKeys = uidl
  1117. .getStringArrayVariableAsSet("selected");
  1118. removeUnselectedRowKeys(selectedKeys);
  1119. if (scrollBody != null) {
  1120. Iterator<Widget> iterator = scrollBody.iterator();
  1121. while (iterator.hasNext()) {
  1122. /*
  1123. * Make the focus reflect to the server side state unless we
  1124. * are currently selecting multiple rows with keyboard.
  1125. */
  1126. VScrollTableRow row = (VScrollTableRow) iterator.next();
  1127. boolean selected = selectedKeys.contains(row.getKey());
  1128. if (!selected
  1129. && unSyncedselectionsBeforeRowFetch != null
  1130. && unSyncedselectionsBeforeRowFetch.contains(row
  1131. .getKey())) {
  1132. selected = true;
  1133. keyboardSelectionOverRowFetchInProgress = true;
  1134. }
  1135. if (selected && selectedKeys.size() == 1) {
  1136. /*
  1137. * If a single item is selected, move focus to the
  1138. * selected row. (#10522)
  1139. */
  1140. setRowFocus(row);
  1141. }
  1142. if (selected != row.isSelected()) {
  1143. row.toggleSelection();
  1144. if (!isSingleSelectMode() && !selected) {
  1145. // Update selection range in case a row is
  1146. // unselected from the middle of a range - #8076
  1147. removeRowFromUnsentSelectionRanges(row);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }
  1153. unSyncedselectionsBeforeRowFetch = null;
  1154. return keyboardSelectionOverRowFetchInProgress;
  1155. }
  1156. private void removeUnselectedRowKeys(final Set<String> selectedKeys) {
  1157. List<String> unselectedKeys = new ArrayList<String>(0);
  1158. for (String key : selectedRowKeys) {
  1159. if (!selectedKeys.contains(key)) {
  1160. unselectedKeys.add(key);
  1161. }
  1162. }
  1163. selectedRowKeys.removeAll(unselectedKeys);
  1164. }
  1165. /** For internal use only. May be removed or replaced in the future. */
  1166. public void updateSortingProperties(UIDL uidl) {
  1167. oldSortColumn = sortColumn;
  1168. if (uidl.hasVariable("sortascending")) {
  1169. sortAscending = uidl.getBooleanVariable("sortascending");
  1170. sortColumn = uidl.getStringVariable("sortcolumn");
  1171. }
  1172. }
  1173. /** For internal use only. May be removed or replaced in the future. */
  1174. public void resizeSortedColumnForSortIndicator() {
  1175. // Force recalculation of the captionContainer element inside the header
  1176. // cell to accomodate for the size of the sort arrow.
  1177. HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
  1178. if (sortedHeader != null) {
  1179. // Mark header as sorted now. Any earlier marking would lead to
  1180. // columns with wrong sizes
  1181. sortedHeader.setSorted(true);
  1182. tHead.resizeCaptionContainer(sortedHeader);
  1183. }
  1184. // Also recalculate the width of the captionContainer element in the
  1185. // previously sorted header, since this now has more room.
  1186. HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
  1187. if (oldSortedHeader != null) {
  1188. tHead.resizeCaptionContainer(oldSortedHeader);
  1189. }
  1190. }
  1191. private boolean lazyScrollerIsActive;
  1192. private void disableLazyScroller() {
  1193. lazyScrollerIsActive = false;
  1194. scrollBodyPanel.getElement().getStyle().clearOverflowX();
  1195. scrollBodyPanel.getElement().getStyle().clearOverflowY();
  1196. }
  1197. private void enableLazyScroller() {
  1198. Scheduler.get().scheduleDeferred(lazyScroller);
  1199. lazyScrollerIsActive = true;
  1200. // prevent scrolling to jump in IE11
  1201. scrollBodyPanel.getElement().getStyle().setOverflowX(Overflow.HIDDEN);
  1202. scrollBodyPanel.getElement().getStyle().setOverflowY(Overflow.HIDDEN);
  1203. }
  1204. private boolean isLazyScrollerActive() {
  1205. return lazyScrollerIsActive;
  1206. }
  1207. private ScheduledCommand lazyScroller = new ScheduledCommand() {
  1208. @Override
  1209. public void execute() {
  1210. if (firstvisible >= 0) {
  1211. firstRowInViewPort = firstvisible;
  1212. if (firstvisibleOnLastPage > -1) {
  1213. scrollBodyPanel
  1214. .setScrollPosition(measureRowHeightOffset(firstvisibleOnLastPage));
  1215. } else {
  1216. scrollBodyPanel
  1217. .setScrollPosition(measureRowHeightOffset(firstvisible));
  1218. }
  1219. }
  1220. disableLazyScroller();
  1221. }
  1222. };
  1223. /** For internal use only. May be removed or replaced in the future. */
  1224. public void updateFirstVisibleAndScrollIfNeeded(UIDL uidl) {
  1225. firstvisible = uidl.hasVariable("firstvisible") ? uidl
  1226. .getIntVariable("firstvisible") : 0;
  1227. firstvisibleOnLastPage = uidl.hasVariable("firstvisibleonlastpage") ? uidl
  1228. .getIntVariable("firstvisibleonlastpage") : -1;
  1229. if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
  1230. // Update lastRequestedFirstvisible right away here
  1231. // (don't rely on update in the timer which could be cancelled).
  1232. lastRequestedFirstvisible = firstRowInViewPort;
  1233. // Only scroll if the first visible changes from the server side.
  1234. // Else we might unintentionally scroll even when the scroll
  1235. // position has not changed.
  1236. enableLazyScroller();
  1237. }
  1238. }
  1239. protected int measureRowHeightOffset(int rowIx) {
  1240. return (int) (rowIx * scrollBody.getRowHeight());
  1241. }
  1242. /** For internal use only. May be removed or replaced in the future. */
  1243. public void updatePageLength(UIDL uidl) {
  1244. int oldPageLength = pageLength;
  1245. if (uidl.hasAttribute("pagelength")) {
  1246. pageLength = uidl.getIntAttribute("pagelength");
  1247. } else {
  1248. // pagelenght is "0" meaning scrolling is turned off
  1249. pageLength = totalRows;
  1250. }
  1251. if (oldPageLength != pageLength && initializedAndAttached) {
  1252. // page length changed, need to update size
  1253. sizeNeedsInit = true;
  1254. }
  1255. }
  1256. /** For internal use only. May be removed or replaced in the future. */
  1257. public void updateSelectionProperties(UIDL uidl,
  1258. AbstractComponentState state, boolean readOnly) {
  1259. setMultiSelectMode(uidl.hasAttribute("multiselectmode") ? uidl
  1260. .getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT);
  1261. nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
  1262. .getBooleanAttribute("nsa") : true;
  1263. if (uidl.hasAttribute("selectmode")) {
  1264. if (readOnly) {
  1265. selectMode = SelectMode.NONE;
  1266. } else if (uidl.getStringAttribute("selectmode").equals("multi")) {
  1267. selectMode = SelectMode.MULTI;
  1268. } else if (uidl.getStringAttribute("selectmode").equals("single")) {
  1269. selectMode = SelectMode.SINGLE;
  1270. } else {
  1271. selectMode = SelectMode.NONE;
  1272. }
  1273. }
  1274. }
  1275. /** For internal use only. May be removed or replaced in the future. */
  1276. public void updateDragMode(UIDL uidl) {
  1277. dragmode = uidl.hasAttribute("dragmode") ? uidl
  1278. .getIntAttribute("dragmode") : 0;
  1279. if (BrowserInfo.get().isIE()) {
  1280. if (dragmode > 0) {
  1281. getElement().setPropertyJSO("onselectstart",
  1282. getPreventTextSelectionIEHack());
  1283. } else {
  1284. getElement().setPropertyJSO("onselectstart", null);
  1285. }
  1286. }
  1287. }
  1288. /** For internal use only. May be removed or replaced in the future. */
  1289. public void updateTotalRows(UIDL uidl) {
  1290. int newTotalRows = uidl.getIntAttribute("totalrows");
  1291. if (newTotalRows != getTotalRows()) {
  1292. if (scrollBody != null) {
  1293. if (getTotalRows() == 0) {
  1294. tHead.clear();
  1295. tFoot.clear();
  1296. }
  1297. initializedAndAttached = false;
  1298. initialContentReceived = false;
  1299. isNewBody = true;
  1300. }
  1301. setTotalRows(newTotalRows);
  1302. }
  1303. }
  1304. protected void setTotalRows(int newTotalRows) {
  1305. totalRows = newTotalRows;
  1306. }
  1307. public int getTotalRows() {
  1308. return totalRows;
  1309. }
  1310. /**
  1311. * Returns the extra space that is given to the header column when column
  1312. * width is determined by header text.
  1313. *
  1314. * @return extra space in pixels
  1315. */
  1316. private int getHeaderPadding() {
  1317. return scrollBody.getCellExtraWidth();
  1318. }
  1319. /**
  1320. * This method exists for the needs of {@link VTreeTable} only. Not part of
  1321. * the official API, <b>extend at your own risk</b>. May be removed or
  1322. * replaced in the future.
  1323. *
  1324. * @return index of TreeTable's hierarchy column, or -1 if not applicable
  1325. */
  1326. protected int getHierarchyColumnIndex() {
  1327. return -1;
  1328. }
  1329. /**
  1330. * For internal use only. May be removed or replaced in the future.
  1331. */
  1332. public void updateMaxIndent() {
  1333. int oldIndent = scrollBody.getMaxIndent();
  1334. scrollBody.calculateMaxIndent();
  1335. if (oldIndent != scrollBody.getMaxIndent()) {
  1336. // indent updated, headers might need adjusting
  1337. triggerLazyColumnAdjustment(true);
  1338. }
  1339. }
  1340. /** For internal use only. May be removed or replaced in the future. */
  1341. public void focusRowFromBody() {
  1342. if (selectedRowKeys.size() == 1) {
  1343. // try to focus a row currently selected and in viewport
  1344. String selectedRowKey = selectedRowKeys.iterator().next();
  1345. if (selectedRowKey != null) {
  1346. VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
  1347. if (renderedRow == null || !renderedRow.isInViewPort()) {
  1348. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1349. } else {
  1350. setRowFocus(renderedRow);
  1351. }
  1352. }
  1353. } else {
  1354. // multiselect mode
  1355. setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
  1356. }
  1357. }
  1358. protected VScrollTableBody createScrollBody() {
  1359. return new VScrollTableBody();
  1360. }
  1361. /**
  1362. * Selects the last row visible in the table
  1363. * <p>
  1364. * For internal use only. May be removed or replaced in the future.
  1365. *
  1366. * @param focusOnly
  1367. * Should the focus only be moved to the last row
  1368. */
  1369. public void selectLastRenderedRowInViewPort(boolean focusOnly) {
  1370. int index = firstRowInViewPort + getFullyVisibleRowCount();
  1371. VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
  1372. if (lastRowInViewport == null) {
  1373. // this should not happen in normal situations (white space at the
  1374. // end of viewport). Select the last rendered as a fallback.
  1375. lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
  1376. .getLastRendered());
  1377. if (lastRowInViewport == null) {
  1378. return; // empty table
  1379. }
  1380. }
  1381. setRowFocus(lastRowInViewport);
  1382. if (!focusOnly) {
  1383. selectFocusedRow(false, multiselectPending);
  1384. sendSelectedRows();
  1385. }
  1386. }
  1387. /**
  1388. * Selects the first row visible in the table
  1389. * <p>
  1390. * For internal use only. May be removed or replaced in the future.
  1391. *
  1392. * @param focusOnly
  1393. * Should the focus only be moved to the first row
  1394. */
  1395. public void selectFirstRenderedRowInViewPort(boolean focusOnly) {
  1396. int index = firstRowInViewPort;
  1397. VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
  1398. if (firstInViewport == null) {
  1399. // this should not happen in normal situations
  1400. return;
  1401. }
  1402. setRowFocus(firstInViewport);
  1403. if (!focusOnly) {
  1404. selectFocusedRow(false, multiselectPending);
  1405. sendSelectedRows();
  1406. }
  1407. }
  1408. /** For internal use only. May be removed or replaced in the future. */
  1409. public void setCacheRateFromUIDL(UIDL uidl) {
  1410. setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
  1411. : CACHE_RATE_DEFAULT);
  1412. }
  1413. private void setCacheRate(double d) {
  1414. if (cache_rate != d) {
  1415. cache_rate = d;
  1416. cache_react_rate = 0.75 * d;
  1417. }
  1418. }
  1419. /** For internal use only. May be removed or replaced in the future. */
  1420. public void updateActionMap(UIDL mainUidl) {
  1421. UIDL actionsUidl = mainUidl.getChildByTagName("actions");
  1422. if (actionsUidl == null) {
  1423. return;
  1424. }
  1425. final Iterator<?> it = actionsUidl.getChildIterator();
  1426. while (it.hasNext()) {
  1427. final UIDL action = (UIDL) it.next();
  1428. final String key = action.getStringAttribute("key");
  1429. final String caption = action.getStringAttribute("caption");
  1430. actionMap.put(key + "_c", caption);
  1431. if (action.hasAttribute("icon")) {
  1432. // TODO need some uri handling ??
  1433. actionMap.put(key + "_i", client.translateVaadinUri(action
  1434. .getStringAttribute("icon")));
  1435. } else {
  1436. actionMap.remove(key + "_i");
  1437. }
  1438. }
  1439. }
  1440. public String getActionCaption(String actionKey) {
  1441. return actionMap.get(actionKey + "_c");
  1442. }
  1443. public String getActionIcon(String actionKey) {
  1444. return actionMap.get(actionKey + "_i");
  1445. }
  1446. private void updateHeader(String[] strings) {
  1447. if (strings == null) {
  1448. return;
  1449. }
  1450. int visibleCols = strings.length;
  1451. int colIndex = 0;
  1452. if (showRowHeaders) {
  1453. tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1454. visibleCols++;
  1455. visibleColOrder = new String[visibleCols];
  1456. visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
  1457. colIndex++;
  1458. } else {
  1459. visibleColOrder = new String[visibleCols];
  1460. tHead.removeCell(ROW_HEADER_COLUMN_KEY);
  1461. }
  1462. int i;
  1463. for (i = 0; i < strings.length; i++) {
  1464. final String cid = strings[i];
  1465. visibleColOrder[colIndex] = cid;
  1466. tHead.enableColumn(cid, colIndex);
  1467. colIndex++;
  1468. }
  1469. tHead.setVisible(showColHeaders);
  1470. setContainerHeight();
  1471. }
  1472. /**
  1473. * Updates footers.
  1474. * <p>
  1475. * Update headers whould be called before this method is called!
  1476. * </p>
  1477. *
  1478. * @param strings
  1479. */
  1480. private void updateFooter(String[] strings) {
  1481. if (strings == null) {
  1482. return;
  1483. }
  1484. // Add dummy column if row headers are present
  1485. int colIndex = 0;
  1486. if (showRowHeaders) {
  1487. tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
  1488. colIndex++;
  1489. } else {
  1490. tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
  1491. }
  1492. int i;
  1493. for (i = 0; i < strings.length; i++) {
  1494. final String cid = strings[i];
  1495. tFoot.enableColumn(cid, colIndex);
  1496. colIndex++;
  1497. }
  1498. tFoot.setVisible(showColFooters);
  1499. }
  1500. /**
  1501. * For internal use only. May be removed or replaced in the future.
  1502. *
  1503. * @param uidl
  1504. * which contains row data
  1505. * @param firstRow
  1506. * first row in data set
  1507. * @param reqRows
  1508. * amount of rows in data set
  1509. */
  1510. public void updateBody(UIDL uidl, int firstRow, int reqRows) {
  1511. int oldIndent = scrollBody.getMaxIndent();
  1512. if (uidl == null || reqRows < 1) {
  1513. // container is empty, remove possibly existing rows
  1514. if (firstRow <= 0) {
  1515. postponeSanityCheckForLastRendered = true;
  1516. while (scrollBody.getLastRendered() > scrollBody
  1517. .getFirstRendered()) {
  1518. scrollBody.unlinkRow(false);
  1519. }
  1520. postponeSanityCheckForLastRendered = false;
  1521. scrollBody.unlinkRow(false);
  1522. }
  1523. return;
  1524. }
  1525. scrollBody.renderRows(uidl, firstRow, reqRows);
  1526. discardRowsOutsideCacheWindow();
  1527. scrollBody.calculateMaxIndent();
  1528. if (oldIndent != scrollBody.getMaxIndent()) {
  1529. // indent updated, headers might need adjusting
  1530. headerChangedDuringUpdate = true;
  1531. }
  1532. }
  1533. /** For internal use only. May be removed or replaced in the future. */
  1534. public void updateRowsInBody(UIDL partialRowUpdates) {
  1535. if (partialRowUpdates == null) {
  1536. return;
  1537. }
  1538. int firstRowIx = partialRowUpdates.getIntAttribute("firsturowix");
  1539. int count = partialRowUpdates.getIntAttribute("numurows");
  1540. scrollBody.unlinkRows(firstRowIx, count);
  1541. scrollBody.insertRows(partialRowUpdates, firstRowIx, count);
  1542. }
  1543. /**
  1544. * Updates the internal cache by unlinking rows that fall outside of the
  1545. * caching window.
  1546. */
  1547. protected void discardRowsOutsideCacheWindow() {
  1548. int firstRowToKeep = (int) (firstRowInViewPort - pageLength
  1549. * cache_rate);
  1550. int lastRowToKeep = (int) (firstRowInViewPort + pageLength + pageLength
  1551. * cache_rate);
  1552. // sanity checks:
  1553. if (firstRowToKeep < 0) {
  1554. firstRowToKeep = 0;
  1555. }
  1556. if (lastRowToKeep > totalRows) {
  1557. lastRowToKeep = totalRows - 1;
  1558. }
  1559. debug("Client side calculated cache rows to keep: " + firstRowToKeep
  1560. + "-" + lastRowToKeep);
  1561. if (serverCacheFirst != -1) {
  1562. firstRowToKeep = serverCacheFirst;
  1563. lastRowToKeep = serverCacheLast;
  1564. debug("Server cache rows that override: " + serverCacheFirst + "-"
  1565. + serverCacheLast);
  1566. if (firstRowToKeep < scrollBody.getFirstRendered()
  1567. || lastRowToKeep > scrollBody.getLastRendered()) {
  1568. debug("*** Server wants us to keep " + serverCacheFirst + "-"
  1569. + serverCacheLast + " but we only have rows "
  1570. + scrollBody.getFirstRendered() + "-"
  1571. + scrollBody.getLastRendered() + " rendered!");
  1572. }
  1573. }
  1574. discardRowsOutsideOf(firstRowToKeep, lastRowToKeep);
  1575. scrollBody.fixSpacers();
  1576. scrollBody.restoreRowVisibility();
  1577. }
  1578. private void discardRowsOutsideOf(int optimalFirstRow, int optimalLastRow) {
  1579. /*
  1580. * firstDiscarded and lastDiscarded are only calculated for debug
  1581. * purposes
  1582. */
  1583. int firstDiscarded = -1, lastDiscarded = -1;
  1584. boolean cont = true;
  1585. while (cont && scrollBody.getLastRendered() > optimalFirstRow
  1586. && scrollBody.getFirstRendered() < optimalFirstRow) {
  1587. if (firstDiscarded == -1) {
  1588. firstDiscarded = scrollBody.getFirstRendered();
  1589. }
  1590. // removing row from start
  1591. cont = scrollBody.unlinkRow(true);
  1592. }
  1593. if (firstDiscarded != -1) {
  1594. lastDiscarded = scrollBody.getFirstRendered() - 1;
  1595. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1596. }
  1597. firstDiscarded = lastDiscarded = -1;
  1598. cont = true;
  1599. while (cont && scrollBody.getLastRendered() > optimalLastRow) {
  1600. if (lastDiscarded == -1) {
  1601. lastDiscarded = scrollBody.getLastRendered();
  1602. }
  1603. // removing row from the end
  1604. cont = scrollBody.unlinkRow(false);
  1605. }
  1606. if (lastDiscarded != -1) {
  1607. firstDiscarded = scrollBody.getLastRendered() + 1;
  1608. debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
  1609. }
  1610. debug("Now in cache: " + scrollBody.getFirstRendered() + "-"
  1611. + scrollBody.getLastRendered());
  1612. }
  1613. /**
  1614. * Inserts rows in the table body or removes them from the table body based
  1615. * on the commands in the UIDL.
  1616. * <p>
  1617. * For internal use only. May be removed or replaced in the future.
  1618. *
  1619. * @param partialRowAdditions
  1620. * the UIDL containing row updates.
  1621. */
  1622. public void addAndRemoveRows(UIDL partialRowAdditions) {
  1623. if (partialRowAdditions == null) {
  1624. return;
  1625. }
  1626. if (partialRowAdditions.hasAttribute("hide")) {
  1627. scrollBody.unlinkAndReindexRows(
  1628. partialRowAdditions.getIntAttribute("firstprowix"),
  1629. partialRowAdditions.getIntAttribute("numprows"));
  1630. scrollBody.ensureCacheFilled();
  1631. } else {
  1632. if (partialRowAdditions.hasAttribute("delbelow")) {
  1633. scrollBody.insertRowsDeleteBelow(partialRowAdditions,
  1634. partialRowAdditions.getIntAttribute("firstprowix"),
  1635. partialRowAdditions.getIntAttribute("numprows"));
  1636. } else {
  1637. scrollBody.insertAndReindexRows(partialRowAdditions,
  1638. partialRowAdditions.getIntAttribute("firstprowix"),
  1639. partialRowAdditions.getIntAttribute("numprows"));
  1640. }
  1641. }
  1642. discardRowsOutsideCacheWindow();
  1643. }
  1644. /**
  1645. * Gives correct column index for given column key ("cid" in UIDL).
  1646. *
  1647. * @param colKey
  1648. * @return column index of visible columns, -1 if column not visible
  1649. */
  1650. private int getColIndexByKey(String colKey) {
  1651. // return 0 if asked for rowHeaders
  1652. if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
  1653. return 0;
  1654. }
  1655. for (int i = 0; i < visibleColOrder.length; i++) {
  1656. if (visibleColOrder[i].equals(colKey)) {
  1657. return i;
  1658. }
  1659. }
  1660. return -1;
  1661. }
  1662. private boolean isMultiSelectModeSimple() {
  1663. return selectMode == SelectMode.MULTI
  1664. && multiselectmode == MULTISELECT_MODE_SIMPLE;
  1665. }
  1666. private boolean isSingleSelectMode() {
  1667. return selectMode == SelectMode.SINGLE;
  1668. }
  1669. private boolean isMultiSelectModeAny() {
  1670. return selectMode == SelectMode.MULTI;
  1671. }
  1672. private boolean isMultiSelectModeDefault() {
  1673. return selectMode == SelectMode.MULTI
  1674. && multiselectmode == MULTISELECT_MODE_DEFAULT;
  1675. }
  1676. private void setMultiSelectMode(int multiselectmode) {
  1677. if (BrowserInfo.get().isTouchDevice()) {
  1678. // Always use the simple mode for touch devices that do not have
  1679. // shift/ctrl keys
  1680. this.multiselectmode = MULTISELECT_MODE_SIMPLE;
  1681. } else {
  1682. this.multiselectmode = multiselectmode;
  1683. }
  1684. }
  1685. /** For internal use only. May be removed or replaced in the future. */
  1686. public boolean isSelectable() {
  1687. return selectMode.getId() > SelectMode.NONE.getId();
  1688. }
  1689. private boolean isCollapsedColumn(String colKey) {
  1690. if (collapsedColumns == null) {
  1691. return false;
  1692. }
  1693. if (collapsedColumns.contains(colKey)) {
  1694. return true;
  1695. }
  1696. return false;
  1697. }
  1698. private String getColKeyByIndex(int index) {
  1699. return tHead.getHeaderCell(index).getColKey();
  1700. }
  1701. /**
  1702. * Note: not part of the official API, extend at your own risk. May be
  1703. * removed or replaced in the future.
  1704. *
  1705. * Sets the indicated column's width for headers and scrollBody alike.
  1706. *
  1707. * @param colIndex
  1708. * index of the modified column
  1709. * @param w
  1710. * new width (may be subject to modifications if doesn't meet
  1711. * minimum requirements)
  1712. * @param isDefinedWidth
  1713. * disables expand ratio if set true
  1714. */
  1715. protected void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
  1716. final HeaderCell hcell = tHead.getHeaderCell(colIndex);
  1717. // Make sure that the column grows to accommodate the sort indicator if
  1718. // necessary.
  1719. // get min width with no indent or padding
  1720. int minWidth = hcell.getMinWidth(false, false);
  1721. if (w < minWidth) {
  1722. w = minWidth;
  1723. }
  1724. // Set header column width WITHOUT INDENT
  1725. hcell.setWidth(w, isDefinedWidth);
  1726. // Set footer column width likewise
  1727. FooterCell fcell = tFoot.getFooterCell(colIndex);
  1728. fcell.setWidth(w, isDefinedWidth);
  1729. // Ensure indicators have been taken into account
  1730. tHead.resizeCaptionContainer(hcell);
  1731. // Make sure that the body column grows to accommodate the indent if
  1732. // necessary.
  1733. // get min width with indent, no padding
  1734. minWidth = hcell.getMinWidth(true, false);
  1735. if (w < minWidth) {
  1736. w = minWidth;
  1737. }
  1738. // Set body column width
  1739. scrollBody.setColWidth(colIndex, w);
  1740. }
  1741. private int getColWidth(String colKey) {
  1742. return tHead.getHeaderCell(colKey).getWidthWithIndent();
  1743. }
  1744. /**
  1745. * Get a rendered row by its key
  1746. *
  1747. * @param key
  1748. * The key to search with
  1749. * @return
  1750. */
  1751. public VScrollTableRow getRenderedRowByKey(String key) {
  1752. if (scrollBody != null) {
  1753. final Iterator<Widget> it = scrollBody.iterator();
  1754. VScrollTableRow r = null;
  1755. while (it.hasNext()) {
  1756. r = (VScrollTableRow) it.next();
  1757. if (r.getKey().equals(key)) {
  1758. return r;
  1759. }
  1760. }
  1761. }
  1762. return null;
  1763. }
  1764. /**
  1765. * Returns the next row to the given row
  1766. *
  1767. * @param row
  1768. * The row to calculate from
  1769. *
  1770. * @return The next row or null if no row exists
  1771. */
  1772. private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
  1773. final Iterator<Widget> it = scrollBody.iterator();
  1774. VScrollTableRow r = null;
  1775. while (it.hasNext()) {
  1776. r = (VScrollTableRow) it.next();
  1777. if (r == row) {
  1778. r = null;
  1779. while (offset >= 0 && it.hasNext()) {
  1780. r = (VScrollTableRow) it.next();
  1781. offset--;
  1782. }
  1783. return r;
  1784. }
  1785. }
  1786. return null;
  1787. }
  1788. /**
  1789. * Returns the previous row from the given row
  1790. *
  1791. * @param row
  1792. * The row to calculate from
  1793. * @return The previous row or null if no row exists
  1794. */
  1795. private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
  1796. final Iterator<Widget> it = scrollBody.iterator();
  1797. final Iterator<Widget> offsetIt = scrollBody.iterator();
  1798. VScrollTableRow r = null;
  1799. VScrollTableRow prev = null;
  1800. while (it.hasNext()) {
  1801. r = (VScrollTableRow) it.next();
  1802. if (offset < 0) {
  1803. prev = (VScrollTableRow) offsetIt.next();
  1804. }
  1805. if (r == row) {
  1806. return prev;
  1807. }
  1808. offset--;
  1809. }
  1810. return null;
  1811. }
  1812. protected void reOrderColumn(String columnKey, int newIndex) {
  1813. final int oldIndex = getColIndexByKey(columnKey);
  1814. // Change header order
  1815. tHead.moveCell(oldIndex, newIndex);
  1816. // Change body order
  1817. scrollBody.moveCol(oldIndex, newIndex);
  1818. // Change footer order
  1819. tFoot.moveCell(oldIndex, newIndex);
  1820. /*
  1821. * Build new columnOrder and update it to server Note that columnOrder
  1822. * also contains collapsed columns so we cannot directly build it from
  1823. * cells vector Loop the old columnOrder and append in order to new
  1824. * array unless on moved columnKey. On new index also put the moved key
  1825. * i == index on columnOrder, j == index on newOrder
  1826. */
  1827. final String oldKeyOnNewIndex = visibleColOrder[newIndex];
  1828. if (showRowHeaders) {
  1829. newIndex--; // columnOrder don't have rowHeader
  1830. }
  1831. // add back hidden rows,
  1832. for (int i = 0; i < columnOrder.length; i++) {
  1833. if (columnOrder[i].equals(oldKeyOnNewIndex)) {
  1834. break; // break loop at target
  1835. }
  1836. if (isCollapsedColumn(columnOrder[i])) {
  1837. newIndex++;
  1838. }
  1839. }
  1840. // finally we can build the new columnOrder for server
  1841. final String[] newOrder = new String[columnOrder.length];
  1842. for (int i = 0, j = 0; j < newOrder.length; i++) {
  1843. if (j == newIndex) {
  1844. newOrder[j] = columnKey;
  1845. j++;
  1846. }
  1847. if (i == columnOrder.length) {
  1848. break;
  1849. }
  1850. if (columnOrder[i].equals(columnKey)) {
  1851. continue;
  1852. }
  1853. newOrder[j] = columnOrder[i];
  1854. j++;
  1855. }
  1856. columnOrder = newOrder;
  1857. // also update visibleColumnOrder
  1858. int i = showRowHeaders ? 1 : 0;
  1859. for (int j = 0; j < newOrder.length; j++) {
  1860. final String cid = newOrder[j];
  1861. if (!isCollapsedColumn(cid)) {
  1862. visibleColOrder[i++] = cid;
  1863. }
  1864. }
  1865. client.updateVariable(paintableId, "columnorder", columnOrder, false);
  1866. if (client.hasEventListeners(this,
  1867. TableConstants.COLUMN_REORDER_EVENT_ID)) {
  1868. client.sendPendingVariableChanges();
  1869. }
  1870. }
  1871. @Override
  1872. protected void onDetach() {
  1873. detachedScrollPosition = scrollBodyPanel.getScrollPosition();
  1874. rowRequestHandler.cancel();
  1875. super.onDetach();
  1876. // ensure that scrollPosElement will be detached
  1877. if (scrollPositionElement != null) {
  1878. final Element parent = DOM.getParent(scrollPositionElement);
  1879. if (parent != null) {
  1880. DOM.removeChild(parent, scrollPositionElement);
  1881. }
  1882. }
  1883. }
  1884. @Override
  1885. public void onAttach() {
  1886. super.onAttach();
  1887. scrollBodyPanel.setScrollPosition(detachedScrollPosition);
  1888. }
  1889. /**
  1890. * Run only once when component is attached and received its initial
  1891. * content. This function:
  1892. *
  1893. * * Syncs headers and bodys "natural widths and saves the values.
  1894. *
  1895. * * Sets proper width and height
  1896. *
  1897. * * Makes deferred request to get some cache rows
  1898. *
  1899. * For internal use only. May be removed or replaced in the future.
  1900. */
  1901. public void sizeInit() {
  1902. sizeNeedsInit = false;
  1903. scrollBody.setContainerHeight();
  1904. /*
  1905. * We will use browsers table rendering algorithm to find proper column
  1906. * widths. If content and header take less space than available, we will
  1907. * divide extra space relatively to each column which has not width set.
  1908. *
  1909. * Overflow pixels are added to last column.
  1910. */
  1911. Iterator<Widget> headCells = tHead.iterator();
  1912. Iterator<Widget> footCells = tFoot.iterator();
  1913. int i = 0;
  1914. int totalExplicitColumnsWidths = 0;
  1915. int total = 0;
  1916. float expandRatioDivider = 0;
  1917. final int[] widths = new int[tHead.visibleCells.size()];
  1918. tHead.enableBrowserIntelligence();
  1919. tFoot.enableBrowserIntelligence();
  1920. int hierarchyColumnIndent = scrollBody != null ? scrollBody
  1921. .getMaxIndent() : 0;
  1922. HeaderCell hierarchyHeaderWithExpandRatio = null;
  1923. // first loop: collect natural widths
  1924. while (headCells.hasNext()) {
  1925. final HeaderCell hCell = (HeaderCell) headCells.next();
  1926. final FooterCell fCell = (FooterCell) footCells.next();
  1927. boolean needsIndent = hierarchyColumnIndent > 0
  1928. && hCell.isHierarchyColumn();
  1929. hCell.saveNaturalColumnWidthIfNotSaved(i);
  1930. fCell.saveNaturalColumnWidthIfNotSaved(i);
  1931. int w = hCell.getWidth();
  1932. if (hCell.isDefinedWidth()) {
  1933. // server has defined column width explicitly
  1934. if (needsIndent && w < hierarchyColumnIndent) {
  1935. // hierarchy indent overrides explicitly set width
  1936. w = hierarchyColumnIndent;
  1937. }
  1938. totalExplicitColumnsWidths += w;
  1939. } else {
  1940. if (hCell.getExpandRatio() > 0) {
  1941. expandRatioDivider += hCell.getExpandRatio();
  1942. w = 0;
  1943. if (needsIndent && w < hierarchyColumnIndent) {
  1944. hierarchyHeaderWithExpandRatio = hCell;
  1945. // don't add to widths here, because will be included in
  1946. // the expand ratio space if there's enough of it
  1947. }
  1948. } else {
  1949. // get and store greater of header width and column width,
  1950. // and store it as a minimum natural column width (these
  1951. // already contain the indent if any)
  1952. int headerWidth = hCell.getNaturalColumnWidth(i);
  1953. int footerWidth = fCell.getNaturalColumnWidth(i);
  1954. w = headerWidth > footerWidth ? headerWidth : footerWidth;
  1955. }
  1956. if (w != 0) {
  1957. hCell.setNaturalMinimumColumnWidth(w);
  1958. fCell.setNaturalMinimumColumnWidth(w);
  1959. }
  1960. }
  1961. widths[i] = w;
  1962. total += w;
  1963. i++;
  1964. }
  1965. if (hierarchyHeaderWithExpandRatio != null) {
  1966. total += hierarchyColumnIndent;
  1967. }
  1968. tHead.disableBrowserIntelligence();
  1969. tFoot.disableBrowserIntelligence();
  1970. boolean willHaveScrollbarz = willHaveScrollbars();
  1971. // fix "natural" width if width not set
  1972. if (isDynamicWidth()) {
  1973. int w = total;
  1974. w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1975. if (willHaveScrollbarz) {
  1976. w += WidgetUtil.getNativeScrollbarSize();
  1977. }
  1978. setContentWidth(w);
  1979. }
  1980. int availW = scrollBody.getAvailableWidth();
  1981. if (BrowserInfo.get().isIE()) {
  1982. // Hey IE, are you really sure about this?
  1983. availW = scrollBody.getAvailableWidth();
  1984. }
  1985. availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
  1986. if (willHaveScrollbarz) {
  1987. availW -= WidgetUtil.getNativeScrollbarSize();
  1988. }
  1989. // TODO refactor this code to be the same as in resize timer
  1990. if (availW > total) {
  1991. // natural size is smaller than available space
  1992. int extraSpace = availW - total;
  1993. if (hierarchyHeaderWithExpandRatio != null) {
  1994. /*
  1995. * add the indent's space back to ensure each column gets an
  1996. * even share according to the expand ratios (note: if the
  1997. * allocated space isn't enough for the hierarchy column it
  1998. * shall be treated like a defined width column and the indent
  1999. * space gets removed from the extra space again)
  2000. */
  2001. extraSpace += hierarchyColumnIndent;
  2002. }
  2003. final int totalWidthR = total - totalExplicitColumnsWidths;
  2004. int checksum = 0;
  2005. if (extraSpace == 1) {
  2006. // We cannot divide one single pixel so we give it the first
  2007. // undefined column
  2008. // no need to worry about indent here
  2009. headCells = tHead.iterator();
  2010. i = 0;
  2011. checksum = availW;
  2012. while (headCells.hasNext()) {
  2013. HeaderCell hc = (HeaderCell) headCells.next();
  2014. if (!hc.isDefinedWidth()) {
  2015. widths[i]++;
  2016. break;
  2017. }
  2018. i++;
  2019. }
  2020. } else if (expandRatioDivider > 0) {
  2021. boolean setIndentToHierarchyHeader = false;
  2022. if (hierarchyHeaderWithExpandRatio != null) {
  2023. // ensure first that the hierarchyColumn gets at least the
  2024. // space allocated for indent
  2025. final int newSpace = Math
  2026. .round((extraSpace * (hierarchyHeaderWithExpandRatio
  2027. .getExpandRatio() / expandRatioDivider)));
  2028. if (newSpace < hierarchyColumnIndent) {
  2029. // not enough space for indent, remove indent from the
  2030. // extraSpace again and handle hierarchy column's header
  2031. // separately
  2032. setIndentToHierarchyHeader = true;
  2033. extraSpace -= hierarchyColumnIndent;
  2034. }
  2035. }
  2036. // visible columns have some active expand ratios, excess
  2037. // space is divided according to them
  2038. headCells = tHead.iterator();
  2039. i = 0;
  2040. while (headCells.hasNext()) {
  2041. HeaderCell hCell = (HeaderCell) headCells.next();
  2042. if (hCell.getExpandRatio() > 0) {
  2043. int w = widths[i];
  2044. if (setIndentToHierarchyHeader
  2045. && hierarchyHeaderWithExpandRatio.equals(hCell)) {
  2046. // hierarchy column's header is no longer part of
  2047. // the expansion divide and only gets indent
  2048. w += hierarchyColumnIndent;
  2049. } else {
  2050. final int newSpace = Math
  2051. .round((extraSpace * (hCell
  2052. .getExpandRatio() / expandRatioDivider)));
  2053. w += newSpace;
  2054. }
  2055. widths[i] = w;
  2056. }
  2057. checksum += widths[i];
  2058. i++;
  2059. }
  2060. } else if (totalWidthR > 0) {
  2061. // no expand ratios defined, we will share extra space
  2062. // relatively to "natural widths" among those without
  2063. // explicit width
  2064. // no need to worry about indent here, it's already included
  2065. headCells = tHead.iterator();
  2066. i = 0;
  2067. while (headCells.hasNext()) {
  2068. HeaderCell hCell = (HeaderCell) headCells.next();
  2069. if (!hCell.isDefinedWidth()) {
  2070. int w = widths[i];
  2071. final int newSpace = Math.round((float) extraSpace
  2072. * (float) w / totalWidthR);
  2073. w += newSpace;
  2074. widths[i] = w;
  2075. }
  2076. checksum += widths[i];
  2077. i++;
  2078. }
  2079. }
  2080. if (extraSpace > 0 && checksum != availW) {
  2081. /*
  2082. * There might be in some cases a rounding error of 1px when
  2083. * extra space is divided so if there is one then we give the
  2084. * first undefined column 1 more pixel
  2085. */
  2086. headCells = tHead.iterator();
  2087. i = 0;
  2088. while (headCells.hasNext()) {
  2089. HeaderCell hc = (HeaderCell) headCells.next();
  2090. if (!hc.isDefinedWidth()) {
  2091. widths[i] += availW - checksum;
  2092. break;
  2093. }
  2094. i++;
  2095. }
  2096. }
  2097. } else {
  2098. // body's size will be more than available and scrollbar will appear
  2099. }
  2100. // last loop: set possibly modified values or reset if new tBody
  2101. i = 0;
  2102. headCells = tHead.iterator();
  2103. while (headCells.hasNext()) {
  2104. final HeaderCell hCell = (HeaderCell) headCells.next();
  2105. if (isNewBody || hCell.getWidth() == -1) {
  2106. final int w = widths[i];
  2107. setColWidth(i, w, false);
  2108. }
  2109. i++;
  2110. }
  2111. initializedAndAttached = true;
  2112. updatePageLength();
  2113. /*
  2114. * Fix "natural" height if height is not set. This must be after width
  2115. * fixing so the components' widths have been adjusted.
  2116. */
  2117. if (isDynamicHeight()) {
  2118. /*
  2119. * We must force an update of the row height as this point as it
  2120. * might have been (incorrectly) calculated earlier
  2121. */
  2122. /*
  2123. * TreeTable updates stuff in a funky order, so we must set the
  2124. * height as zero here before doing the real update to make it
  2125. * realize that there is no content,
  2126. */
  2127. if (pageLength == totalRows && pageLength == 0) {
  2128. scrollBody.setHeight("0px");
  2129. }
  2130. int bodyHeight;
  2131. if (pageLength == totalRows) {
  2132. /*
  2133. * A hack to support variable height rows when paging is off.
  2134. * Generally this is not supported by scrolltable. We want to
  2135. * show all rows so the bodyHeight should be equal to the table
  2136. * height.
  2137. */
  2138. // int bodyHeight = scrollBody.getOffsetHeight();
  2139. bodyHeight = scrollBody.getRequiredHeight();
  2140. } else {
  2141. bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
  2142. * pageLength);
  2143. }
  2144. boolean needsSpaceForHorizontalSrollbar = (total > availW);
  2145. if (needsSpaceForHorizontalSrollbar) {
  2146. bodyHeight += WidgetUtil.getNativeScrollbarSize();
  2147. }
  2148. scrollBodyPanel.setHeight(bodyHeight + "px");
  2149. WidgetUtil.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
  2150. }
  2151. isNewBody = false;
  2152. if (firstvisible > 0) {
  2153. enableLazyScroller();
  2154. }
  2155. if (enabled) {
  2156. // Do we need cache rows
  2157. if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
  2158. + pageLength + (int) cache_react_rate * pageLength) {
  2159. if (totalRows - 1 > scrollBody.getLastRendered()) {
  2160. // fetch cache rows
  2161. int firstInNewSet = scrollBody.getLastRendered() + 1;
  2162. int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
  2163. * pageLength);
  2164. if (lastInNewSet > totalRows - 1) {
  2165. lastInNewSet = totalRows - 1;
  2166. }
  2167. rowRequestHandler.triggerRowFetch(firstInNewSet,
  2168. lastInNewSet - firstInNewSet + 1, 1);
  2169. }
  2170. }
  2171. }
  2172. /*
  2173. * Ensures the column alignments are correct at initial loading. <br/>
  2174. * (child components widths are correct)
  2175. */
  2176. WidgetUtil.runWebkitOverflowAutoFixDeferred(scrollBodyPanel
  2177. .getElement());
  2178. hadScrollBars = willHaveScrollbarz;
  2179. }
  2180. /**
  2181. * Note: this method is not part of official API although declared as
  2182. * protected. Extend at your own risk.
  2183. *
  2184. * @return true if content area will have scrollbars visible.
  2185. */
  2186. protected boolean willHaveScrollbars() {
  2187. if (isDynamicHeight()) {
  2188. if (pageLength < totalRows) {
  2189. return true;
  2190. }
  2191. } else {
  2192. int fakeheight = (int) Math.round(scrollBody.getRowHeight()
  2193. * totalRows);
  2194. int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
  2195. "clientHeight");
  2196. if (fakeheight > availableHeight) {
  2197. return true;
  2198. }
  2199. }
  2200. return false;
  2201. }
  2202. private void announceScrollPosition() {
  2203. if (scrollPositionElement == null) {
  2204. scrollPositionElement = DOM.createDiv();
  2205. scrollPositionElement.setClassName(getStylePrimaryName()
  2206. + "-scrollposition");
  2207. scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
  2208. scrollPositionElement.getStyle().setDisplay(Display.NONE);
  2209. getElement().appendChild(scrollPositionElement);
  2210. }
  2211. Style style = scrollPositionElement.getStyle();
  2212. style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
  2213. style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
  2214. // indexes go from 1-totalRows, as rowheaders in index-mode indicate
  2215. int last = (firstRowInViewPort + pageLength);
  2216. if (last > totalRows) {
  2217. last = totalRows;
  2218. }
  2219. scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
  2220. + " &ndash; " + (last) + "..." + "</span>");
  2221. style.setDisplay(Display.BLOCK);
  2222. }
  2223. /** For internal use only. May be removed or replaced in the future. */
  2224. public void hideScrollPositionAnnotation() {
  2225. if (scrollPositionElement != null) {
  2226. scrollPositionElement.getStyle().setDisplay(Display.NONE);
  2227. }
  2228. }
  2229. /** For internal use only. May be removed or replaced in the future. */
  2230. public boolean isScrollPositionVisible() {
  2231. return scrollPositionElement != null
  2232. && !scrollPositionElement.getStyle().getDisplay()
  2233. .equals(Display.NONE.toString());
  2234. }
  2235. /** For internal use only. May be removed or replaced in the future. */
  2236. public class RowRequestHandler extends Timer {
  2237. private int reqFirstRow = 0;
  2238. private int reqRows = 0;
  2239. private boolean isRequestHandlerRunning = false;
  2240. public void triggerRowFetch(int first, int rows) {
  2241. setReqFirstRow(first);
  2242. setReqRows(rows);
  2243. deferRowFetch();
  2244. }
  2245. public void triggerRowFetch(int first, int rows, int delay) {
  2246. setReqFirstRow(first);
  2247. setReqRows(rows);
  2248. deferRowFetch(delay);
  2249. }
  2250. public void deferRowFetch() {
  2251. deferRowFetch(250);
  2252. }
  2253. public boolean isRequestHandlerRunning() {
  2254. return isRequestHandlerRunning;
  2255. }
  2256. public void deferRowFetch(int msec) {
  2257. isRequestHandlerRunning = true;
  2258. if (reqRows > 0 && reqFirstRow < totalRows) {
  2259. schedule(msec);
  2260. // tell scroll position to user if currently "visible" rows are
  2261. // not rendered
  2262. if (totalRows > pageLength
  2263. && ((firstRowInViewPort + pageLength > scrollBody
  2264. .getLastRendered()) || (firstRowInViewPort < scrollBody
  2265. .getFirstRendered()))) {
  2266. announceScrollPosition();
  2267. } else {
  2268. hideScrollPositionAnnotation();
  2269. }
  2270. }
  2271. }
  2272. public int getReqFirstRow() {
  2273. return reqFirstRow;
  2274. }
  2275. public void setReqFirstRow(int reqFirstRow) {
  2276. if (reqFirstRow < 0) {
  2277. this.reqFirstRow = 0;
  2278. } else if (reqFirstRow >= totalRows) {
  2279. this.reqFirstRow = totalRows - 1;
  2280. } else {
  2281. this.reqFirstRow = reqFirstRow;
  2282. }
  2283. }
  2284. public void setReqRows(int reqRows) {
  2285. if (reqRows < 0) {
  2286. this.reqRows = 0;
  2287. } else if (reqFirstRow + reqRows > totalRows) {
  2288. this.reqRows = totalRows - reqFirstRow;
  2289. } else {
  2290. this.reqRows = reqRows;
  2291. }
  2292. }
  2293. @Override
  2294. public void run() {
  2295. if (client.hasActiveRequest() || navKeyDown) {
  2296. // if client connection is busy, don't bother loading it more
  2297. VConsole.log("Postponed rowfetch");
  2298. schedule(250);
  2299. } else if (allRenderedRowsAreNew() && !updatedReqRows) {
  2300. /*
  2301. * If all rows are new, there might have been a server-side call
  2302. * to Table.setCurrentPageFirstItemIndex(int) In this case,
  2303. * scrolling event takes way too late, and all the rows from
  2304. * previous viewport to this one were requested.
  2305. *
  2306. * This should prevent requesting unneeded rows by updating
  2307. * reqFirstRow and reqRows before needing them. See (#14135)
  2308. */
  2309. setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
  2310. int last = firstRowInViewPort + (int) (cache_rate * pageLength)
  2311. + pageLength - 1;
  2312. if (last >= totalRows) {
  2313. last = totalRows - 1;
  2314. }
  2315. setReqRows(last - getReqFirstRow() + 1);
  2316. updatedReqRows = true;
  2317. schedule(250);
  2318. } else {
  2319. int firstRendered = scrollBody.getFirstRendered();
  2320. int lastRendered = scrollBody.getLastRendered();
  2321. if (lastRendered > totalRows) {
  2322. lastRendered = totalRows - 1;
  2323. }
  2324. boolean rendered = firstRendered >= 0 && lastRendered >= 0;
  2325. int firstToBeRendered = firstRendered;
  2326. if (reqFirstRow < firstToBeRendered) {
  2327. firstToBeRendered = reqFirstRow;
  2328. } else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
  2329. firstToBeRendered = firstRowInViewPort
  2330. - (int) (cache_rate * pageLength);
  2331. if (firstToBeRendered < 0) {
  2332. firstToBeRendered = 0;
  2333. }
  2334. } else if (rendered && firstRendered + 1 < reqFirstRow
  2335. && lastRendered + 1 < reqFirstRow) {
  2336. // requested rows must fall within the requested rendering
  2337. // area
  2338. firstToBeRendered = reqFirstRow;
  2339. }
  2340. if (firstToBeRendered + reqRows < firstRendered) {
  2341. // must increase the required row count accordingly,
  2342. // otherwise may leave a gap and the rows beyond will get
  2343. // removed
  2344. setReqRows(firstRendered - firstToBeRendered);
  2345. }
  2346. int lastToBeRendered = lastRendered;
  2347. int lastReqRow = reqFirstRow + reqRows - 1;
  2348. if (lastReqRow > lastToBeRendered) {
  2349. lastToBeRendered = lastReqRow;
  2350. } else if (firstRowInViewPort + pageLength + pageLength
  2351. * cache_rate < lastToBeRendered) {
  2352. lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
  2353. if (lastToBeRendered >= totalRows) {
  2354. lastToBeRendered = totalRows - 1;
  2355. }
  2356. // due Safari 3.1 bug (see #2607), verify reqrows, original
  2357. // problem unknown, but this should catch the issue
  2358. if (lastReqRow > lastToBeRendered) {
  2359. setReqRows(lastToBeRendered - reqFirstRow);
  2360. }
  2361. } else if (rendered && lastRendered - 1 > lastReqRow
  2362. && firstRendered - 1 > lastReqRow) {
  2363. // requested rows must fall within the requested rendering
  2364. // area
  2365. lastToBeRendered = lastReqRow;
  2366. }
  2367. if (lastToBeRendered > totalRows) {
  2368. lastToBeRendered = totalRows - 1;
  2369. }
  2370. if (reqFirstRow < firstToBeRendered
  2371. || (reqFirstRow > firstToBeRendered && (reqFirstRow < firstRendered || reqFirstRow > lastRendered + 1))) {
  2372. setReqFirstRow(firstToBeRendered);
  2373. }
  2374. if (lastRendered < lastToBeRendered
  2375. && lastRendered + reqRows < lastToBeRendered) {
  2376. // must increase the required row count accordingly,
  2377. // otherwise may leave a gap and the rows after will get
  2378. // removed
  2379. setReqRows(lastToBeRendered - lastRendered);
  2380. } else if (lastToBeRendered >= firstRendered
  2381. && reqFirstRow + reqRows < firstRendered) {
  2382. setReqRows(lastToBeRendered - lastRendered);
  2383. }
  2384. client.updateVariable(paintableId, "firstToBeRendered",
  2385. firstToBeRendered, false);
  2386. client.updateVariable(paintableId, "lastToBeRendered",
  2387. lastToBeRendered, false);
  2388. // don't request server to update page first index in case it
  2389. // has not been changed
  2390. if (firstRowInViewPort != firstvisible) {
  2391. // remember which firstvisible we requested, in case the
  2392. // server has a differing opinion
  2393. lastRequestedFirstvisible = firstRowInViewPort;
  2394. client.updateVariable(paintableId, "firstvisible",
  2395. firstRowInViewPort, false);
  2396. }
  2397. client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
  2398. false);
  2399. client.updateVariable(paintableId, "reqrows", reqRows, true);
  2400. if (selectionChanged) {
  2401. unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
  2402. selectedRowKeys);
  2403. }
  2404. isRequestHandlerRunning = false;
  2405. }
  2406. }
  2407. /**
  2408. * Sends request to refresh content at this position.
  2409. */
  2410. public void refreshContent() {
  2411. isRequestHandlerRunning = true;
  2412. int first = (int) (firstRowInViewPort - pageLength * cache_rate);
  2413. int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
  2414. if (first < 0) {
  2415. reqRows = reqRows + first;
  2416. first = 0;
  2417. }
  2418. setReqFirstRow(first);
  2419. setReqRows(reqRows);
  2420. run();
  2421. }
  2422. }
  2423. public class HeaderCell extends Widget {
  2424. Element td = DOM.createTD();
  2425. Element captionContainer = DOM.createDiv();
  2426. Element sortIndicator = DOM.createDiv();
  2427. Element colResizeWidget = DOM.createDiv();
  2428. Element floatingCopyOfHeaderCell;
  2429. private boolean sortable = false;
  2430. private final String cid;
  2431. private boolean dragging;
  2432. private Integer currentDragX = null; // is used to resolve #14796
  2433. private int dragStartX;
  2434. private int colIndex;
  2435. private int originalWidth;
  2436. private boolean isResizing;
  2437. private int headerX;
  2438. private boolean moved;
  2439. private int closestSlot;
  2440. private int width = -1;
  2441. private int naturalWidth = -1;
  2442. private char align = ALIGN_LEFT;
  2443. boolean definedWidth = false;
  2444. private float expandRatio = 0;
  2445. private boolean sorted;
  2446. public void setSortable(boolean b) {
  2447. sortable = b;
  2448. }
  2449. /**
  2450. * Makes room for the sorting indicator in case the column that the
  2451. * header cell belongs to is sorted. This is done by resizing the width
  2452. * of the caption container element by the correct amount
  2453. */
  2454. public void resizeCaptionContainer(int rightSpacing) {
  2455. int captionContainerWidth = width
  2456. - colResizeWidget.getOffsetWidth() - rightSpacing;
  2457. if (td.getClassName().contains("-asc")
  2458. || td.getClassName().contains("-desc")) {
  2459. // Leave room for the sort indicator
  2460. captionContainerWidth -= sortIndicator.getOffsetWidth();
  2461. }
  2462. if (captionContainerWidth < 0) {
  2463. rightSpacing += captionContainerWidth;
  2464. captionContainerWidth = 0;
  2465. }
  2466. captionContainer.getStyle().setPropertyPx("width",
  2467. captionContainerWidth);
  2468. // Apply/Remove spacing if defined
  2469. if (rightSpacing > 0) {
  2470. colResizeWidget.getStyle().setMarginLeft(rightSpacing, Unit.PX);
  2471. } else {
  2472. colResizeWidget.getStyle().clearMarginLeft();
  2473. }
  2474. }
  2475. public void setNaturalMinimumColumnWidth(int w) {
  2476. naturalWidth = w;
  2477. }
  2478. public HeaderCell(String colId, String headerText) {
  2479. cid = colId;
  2480. setText(headerText);
  2481. td.appendChild(colResizeWidget);
  2482. // ensure no clipping initially (problem on column additions)
  2483. captionContainer.getStyle().setOverflow(Overflow.VISIBLE);
  2484. td.appendChild(sortIndicator);
  2485. td.appendChild(captionContainer);
  2486. DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
  2487. | Event.ONCONTEXTMENU | Event.TOUCHEVENTS);
  2488. setElement(td);
  2489. setAlign(ALIGN_LEFT);
  2490. }
  2491. protected void updateStyleNames(String primaryStyleName) {
  2492. colResizeWidget.setClassName(primaryStyleName + "-resizer");
  2493. sortIndicator.setClassName(primaryStyleName + "-sort-indicator");
  2494. captionContainer.setClassName(primaryStyleName
  2495. + "-caption-container");
  2496. if (sorted) {
  2497. if (sortAscending) {
  2498. setStyleName(primaryStyleName + "-header-cell-asc");
  2499. } else {
  2500. setStyleName(primaryStyleName + "-header-cell-desc");
  2501. }
  2502. } else {
  2503. setStyleName(primaryStyleName + "-header-cell");
  2504. }
  2505. final String ALIGN_PREFIX = primaryStyleName
  2506. + "-caption-container-align-";
  2507. switch (align) {
  2508. case ALIGN_CENTER:
  2509. captionContainer.addClassName(ALIGN_PREFIX + "center");
  2510. break;
  2511. case ALIGN_RIGHT:
  2512. captionContainer.addClassName(ALIGN_PREFIX + "right");
  2513. break;
  2514. default:
  2515. captionContainer.addClassName(ALIGN_PREFIX + "left");
  2516. break;
  2517. }
  2518. }
  2519. public void disableAutoWidthCalculation() {
  2520. definedWidth = true;
  2521. expandRatio = 0;
  2522. }
  2523. /**
  2524. * Sets width to the header cell. This width should not include any
  2525. * possible indent modifications that are present in
  2526. * {@link VScrollTableBody#getMaxIndent()}.
  2527. *
  2528. * @param w
  2529. * required width of the cell sans indentations
  2530. * @param ensureDefinedWidth
  2531. * disables expand ratio if required
  2532. */
  2533. public void setWidth(int w, boolean ensureDefinedWidth) {
  2534. if (ensureDefinedWidth) {
  2535. definedWidth = true;
  2536. // on column resize expand ratio becomes zero
  2537. expandRatio = 0;
  2538. }
  2539. if (width == -1) {
  2540. // go to default mode, clip content if necessary
  2541. captionContainer.getStyle().clearOverflow();
  2542. }
  2543. width = w;
  2544. if (w == -1) {
  2545. captionContainer.getStyle().clearWidth();
  2546. setWidth("");
  2547. } else {
  2548. tHead.resizeCaptionContainer(this);
  2549. /*
  2550. * if we already have tBody, set the header width properly, if
  2551. * not defer it. IE will fail with complex float in table header
  2552. * unless TD width is not explicitly set.
  2553. */
  2554. if (scrollBody != null) {
  2555. int maxIndent = scrollBody.getMaxIndent();
  2556. if (w < maxIndent && isHierarchyColumn()) {
  2557. w = maxIndent;
  2558. }
  2559. int tdWidth = w + scrollBody.getCellExtraWidth();
  2560. setWidth(tdWidth + "px");
  2561. } else {
  2562. Scheduler.get().scheduleDeferred(new Command() {
  2563. @Override
  2564. public void execute() {
  2565. int maxIndent = scrollBody.getMaxIndent();
  2566. int tdWidth = width;
  2567. if (tdWidth < maxIndent && isHierarchyColumn()) {
  2568. tdWidth = maxIndent;
  2569. }
  2570. tdWidth += scrollBody.getCellExtraWidth();
  2571. setWidth(tdWidth + "px");
  2572. }
  2573. });
  2574. }
  2575. }
  2576. }
  2577. public void setUndefinedWidth() {
  2578. definedWidth = false;
  2579. if (!isResizing) {
  2580. setWidth(-1, false);
  2581. }
  2582. }
  2583. private void setUndefinedWidthFlagOnly() {
  2584. definedWidth = false;
  2585. }
  2586. /**
  2587. * Detects if width is fixed by developer on server side or resized to
  2588. * current width by user.
  2589. *
  2590. * @return true if defined, false if "natural" width
  2591. */
  2592. public boolean isDefinedWidth() {
  2593. return definedWidth && width >= 0;
  2594. }
  2595. /**
  2596. * This method exists for the needs of {@link VTreeTable} only.
  2597. *
  2598. * Returns the pixels width of the header cell. This includes the
  2599. * indent, if applicable.
  2600. *
  2601. * @return The width in pixels
  2602. */
  2603. protected int getWidthWithIndent() {
  2604. if (scrollBody != null && isHierarchyColumn()) {
  2605. int maxIndent = scrollBody.getMaxIndent();
  2606. if (maxIndent > width) {
  2607. return maxIndent;
  2608. }
  2609. }
  2610. return width;
  2611. }
  2612. /**
  2613. * Returns the pixels width of the header cell.
  2614. *
  2615. * @return The width in pixels
  2616. */
  2617. public int getWidth() {
  2618. return width;
  2619. }
  2620. /**
  2621. * This method exists for the needs of {@link VTreeTable} only.
  2622. *
  2623. * @return <code>true</code> if this is hierarcyColumn's header cell,
  2624. * <code>false</code> otherwise
  2625. */
  2626. private boolean isHierarchyColumn() {
  2627. int hierarchyColumnIndex = getHierarchyColumnIndex();
  2628. return hierarchyColumnIndex >= 0
  2629. && tHead.visibleCells.indexOf(this) == hierarchyColumnIndex;
  2630. }
  2631. public void setText(String headerText) {
  2632. DOM.setInnerHTML(captionContainer, headerText);
  2633. }
  2634. public String getColKey() {
  2635. return cid;
  2636. }
  2637. private void setSorted(boolean sorted) {
  2638. this.sorted = sorted;
  2639. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  2640. }
  2641. /**
  2642. * Handle column reordering.
  2643. */
  2644. @Override
  2645. public void onBrowserEvent(Event event) {
  2646. if (enabled && event != null) {
  2647. if (isResizing
  2648. || event.getEventTarget().cast() == colResizeWidget) {
  2649. if (dragging
  2650. && (event.getTypeInt() == Event.ONMOUSEUP || event
  2651. .getTypeInt() == Event.ONTOUCHEND)) {
  2652. // Handle releasing column header on spacer #5318
  2653. handleCaptionEvent(event);
  2654. } else {
  2655. onResizeEvent(event);
  2656. }
  2657. } else {
  2658. /*
  2659. * Ensure focus before handling caption event. Otherwise
  2660. * variables changed from caption event may be before
  2661. * variables from other components that fire variables when
  2662. * they lose focus.
  2663. */
  2664. if (event.getTypeInt() == Event.ONMOUSEDOWN
  2665. || event.getTypeInt() == Event.ONTOUCHSTART) {
  2666. scrollBodyPanel.setFocus(true);
  2667. }
  2668. handleCaptionEvent(event);
  2669. boolean stopPropagation = true;
  2670. if (event.getTypeInt() == Event.ONCONTEXTMENU
  2671. && !client.hasEventListeners(VScrollTable.this,
  2672. TableConstants.HEADER_CLICK_EVENT_ID)) {
  2673. // Prevent showing the browser's context menu only when
  2674. // there is a header click listener.
  2675. stopPropagation = false;
  2676. }
  2677. if (stopPropagation) {
  2678. event.stopPropagation();
  2679. event.preventDefault();
  2680. }
  2681. }
  2682. }
  2683. }
  2684. private void createFloatingCopy() {
  2685. floatingCopyOfHeaderCell = DOM.createDiv();
  2686. DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
  2687. floatingCopyOfHeaderCell = DOM
  2688. .getChild(floatingCopyOfHeaderCell, 2);
  2689. // #12714 the shown "ghost element" should be inside
  2690. // v-overlay-container, and it should contain the same styles as the
  2691. // table to enable theming (except v-table & v-widget).
  2692. String stylePrimaryName = VScrollTable.this.getStylePrimaryName();
  2693. StringBuilder sb = new StringBuilder();
  2694. for (String s : VScrollTable.this.getStyleName().split(" ")) {
  2695. if (!s.equals(StyleConstants.UI_WIDGET)) {
  2696. sb.append(s);
  2697. if (s.equals(stylePrimaryName)) {
  2698. sb.append("-header-drag ");
  2699. } else {
  2700. sb.append(" ");
  2701. }
  2702. }
  2703. }
  2704. floatingCopyOfHeaderCell.setClassName(sb.toString().trim());
  2705. // otherwise might wrap or be cut if narrow column
  2706. floatingCopyOfHeaderCell.getStyle().setProperty("width", "auto");
  2707. updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
  2708. DOM.getAbsoluteTop(td));
  2709. DOM.appendChild(VOverlay.getOverlayContainer(client),
  2710. floatingCopyOfHeaderCell);
  2711. }
  2712. private void updateFloatingCopysPosition(int x, int y) {
  2713. x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
  2714. "offsetWidth") / 2;
  2715. floatingCopyOfHeaderCell.getStyle().setLeft(x, Unit.PX);
  2716. if (y > 0) {
  2717. floatingCopyOfHeaderCell.getStyle().setTop(y + 7, Unit.PX);
  2718. }
  2719. }
  2720. private void hideFloatingCopy() {
  2721. floatingCopyOfHeaderCell.removeFromParent();
  2722. floatingCopyOfHeaderCell = null;
  2723. }
  2724. /**
  2725. * Fires a header click event after the user has clicked a column header
  2726. * cell
  2727. *
  2728. * @param event
  2729. * The click event
  2730. */
  2731. private void fireHeaderClickedEvent(Event event) {
  2732. if (client.hasEventListeners(VScrollTable.this,
  2733. TableConstants.HEADER_CLICK_EVENT_ID)) {
  2734. MouseEventDetails details = MouseEventDetailsBuilder
  2735. .buildMouseEventDetails(event);
  2736. client.updateVariable(paintableId, "headerClickEvent",
  2737. details.toString(), false);
  2738. client.updateVariable(paintableId, "headerClickCID", cid, true);
  2739. }
  2740. }
  2741. protected void handleCaptionEvent(Event event) {
  2742. switch (DOM.eventGetType(event)) {
  2743. case Event.ONTOUCHSTART:
  2744. case Event.ONMOUSEDOWN:
  2745. if (columnReordering
  2746. && WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2747. if (event.getTypeInt() == Event.ONTOUCHSTART) {
  2748. /*
  2749. * prevent using this event in e.g. scrolling
  2750. */
  2751. event.stopPropagation();
  2752. }
  2753. dragging = true;
  2754. currentDragX = WidgetUtil.getTouchOrMouseClientX(event);
  2755. moved = false;
  2756. colIndex = getColIndexByKey(cid);
  2757. DOM.setCapture(getElement());
  2758. headerX = tHead.getAbsoluteLeft();
  2759. event.preventDefault(); // prevent selecting text &&
  2760. // generated touch events
  2761. }
  2762. break;
  2763. case Event.ONMOUSEUP:
  2764. case Event.ONTOUCHEND:
  2765. case Event.ONTOUCHCANCEL:
  2766. if (columnReordering
  2767. && WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2768. dragging = false;
  2769. currentDragX = null;
  2770. DOM.releaseCapture(getElement());
  2771. if (WidgetUtil.isTouchEvent(event)) {
  2772. /*
  2773. * Prevent using in e.g. scrolling and prevent generated
  2774. * events.
  2775. */
  2776. event.preventDefault();
  2777. event.stopPropagation();
  2778. }
  2779. if (moved) {
  2780. hideFloatingCopy();
  2781. tHead.removeSlotFocus();
  2782. if (closestSlot != colIndex
  2783. && closestSlot != (colIndex + 1)) {
  2784. if (closestSlot > colIndex) {
  2785. reOrderColumn(cid, closestSlot - 1);
  2786. } else {
  2787. reOrderColumn(cid, closestSlot);
  2788. }
  2789. }
  2790. moved = false;
  2791. break;
  2792. }
  2793. }
  2794. if (!moved) {
  2795. // mouse event was a click to header -> sort column
  2796. if (sortable
  2797. && WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2798. if (sortColumn.equals(cid)) {
  2799. // just toggle order
  2800. client.updateVariable(paintableId, "sortascending",
  2801. !sortAscending, false);
  2802. } else {
  2803. // set table sorted by this column
  2804. client.updateVariable(paintableId, "sortcolumn",
  2805. cid, false);
  2806. }
  2807. // get also cache columns at the same request
  2808. scrollBodyPanel.setScrollPosition(0);
  2809. firstvisible = 0;
  2810. rowRequestHandler.setReqFirstRow(0);
  2811. rowRequestHandler.setReqRows((int) (2 * pageLength
  2812. * cache_rate + pageLength));
  2813. rowRequestHandler.deferRowFetch(); // some validation +
  2814. // defer 250ms
  2815. rowRequestHandler.cancel(); // instead of waiting
  2816. rowRequestHandler.run(); // run immediately
  2817. }
  2818. fireHeaderClickedEvent(event);
  2819. if (WidgetUtil.isTouchEvent(event)) {
  2820. /*
  2821. * Prevent using in e.g. scrolling and prevent generated
  2822. * events.
  2823. */
  2824. event.preventDefault();
  2825. event.stopPropagation();
  2826. }
  2827. break;
  2828. }
  2829. break;
  2830. case Event.ONDBLCLICK:
  2831. fireHeaderClickedEvent(event);
  2832. break;
  2833. case Event.ONTOUCHMOVE:
  2834. case Event.ONMOUSEMOVE:
  2835. // only start the drag if the mouse / touch has moved a minimum
  2836. // distance in x-axis (the same idea as in #13381)
  2837. int currentX = WidgetUtil.getTouchOrMouseClientX(event);
  2838. if (currentDragX == null
  2839. || Math.abs(currentDragX - currentX) > VDragAndDropManager.MINIMUM_DISTANCE_TO_START_DRAG) {
  2840. if (dragging
  2841. && WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2842. if (event.getTypeInt() == Event.ONTOUCHMOVE) {
  2843. /*
  2844. * prevent using this event in e.g. scrolling
  2845. */
  2846. event.stopPropagation();
  2847. }
  2848. if (!moved) {
  2849. createFloatingCopy();
  2850. moved = true;
  2851. }
  2852. final int clientX = WidgetUtil
  2853. .getTouchOrMouseClientX(event);
  2854. final int x = clientX
  2855. + tHead.hTableWrapper.getScrollLeft();
  2856. int slotX = headerX;
  2857. closestSlot = colIndex;
  2858. int closestDistance = -1;
  2859. int start = 0;
  2860. if (showRowHeaders) {
  2861. start++;
  2862. }
  2863. final int visibleCellCount = tHead
  2864. .getVisibleCellCount();
  2865. for (int i = start; i <= visibleCellCount; i++) {
  2866. if (i > 0) {
  2867. final String colKey = getColKeyByIndex(i - 1);
  2868. // getColWidth only returns the internal width
  2869. // without padding, not the offset width of the
  2870. // whole td (#10890)
  2871. slotX += getColWidth(colKey)
  2872. + scrollBody.getCellExtraWidth();
  2873. }
  2874. final int dist = Math.abs(x - slotX);
  2875. if (closestDistance == -1 || dist < closestDistance) {
  2876. closestDistance = dist;
  2877. closestSlot = i;
  2878. }
  2879. }
  2880. tHead.focusSlot(closestSlot);
  2881. updateFloatingCopysPosition(clientX, -1);
  2882. }
  2883. }
  2884. break;
  2885. default:
  2886. break;
  2887. }
  2888. }
  2889. private void onResizeEvent(Event event) {
  2890. switch (DOM.eventGetType(event)) {
  2891. case Event.ONMOUSEDOWN:
  2892. if (!WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2893. return;
  2894. }
  2895. isResizing = true;
  2896. DOM.setCapture(getElement());
  2897. dragStartX = DOM.eventGetClientX(event);
  2898. colIndex = getColIndexByKey(cid);
  2899. originalWidth = getWidthWithIndent();
  2900. DOM.eventPreventDefault(event);
  2901. break;
  2902. case Event.ONMOUSEUP:
  2903. if (!WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2904. return;
  2905. }
  2906. isResizing = false;
  2907. DOM.releaseCapture(getElement());
  2908. tHead.disableAutoColumnWidthCalculation(this);
  2909. // Ensure last header cell is taking into account possible
  2910. // column selector
  2911. HeaderCell lastCell = tHead.getHeaderCell(tHead
  2912. .getVisibleCellCount() - 1);
  2913. tHead.resizeCaptionContainer(lastCell);
  2914. triggerLazyColumnAdjustment(true);
  2915. fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
  2916. break;
  2917. case Event.ONMOUSEMOVE:
  2918. if (!WidgetUtil.isTouchEventOrLeftMouseButton(event)) {
  2919. return;
  2920. }
  2921. if (isResizing) {
  2922. final int deltaX = DOM.eventGetClientX(event) - dragStartX;
  2923. if (deltaX == 0) {
  2924. return;
  2925. }
  2926. tHead.disableAutoColumnWidthCalculation(this);
  2927. int newWidth = originalWidth + deltaX;
  2928. // get min width with indent, no padding
  2929. int minWidth = getMinWidth(true, false);
  2930. if (newWidth < minWidth) {
  2931. // already includes indent if any
  2932. newWidth = minWidth;
  2933. }
  2934. setColWidth(colIndex, newWidth, true);
  2935. triggerLazyColumnAdjustment(false);
  2936. forceRealignColumnHeaders();
  2937. }
  2938. break;
  2939. default:
  2940. break;
  2941. }
  2942. }
  2943. /**
  2944. * Returns the smallest possible cell width in pixels.
  2945. *
  2946. * @param includeIndent
  2947. * - width should include hierarchy column indent if
  2948. * applicable (VTreeTable only)
  2949. * @param includeCellExtraWidth
  2950. * - width should include paddings etc.
  2951. * @return
  2952. */
  2953. private int getMinWidth(boolean includeIndent,
  2954. boolean includeCellExtraWidth) {
  2955. int minWidth = sortIndicator.getOffsetWidth();
  2956. if (scrollBody != null) {
  2957. // check the need for indent before adding paddings etc.
  2958. if (includeIndent && isHierarchyColumn()) {
  2959. int maxIndent = scrollBody.getMaxIndent();
  2960. if (minWidth < maxIndent) {
  2961. minWidth = maxIndent;
  2962. }
  2963. }
  2964. if (includeCellExtraWidth) {
  2965. minWidth += scrollBody.getCellExtraWidth();
  2966. }
  2967. }
  2968. return minWidth;
  2969. }
  2970. public int getMinWidth() {
  2971. // get min width with padding, no indent
  2972. return getMinWidth(false, true);
  2973. }
  2974. public String getCaption() {
  2975. return DOM.getInnerText(captionContainer);
  2976. }
  2977. public boolean isEnabled() {
  2978. return getParent() != null;
  2979. }
  2980. public void setAlign(char c) {
  2981. align = c;
  2982. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  2983. }
  2984. public char getAlign() {
  2985. return align;
  2986. }
  2987. /**
  2988. * Saves natural column width if it hasn't been saved already.
  2989. *
  2990. * @param columnIndex
  2991. * @since 7.3.9
  2992. */
  2993. protected void saveNaturalColumnWidthIfNotSaved(int columnIndex) {
  2994. if (naturalWidth < 0) {
  2995. // This is recently revealed column. Try to detect a proper
  2996. // value (greater of header and data columns)
  2997. int hw = captionContainer.getOffsetWidth() + getHeaderPadding();
  2998. if (BrowserInfo.get().isGecko()) {
  2999. hw += sortIndicator.getOffsetWidth();
  3000. }
  3001. if (columnIndex < 0) {
  3002. columnIndex = 0;
  3003. for (Iterator<Widget> it = tHead.iterator(); it.hasNext(); columnIndex++) {
  3004. if (it.next() == this) {
  3005. break;
  3006. }
  3007. }
  3008. }
  3009. final int cw = scrollBody.getColWidth(columnIndex);
  3010. naturalWidth = (hw > cw ? hw : cw);
  3011. }
  3012. }
  3013. /**
  3014. * Detects the natural minimum width for the column of this header cell.
  3015. * If column is resized by user or the width is defined by server the
  3016. * actual width is returned. Else the natural min width is returned.
  3017. *
  3018. * @param columnIndex
  3019. * column index hint, if -1 (unknown) it will be detected
  3020. *
  3021. * @return
  3022. */
  3023. public int getNaturalColumnWidth(int columnIndex) {
  3024. final int iw = columnIndex == getHierarchyColumnIndex() ? scrollBody
  3025. .getMaxIndent() : 0;
  3026. saveNaturalColumnWidthIfNotSaved(columnIndex);
  3027. if (isDefinedWidth()) {
  3028. if (iw > width) {
  3029. return iw;
  3030. }
  3031. return width;
  3032. } else {
  3033. if (iw > naturalWidth) {
  3034. // indent is temporary value, naturalWidth shouldn't be
  3035. // updated
  3036. return iw;
  3037. } else {
  3038. return naturalWidth;
  3039. }
  3040. }
  3041. }
  3042. public void setExpandRatio(float floatAttribute) {
  3043. if (floatAttribute != expandRatio) {
  3044. triggerLazyColumnAdjustment(false);
  3045. }
  3046. expandRatio = floatAttribute;
  3047. }
  3048. public float getExpandRatio() {
  3049. return expandRatio;
  3050. }
  3051. public boolean isSorted() {
  3052. return sorted;
  3053. }
  3054. }
  3055. /**
  3056. * HeaderCell that is header cell for row headers.
  3057. *
  3058. * Reordering disabled and clicking on it resets sorting.
  3059. */
  3060. public class RowHeadersHeaderCell extends HeaderCell {
  3061. RowHeadersHeaderCell() {
  3062. super(ROW_HEADER_COLUMN_KEY, "");
  3063. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3064. }
  3065. @Override
  3066. protected void updateStyleNames(String primaryStyleName) {
  3067. super.updateStyleNames(primaryStyleName);
  3068. setStyleName(primaryStyleName + "-header-cell-rowheader");
  3069. }
  3070. @Override
  3071. protected void handleCaptionEvent(Event event) {
  3072. // NOP: RowHeaders cannot be reordered
  3073. // TODO It'd be nice to reset sorting here
  3074. }
  3075. }
  3076. public class TableHead extends Panel implements ActionOwner {
  3077. private static final int WRAPPER_WIDTH = 900000;
  3078. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  3079. HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
  3080. Element div = DOM.createDiv();
  3081. Element hTableWrapper = DOM.createDiv();
  3082. Element hTableContainer = DOM.createDiv();
  3083. Element table = DOM.createTable();
  3084. Element headerTableBody = DOM.createTBody();
  3085. Element tr = DOM.createTR();
  3086. private final Element columnSelector = DOM.createDiv();
  3087. private int focusedSlot = -1;
  3088. public TableHead() {
  3089. if (BrowserInfo.get().isIE()) {
  3090. table.setPropertyInt("cellSpacing", 0);
  3091. }
  3092. hTableWrapper.getStyle().setOverflow(Overflow.HIDDEN);
  3093. columnSelector.getStyle().setDisplay(Display.NONE);
  3094. DOM.appendChild(table, headerTableBody);
  3095. DOM.appendChild(headerTableBody, tr);
  3096. DOM.appendChild(hTableContainer, table);
  3097. DOM.appendChild(hTableWrapper, hTableContainer);
  3098. DOM.appendChild(div, hTableWrapper);
  3099. DOM.appendChild(div, columnSelector);
  3100. setElement(div);
  3101. DOM.sinkEvents(columnSelector, Event.ONCLICK);
  3102. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3103. new RowHeadersHeaderCell());
  3104. }
  3105. protected void updateStyleNames(String primaryStyleName) {
  3106. hTableWrapper.setClassName(primaryStyleName + "-header");
  3107. columnSelector.setClassName(primaryStyleName + "-column-selector");
  3108. setStyleName(primaryStyleName + "-header-wrap");
  3109. for (HeaderCell c : availableCells.values()) {
  3110. c.updateStyleNames(primaryStyleName);
  3111. }
  3112. }
  3113. public void resizeCaptionContainer(HeaderCell cell) {
  3114. HeaderCell lastcell = getHeaderCell(visibleCells.size() - 1);
  3115. int columnSelectorOffset = columnSelector.getOffsetWidth();
  3116. if (cell == lastcell && columnSelectorOffset > 0
  3117. && !hasVerticalScrollbar()) {
  3118. // Measure column widths
  3119. int columnTotalWidth = 0;
  3120. for (Widget w : visibleCells) {
  3121. int cellExtraWidth = w.getOffsetWidth();
  3122. if (scrollBody != null
  3123. && visibleCells.indexOf(w) == getHierarchyColumnIndex()
  3124. && cellExtraWidth < scrollBody.getMaxIndent()) {
  3125. // indent must be taken into consideration even if it
  3126. // hasn't been applied yet
  3127. columnTotalWidth += scrollBody.getMaxIndent();
  3128. } else {
  3129. columnTotalWidth += cellExtraWidth;
  3130. }
  3131. }
  3132. int divOffset = div.getOffsetWidth();
  3133. if (columnTotalWidth >= divOffset - columnSelectorOffset) {
  3134. /*
  3135. * Ensure column caption is visible when placed under the
  3136. * column selector widget by shifting and resizing the
  3137. * caption.
  3138. */
  3139. int offset = 0;
  3140. int diff = divOffset - columnTotalWidth;
  3141. if (diff < columnSelectorOffset && diff > 0) {
  3142. /*
  3143. * If the difference is less than the column selectors
  3144. * width then just offset by the difference
  3145. */
  3146. offset = columnSelectorOffset - diff;
  3147. } else {
  3148. // Else offset by the whole column selector
  3149. offset = columnSelectorOffset;
  3150. }
  3151. lastcell.resizeCaptionContainer(offset);
  3152. } else {
  3153. cell.resizeCaptionContainer(0);
  3154. }
  3155. } else {
  3156. cell.resizeCaptionContainer(0);
  3157. }
  3158. }
  3159. @Override
  3160. public void clear() {
  3161. for (String cid : availableCells.keySet()) {
  3162. removeCell(cid);
  3163. }
  3164. availableCells.clear();
  3165. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3166. new RowHeadersHeaderCell());
  3167. }
  3168. public void updateCellsFromUIDL(UIDL uidl) {
  3169. Iterator<?> it = uidl.getChildIterator();
  3170. HashSet<String> updated = new HashSet<String>();
  3171. boolean refreshContentWidths = initializedAndAttached
  3172. && hadScrollBars != willHaveScrollbars();
  3173. while (it.hasNext()) {
  3174. final UIDL col = (UIDL) it.next();
  3175. final String cid = col.getStringAttribute("cid");
  3176. updated.add(cid);
  3177. String caption = buildCaptionHtmlSnippet(col);
  3178. HeaderCell c = getHeaderCell(cid);
  3179. if (c == null) {
  3180. c = new HeaderCell(cid, caption);
  3181. availableCells.put(cid, c);
  3182. if (initializedAndAttached) {
  3183. // we will need a column width recalculation
  3184. initializedAndAttached = false;
  3185. initialContentReceived = false;
  3186. isNewBody = true;
  3187. }
  3188. } else {
  3189. c.setText(caption);
  3190. }
  3191. c.setSorted(false);
  3192. if (col.hasAttribute("sortable")) {
  3193. c.setSortable(true);
  3194. } else {
  3195. c.setSortable(false);
  3196. }
  3197. if (col.hasAttribute("align")) {
  3198. c.setAlign(col.getStringAttribute("align").charAt(0));
  3199. } else {
  3200. c.setAlign(ALIGN_LEFT);
  3201. }
  3202. if (col.hasAttribute("width") && !c.isResizing) {
  3203. // Make sure to accomodate for the sort indicator if
  3204. // necessary.
  3205. int width = col.getIntAttribute("width");
  3206. int widthWithoutAddedIndent = width;
  3207. // get min width with indent, no padding
  3208. int minWidth = c.getMinWidth(true, false);
  3209. if (width < minWidth) {
  3210. width = minWidth;
  3211. }
  3212. if (scrollBody != null && width != c.getWidthWithIndent()) {
  3213. // Do a more thorough update if a column is resized from
  3214. // the server *after* the header has been properly
  3215. // initialized
  3216. final int newWidth = width;
  3217. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  3218. @Override
  3219. public void execute() {
  3220. final int colIx = getColIndexByKey(cid);
  3221. setColWidth(colIx, newWidth, true);
  3222. }
  3223. });
  3224. refreshContentWidths = true;
  3225. } else {
  3226. // get min width with no indent or padding
  3227. minWidth = c.getMinWidth(false, false);
  3228. if (widthWithoutAddedIndent < minWidth) {
  3229. widthWithoutAddedIndent = minWidth;
  3230. }
  3231. // save min width without indent
  3232. c.setWidth(widthWithoutAddedIndent, true);
  3233. }
  3234. } else if (col.hasAttribute("er")) {
  3235. c.setExpandRatio(col.getFloatAttribute("er"));
  3236. c.setUndefinedWidthFlagOnly();
  3237. } else if (recalcWidths) {
  3238. c.setUndefinedWidth();
  3239. } else {
  3240. boolean hadExpandRatio = c.getExpandRatio() > 0;
  3241. boolean hadDefinedWidth = c.isDefinedWidth();
  3242. if (hadExpandRatio || hadDefinedWidth) {
  3243. // Someone has removed a expand width or the defined
  3244. // width on the server side (setting it to -1), make the
  3245. // column undefined again and measure columns again.
  3246. c.setUndefinedWidth();
  3247. c.setExpandRatio(0);
  3248. refreshContentWidths = true;
  3249. }
  3250. }
  3251. if (col.hasAttribute("collapsed")) {
  3252. // ensure header is properly removed from parent (case when
  3253. // collapsing happens via servers side api)
  3254. if (c.isAttached()) {
  3255. c.removeFromParent();
  3256. headerChangedDuringUpdate = true;
  3257. }
  3258. }
  3259. }
  3260. if (refreshContentWidths) {
  3261. // Recalculate the column sizings if any column has changed
  3262. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  3263. @Override
  3264. public void execute() {
  3265. triggerLazyColumnAdjustment(true);
  3266. }
  3267. });
  3268. }
  3269. // check for orphaned header cells
  3270. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  3271. .hasNext();) {
  3272. String cid = cit.next();
  3273. if (!updated.contains(cid)) {
  3274. removeCell(cid);
  3275. cit.remove();
  3276. // we will need a column width recalculation, since columns
  3277. // with expand ratios should expand to fill the void.
  3278. initializedAndAttached = false;
  3279. initialContentReceived = false;
  3280. isNewBody = true;
  3281. }
  3282. }
  3283. }
  3284. public void enableColumn(String cid, int index) {
  3285. final HeaderCell c = getHeaderCell(cid);
  3286. if (!c.isEnabled() || getHeaderCell(index) != c) {
  3287. setHeaderCell(index, c);
  3288. if (initializedAndAttached) {
  3289. headerChangedDuringUpdate = true;
  3290. }
  3291. }
  3292. }
  3293. public int getVisibleCellCount() {
  3294. return visibleCells.size();
  3295. }
  3296. public void setHorizontalScrollPosition(int scrollLeft) {
  3297. hTableWrapper.setScrollLeft(scrollLeft);
  3298. }
  3299. public void setColumnCollapsingAllowed(boolean cc) {
  3300. if (cc) {
  3301. columnSelector.getStyle().setDisplay(Display.BLOCK);
  3302. } else {
  3303. columnSelector.getStyle().setDisplay(Display.NONE);
  3304. }
  3305. }
  3306. public void disableBrowserIntelligence() {
  3307. hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
  3308. }
  3309. public void enableBrowserIntelligence() {
  3310. hTableContainer.getStyle().clearWidth();
  3311. }
  3312. public void setHeaderCell(int index, HeaderCell cell) {
  3313. if (cell.isEnabled()) {
  3314. // we're moving the cell
  3315. DOM.removeChild(tr, cell.getElement());
  3316. orphan(cell);
  3317. visibleCells.remove(cell);
  3318. }
  3319. if (index < visibleCells.size()) {
  3320. // insert to right slot
  3321. DOM.insertChild(tr, cell.getElement(), index);
  3322. adopt(cell);
  3323. visibleCells.add(index, cell);
  3324. } else if (index == visibleCells.size()) {
  3325. // simply append
  3326. DOM.appendChild(tr, cell.getElement());
  3327. adopt(cell);
  3328. visibleCells.add(cell);
  3329. } else {
  3330. throw new RuntimeException(
  3331. "Header cells must be appended in order");
  3332. }
  3333. }
  3334. public HeaderCell getHeaderCell(int index) {
  3335. if (index >= 0 && index < visibleCells.size()) {
  3336. return (HeaderCell) visibleCells.get(index);
  3337. } else {
  3338. return null;
  3339. }
  3340. }
  3341. /**
  3342. * Get's HeaderCell by it's column Key.
  3343. *
  3344. * Note that this returns HeaderCell even if it is currently collapsed.
  3345. *
  3346. * @param cid
  3347. * Column key of accessed HeaderCell
  3348. * @return HeaderCell
  3349. */
  3350. public HeaderCell getHeaderCell(String cid) {
  3351. return availableCells.get(cid);
  3352. }
  3353. public void moveCell(int oldIndex, int newIndex) {
  3354. final HeaderCell hCell = getHeaderCell(oldIndex);
  3355. final Element cell = hCell.getElement();
  3356. visibleCells.remove(oldIndex);
  3357. DOM.removeChild(tr, cell);
  3358. DOM.insertChild(tr, cell, newIndex);
  3359. visibleCells.add(newIndex, hCell);
  3360. }
  3361. @Override
  3362. public Iterator<Widget> iterator() {
  3363. return visibleCells.iterator();
  3364. }
  3365. @Override
  3366. public boolean remove(Widget w) {
  3367. if (visibleCells.contains(w)) {
  3368. visibleCells.remove(w);
  3369. orphan(w);
  3370. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  3371. return true;
  3372. }
  3373. return false;
  3374. }
  3375. public void removeCell(String colKey) {
  3376. final HeaderCell c = getHeaderCell(colKey);
  3377. remove(c);
  3378. }
  3379. private void focusSlot(int index) {
  3380. removeSlotFocus();
  3381. if (index > 0) {
  3382. Element child = tr.getChild(index - 1).getFirstChild().cast();
  3383. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3384. + "-resizer");
  3385. child.addClassName(VScrollTable.this.getStylePrimaryName()
  3386. + "-focus-slot-right");
  3387. } else {
  3388. Element child = tr.getChild(index).getFirstChild().cast();
  3389. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3390. + "-resizer");
  3391. child.addClassName(VScrollTable.this.getStylePrimaryName()
  3392. + "-focus-slot-left");
  3393. }
  3394. focusedSlot = index;
  3395. }
  3396. private void removeSlotFocus() {
  3397. if (focusedSlot < 0) {
  3398. return;
  3399. }
  3400. if (focusedSlot == 0) {
  3401. Element child = tr.getChild(focusedSlot).getFirstChild().cast();
  3402. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3403. + "-resizer");
  3404. } else if (focusedSlot > 0) {
  3405. Element child = tr.getChild(focusedSlot - 1).getFirstChild()
  3406. .cast();
  3407. child.setClassName(VScrollTable.this.getStylePrimaryName()
  3408. + "-resizer");
  3409. }
  3410. focusedSlot = -1;
  3411. }
  3412. @Override
  3413. public void onBrowserEvent(Event event) {
  3414. if (enabled) {
  3415. if (event.getEventTarget().cast() == columnSelector) {
  3416. final int left = DOM.getAbsoluteLeft(columnSelector);
  3417. final int top = DOM.getAbsoluteTop(columnSelector)
  3418. + DOM.getElementPropertyInt(columnSelector,
  3419. "offsetHeight");
  3420. client.getContextMenu().showAt(this, left, top);
  3421. }
  3422. }
  3423. }
  3424. @Override
  3425. protected void onDetach() {
  3426. super.onDetach();
  3427. if (client != null) {
  3428. client.getContextMenu().ensureHidden(this);
  3429. }
  3430. }
  3431. class VisibleColumnAction extends Action {
  3432. String colKey;
  3433. private boolean collapsed;
  3434. private boolean noncollapsible = false;
  3435. private VScrollTableRow currentlyFocusedRow;
  3436. public VisibleColumnAction(String colKey) {
  3437. super(VScrollTable.TableHead.this);
  3438. this.colKey = colKey;
  3439. caption = tHead.getHeaderCell(colKey).getCaption();
  3440. currentlyFocusedRow = focusedRow;
  3441. }
  3442. @Override
  3443. public void execute() {
  3444. if (noncollapsible) {
  3445. return;
  3446. }
  3447. client.getContextMenu().hide();
  3448. // toggle selected column
  3449. if (collapsedColumns.contains(colKey)) {
  3450. collapsedColumns.remove(colKey);
  3451. } else {
  3452. tHead.removeCell(colKey);
  3453. collapsedColumns.add(colKey);
  3454. triggerLazyColumnAdjustment(true);
  3455. }
  3456. // update variable to server
  3457. client.updateVariable(paintableId, "collapsedcolumns",
  3458. collapsedColumns.toArray(new String[collapsedColumns
  3459. .size()]), false);
  3460. // let rowRequestHandler determine proper rows
  3461. rowRequestHandler.refreshContent();
  3462. lazyRevertFocusToRow(currentlyFocusedRow);
  3463. }
  3464. public void setCollapsed(boolean b) {
  3465. collapsed = b;
  3466. }
  3467. public void setNoncollapsible(boolean b) {
  3468. noncollapsible = b;
  3469. }
  3470. /**
  3471. * Override default method to distinguish on/off columns
  3472. */
  3473. @Override
  3474. public String getHTML() {
  3475. final StringBuffer buf = new StringBuffer();
  3476. buf.append("<span class=\"");
  3477. if (collapsed) {
  3478. buf.append("v-off");
  3479. } else {
  3480. buf.append("v-on");
  3481. }
  3482. if (noncollapsible) {
  3483. buf.append(" v-disabled");
  3484. }
  3485. buf.append("\">");
  3486. buf.append(super.getHTML());
  3487. buf.append("</span>");
  3488. return buf.toString();
  3489. }
  3490. }
  3491. /*
  3492. * Returns columns as Action array for column select popup
  3493. */
  3494. @Override
  3495. public Action[] getActions() {
  3496. Object[] cols;
  3497. if (columnReordering && columnOrder != null) {
  3498. cols = columnOrder;
  3499. } else {
  3500. // if columnReordering is disabled, we need different way to get
  3501. // all available columns
  3502. cols = visibleColOrder;
  3503. cols = new Object[visibleColOrder.length
  3504. + collapsedColumns.size()];
  3505. int i;
  3506. for (i = 0; i < visibleColOrder.length; i++) {
  3507. cols[i] = visibleColOrder[i];
  3508. }
  3509. for (final Iterator<String> it = collapsedColumns.iterator(); it
  3510. .hasNext();) {
  3511. cols[i++] = it.next();
  3512. }
  3513. }
  3514. final Action[] actions = new Action[cols.length];
  3515. for (int i = 0; i < cols.length; i++) {
  3516. final String cid = (String) cols[i];
  3517. final HeaderCell c = getHeaderCell(cid);
  3518. final VisibleColumnAction a = new VisibleColumnAction(
  3519. c.getColKey());
  3520. a.setCaption(c.getCaption());
  3521. if (!c.isEnabled()) {
  3522. a.setCollapsed(true);
  3523. }
  3524. if (noncollapsibleColumns.contains(cid)) {
  3525. a.setNoncollapsible(true);
  3526. }
  3527. actions[i] = a;
  3528. }
  3529. return actions;
  3530. }
  3531. @Override
  3532. public ApplicationConnection getClient() {
  3533. return client;
  3534. }
  3535. @Override
  3536. public String getPaintableId() {
  3537. return paintableId;
  3538. }
  3539. /**
  3540. * Returns column alignments for visible columns
  3541. */
  3542. public char[] getColumnAlignments() {
  3543. final Iterator<Widget> it = visibleCells.iterator();
  3544. final char[] aligns = new char[visibleCells.size()];
  3545. int colIndex = 0;
  3546. while (it.hasNext()) {
  3547. aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
  3548. }
  3549. return aligns;
  3550. }
  3551. /**
  3552. * Disables the automatic calculation of all column widths by forcing
  3553. * the widths to be "defined" thus turning off expand ratios and such.
  3554. */
  3555. public void disableAutoColumnWidthCalculation(HeaderCell source) {
  3556. for (HeaderCell cell : availableCells.values()) {
  3557. cell.disableAutoWidthCalculation();
  3558. }
  3559. // fire column resize events for all columns but the source of the
  3560. // resize action, since an event will fire separately for this.
  3561. ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
  3562. availableCells.values());
  3563. columns.remove(source);
  3564. sendColumnWidthUpdates(columns);
  3565. forceRealignColumnHeaders();
  3566. }
  3567. }
  3568. /**
  3569. * A cell in the footer
  3570. */
  3571. public class FooterCell extends Widget {
  3572. private final Element td = DOM.createTD();
  3573. private final Element captionContainer = DOM.createDiv();
  3574. private char align = ALIGN_LEFT;
  3575. private int width = -1;
  3576. private float expandRatio = 0;
  3577. private final String cid;
  3578. boolean definedWidth = false;
  3579. private int naturalWidth = -1;
  3580. public FooterCell(String colId, String headerText) {
  3581. cid = colId;
  3582. setText(headerText);
  3583. // ensure no clipping initially (problem on column additions)
  3584. captionContainer.getStyle().setOverflow(Overflow.VISIBLE);
  3585. DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
  3586. DOM.appendChild(td, captionContainer);
  3587. DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
  3588. | Event.ONCONTEXTMENU);
  3589. setElement(td);
  3590. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3591. }
  3592. protected void updateStyleNames(String primaryStyleName) {
  3593. captionContainer.setClassName(primaryStyleName
  3594. + "-footer-container");
  3595. }
  3596. /**
  3597. * Sets the text of the footer
  3598. *
  3599. * @param footerText
  3600. * The text in the footer
  3601. */
  3602. public void setText(String footerText) {
  3603. if (footerText == null || footerText.equals("")) {
  3604. footerText = "&nbsp;";
  3605. }
  3606. DOM.setInnerHTML(captionContainer, footerText);
  3607. }
  3608. /**
  3609. * Set alignment of the text in the cell
  3610. *
  3611. * @param c
  3612. * The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
  3613. * ALIGN_RIGHT
  3614. */
  3615. public void setAlign(char c) {
  3616. if (align != c) {
  3617. switch (c) {
  3618. case ALIGN_CENTER:
  3619. captionContainer.getStyle().setTextAlign(TextAlign.CENTER);
  3620. break;
  3621. case ALIGN_RIGHT:
  3622. captionContainer.getStyle().setTextAlign(TextAlign.RIGHT);
  3623. break;
  3624. default:
  3625. captionContainer.getStyle().setTextAlign(TextAlign.LEFT);
  3626. break;
  3627. }
  3628. }
  3629. align = c;
  3630. }
  3631. /**
  3632. * Get the alignment of the text int the cell
  3633. *
  3634. * @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
  3635. */
  3636. public char getAlign() {
  3637. return align;
  3638. }
  3639. /**
  3640. * Sets the width of the cell. This width should not include any
  3641. * possible indent modifications that are present in
  3642. * {@link VScrollTableBody#getMaxIndent()}.
  3643. *
  3644. * @param w
  3645. * The width of the cell
  3646. * @param ensureDefinedWidth
  3647. * Ensures that the given width is not recalculated
  3648. */
  3649. public void setWidth(int w, boolean ensureDefinedWidth) {
  3650. if (ensureDefinedWidth) {
  3651. definedWidth = true;
  3652. // on column resize expand ratio becomes zero
  3653. expandRatio = 0;
  3654. }
  3655. if (width == w) {
  3656. return;
  3657. }
  3658. if (width == -1) {
  3659. // go to default mode, clip content if necessary
  3660. captionContainer.getStyle().clearOverflow();
  3661. }
  3662. width = w;
  3663. if (w == -1) {
  3664. captionContainer.getStyle().clearWidth();
  3665. setWidth("");
  3666. } else {
  3667. /*
  3668. * Reduce width with one pixel for the right border since the
  3669. * footers does not have any spacers between them.
  3670. */
  3671. final int borderWidths = 1;
  3672. // Set the container width (check for negative value)
  3673. captionContainer.getStyle().setPropertyPx("width",
  3674. Math.max(w - borderWidths, 0));
  3675. /*
  3676. * if we already have tBody, set the header width properly, if
  3677. * not defer it. IE will fail with complex float in table header
  3678. * unless TD width is not explicitly set.
  3679. */
  3680. if (scrollBody != null) {
  3681. int maxIndent = scrollBody.getMaxIndent();
  3682. if (w < maxIndent
  3683. && tFoot.visibleCells.indexOf(this) == getHierarchyColumnIndex()) {
  3684. // ensure there's room for the indent
  3685. w = maxIndent;
  3686. }
  3687. int tdWidth = w + scrollBody.getCellExtraWidth()
  3688. - borderWidths;
  3689. setWidth(Math.max(tdWidth, 0) + "px");
  3690. } else {
  3691. Scheduler.get().scheduleDeferred(new Command() {
  3692. @Override
  3693. public void execute() {
  3694. int tdWidth = width;
  3695. int maxIndent = scrollBody.getMaxIndent();
  3696. if (tdWidth < maxIndent
  3697. && tFoot.visibleCells.indexOf(this) == getHierarchyColumnIndex()) {
  3698. // ensure there's room for the indent
  3699. tdWidth = maxIndent;
  3700. }
  3701. tdWidth += scrollBody.getCellExtraWidth()
  3702. - borderWidths;
  3703. setWidth(Math.max(tdWidth, 0) + "px");
  3704. }
  3705. });
  3706. }
  3707. }
  3708. }
  3709. /**
  3710. * Sets the width to undefined
  3711. */
  3712. public void setUndefinedWidth() {
  3713. definedWidth = false;
  3714. setWidth(-1, false);
  3715. }
  3716. /**
  3717. * Detects if width is fixed by developer on server side or resized to
  3718. * current width by user.
  3719. *
  3720. * @return true if defined, false if "natural" width
  3721. */
  3722. public boolean isDefinedWidth() {
  3723. return definedWidth && width >= 0;
  3724. }
  3725. /**
  3726. * Returns the pixels width of the footer cell.
  3727. *
  3728. * @return The width in pixels
  3729. */
  3730. public int getWidth() {
  3731. return width;
  3732. }
  3733. /**
  3734. * Sets the expand ratio of the cell
  3735. *
  3736. * @param floatAttribute
  3737. * The expand ratio
  3738. */
  3739. public void setExpandRatio(float floatAttribute) {
  3740. expandRatio = floatAttribute;
  3741. }
  3742. /**
  3743. * Returns the expand ratio of the cell
  3744. *
  3745. * @return The expand ratio
  3746. */
  3747. public float getExpandRatio() {
  3748. return expandRatio;
  3749. }
  3750. /**
  3751. * Is the cell enabled?
  3752. *
  3753. * @return True if enabled else False
  3754. */
  3755. public boolean isEnabled() {
  3756. return getParent() != null;
  3757. }
  3758. /**
  3759. * Handle column clicking
  3760. */
  3761. @Override
  3762. public void onBrowserEvent(Event event) {
  3763. if (enabled && event != null) {
  3764. handleCaptionEvent(event);
  3765. if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
  3766. scrollBodyPanel.setFocus(true);
  3767. }
  3768. boolean stopPropagation = true;
  3769. if (event.getTypeInt() == Event.ONCONTEXTMENU
  3770. && !client.hasEventListeners(VScrollTable.this,
  3771. TableConstants.FOOTER_CLICK_EVENT_ID)) {
  3772. // Show browser context menu if a footer click listener is
  3773. // not present
  3774. stopPropagation = false;
  3775. }
  3776. if (stopPropagation) {
  3777. event.stopPropagation();
  3778. event.preventDefault();
  3779. }
  3780. }
  3781. }
  3782. /**
  3783. * Handles a event on the captions
  3784. *
  3785. * @param event
  3786. * The event to handle
  3787. */
  3788. protected void handleCaptionEvent(Event event) {
  3789. if (event.getTypeInt() == Event.ONMOUSEUP
  3790. || event.getTypeInt() == Event.ONDBLCLICK) {
  3791. fireFooterClickedEvent(event);
  3792. }
  3793. }
  3794. /**
  3795. * Fires a footer click event after the user has clicked a column footer
  3796. * cell
  3797. *
  3798. * @param event
  3799. * The click event
  3800. */
  3801. private void fireFooterClickedEvent(Event event) {
  3802. if (client.hasEventListeners(VScrollTable.this,
  3803. TableConstants.FOOTER_CLICK_EVENT_ID)) {
  3804. MouseEventDetails details = MouseEventDetailsBuilder
  3805. .buildMouseEventDetails(event);
  3806. client.updateVariable(paintableId, "footerClickEvent",
  3807. details.toString(), false);
  3808. client.updateVariable(paintableId, "footerClickCID", cid, true);
  3809. }
  3810. }
  3811. /**
  3812. * Returns the column key of the column
  3813. *
  3814. * @return The column key
  3815. */
  3816. public String getColKey() {
  3817. return cid;
  3818. }
  3819. /**
  3820. * Saves natural column width if it hasn't been saved already.
  3821. *
  3822. * @param columnIndex
  3823. * @since 7.3.9
  3824. */
  3825. protected void saveNaturalColumnWidthIfNotSaved(int columnIndex) {
  3826. if (naturalWidth < 0) {
  3827. // This is recently revealed column. Try to detect a proper
  3828. // value (greater of header and data cols)
  3829. final int hw = ((Element) getElement().getLastChild())
  3830. .getOffsetWidth() + getHeaderPadding();
  3831. if (columnIndex < 0) {
  3832. columnIndex = 0;
  3833. for (Iterator<Widget> it = tHead.iterator(); it.hasNext(); columnIndex++) {
  3834. if (it.next() == this) {
  3835. break;
  3836. }
  3837. }
  3838. }
  3839. final int cw = scrollBody.getColWidth(columnIndex);
  3840. naturalWidth = (hw > cw ? hw : cw);
  3841. }
  3842. }
  3843. /**
  3844. * Detects the natural minimum width for the column of this header cell.
  3845. * If column is resized by user or the width is defined by server the
  3846. * actual width is returned. Else the natural min width is returned.
  3847. *
  3848. * @param columnIndex
  3849. * column index hint, if -1 (unknown) it will be detected
  3850. *
  3851. * @return
  3852. */
  3853. public int getNaturalColumnWidth(int columnIndex) {
  3854. final int iw = columnIndex == getHierarchyColumnIndex() ? scrollBody
  3855. .getMaxIndent() : 0;
  3856. saveNaturalColumnWidthIfNotSaved(columnIndex);
  3857. if (isDefinedWidth()) {
  3858. if (iw > width) {
  3859. return iw;
  3860. }
  3861. return width;
  3862. } else {
  3863. if (iw > naturalWidth) {
  3864. return iw;
  3865. } else {
  3866. return naturalWidth;
  3867. }
  3868. }
  3869. }
  3870. public void setNaturalMinimumColumnWidth(int w) {
  3871. naturalWidth = w;
  3872. }
  3873. }
  3874. /**
  3875. * HeaderCell that is header cell for row headers.
  3876. *
  3877. * Reordering disabled and clicking on it resets sorting.
  3878. */
  3879. public class RowHeadersFooterCell extends FooterCell {
  3880. RowHeadersFooterCell() {
  3881. super(ROW_HEADER_COLUMN_KEY, "");
  3882. }
  3883. @Override
  3884. protected void handleCaptionEvent(Event event) {
  3885. // NOP: RowHeaders cannot be reordered
  3886. // TODO It'd be nice to reset sorting here
  3887. }
  3888. }
  3889. /**
  3890. * The footer of the table which can be seen in the bottom of the Table.
  3891. */
  3892. public class TableFooter extends Panel {
  3893. private static final int WRAPPER_WIDTH = 900000;
  3894. ArrayList<Widget> visibleCells = new ArrayList<Widget>();
  3895. HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
  3896. Element div = DOM.createDiv();
  3897. Element hTableWrapper = DOM.createDiv();
  3898. Element hTableContainer = DOM.createDiv();
  3899. Element table = DOM.createTable();
  3900. Element headerTableBody = DOM.createTBody();
  3901. Element tr = DOM.createTR();
  3902. public TableFooter() {
  3903. hTableWrapper.getStyle().setOverflow(Overflow.HIDDEN);
  3904. DOM.appendChild(table, headerTableBody);
  3905. DOM.appendChild(headerTableBody, tr);
  3906. DOM.appendChild(hTableContainer, table);
  3907. DOM.appendChild(hTableWrapper, hTableContainer);
  3908. DOM.appendChild(div, hTableWrapper);
  3909. setElement(div);
  3910. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3911. new RowHeadersFooterCell());
  3912. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  3913. }
  3914. protected void updateStyleNames(String primaryStyleName) {
  3915. hTableWrapper.setClassName(primaryStyleName + "-footer");
  3916. setStyleName(primaryStyleName + "-footer-wrap");
  3917. for (FooterCell c : availableCells.values()) {
  3918. c.updateStyleNames(primaryStyleName);
  3919. }
  3920. }
  3921. @Override
  3922. public void clear() {
  3923. for (String cid : availableCells.keySet()) {
  3924. removeCell(cid);
  3925. }
  3926. availableCells.clear();
  3927. availableCells.put(ROW_HEADER_COLUMN_KEY,
  3928. new RowHeadersFooterCell());
  3929. }
  3930. /*
  3931. * (non-Javadoc)
  3932. *
  3933. * @see
  3934. * com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
  3935. * .ui.Widget)
  3936. */
  3937. @Override
  3938. public boolean remove(Widget w) {
  3939. if (visibleCells.contains(w)) {
  3940. visibleCells.remove(w);
  3941. orphan(w);
  3942. DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
  3943. return true;
  3944. }
  3945. return false;
  3946. }
  3947. /*
  3948. * (non-Javadoc)
  3949. *
  3950. * @see com.google.gwt.user.client.ui.HasWidgets#iterator()
  3951. */
  3952. @Override
  3953. public Iterator<Widget> iterator() {
  3954. return visibleCells.iterator();
  3955. }
  3956. /**
  3957. * Gets a footer cell which represents the given columnId
  3958. *
  3959. * @param cid
  3960. * The columnId
  3961. *
  3962. * @return The cell
  3963. */
  3964. public FooterCell getFooterCell(String cid) {
  3965. return availableCells.get(cid);
  3966. }
  3967. /**
  3968. * Gets a footer cell by using a column index
  3969. *
  3970. * @param index
  3971. * The index of the column
  3972. * @return The Cell
  3973. */
  3974. public FooterCell getFooterCell(int index) {
  3975. if (index < visibleCells.size()) {
  3976. return (FooterCell) visibleCells.get(index);
  3977. } else {
  3978. return null;
  3979. }
  3980. }
  3981. /**
  3982. * Updates the cells contents when updateUIDL request is received
  3983. *
  3984. * @param uidl
  3985. * The UIDL
  3986. */
  3987. public void updateCellsFromUIDL(UIDL uidl) {
  3988. Iterator<?> columnIterator = uidl.getChildIterator();
  3989. HashSet<String> updated = new HashSet<String>();
  3990. while (columnIterator.hasNext()) {
  3991. final UIDL col = (UIDL) columnIterator.next();
  3992. final String cid = col.getStringAttribute("cid");
  3993. updated.add(cid);
  3994. String caption = col.hasAttribute("fcaption") ? col
  3995. .getStringAttribute("fcaption") : "";
  3996. FooterCell c = getFooterCell(cid);
  3997. if (c == null) {
  3998. c = new FooterCell(cid, caption);
  3999. availableCells.put(cid, c);
  4000. if (initializedAndAttached) {
  4001. // we will need a column width recalculation
  4002. initializedAndAttached = false;
  4003. initialContentReceived = false;
  4004. isNewBody = true;
  4005. }
  4006. } else {
  4007. c.setText(caption);
  4008. }
  4009. if (col.hasAttribute("align")) {
  4010. c.setAlign(col.getStringAttribute("align").charAt(0));
  4011. } else {
  4012. c.setAlign(ALIGN_LEFT);
  4013. }
  4014. if (col.hasAttribute("width")) {
  4015. if (scrollBody == null || isNewBody) {
  4016. // Already updated by setColWidth called from
  4017. // TableHeads.updateCellsFromUIDL in case of a server
  4018. // side resize
  4019. final int width = col.getIntAttribute("width");
  4020. c.setWidth(width, true);
  4021. }
  4022. } else if (recalcWidths) {
  4023. c.setUndefinedWidth();
  4024. }
  4025. if (col.hasAttribute("er")) {
  4026. c.setExpandRatio(col.getFloatAttribute("er"));
  4027. }
  4028. if (col.hasAttribute("collapsed")) {
  4029. // ensure header is properly removed from parent (case when
  4030. // collapsing happens via servers side api)
  4031. if (c.isAttached()) {
  4032. c.removeFromParent();
  4033. headerChangedDuringUpdate = true;
  4034. }
  4035. }
  4036. }
  4037. // check for orphaned header cells
  4038. for (Iterator<String> cit = availableCells.keySet().iterator(); cit
  4039. .hasNext();) {
  4040. String cid = cit.next();
  4041. if (!updated.contains(cid)) {
  4042. removeCell(cid);
  4043. cit.remove();
  4044. }
  4045. }
  4046. }
  4047. /**
  4048. * Set a footer cell for a specified column index
  4049. *
  4050. * @param index
  4051. * The index
  4052. * @param cell
  4053. * The footer cell
  4054. */
  4055. public void setFooterCell(int index, FooterCell cell) {
  4056. if (cell.isEnabled()) {
  4057. // we're moving the cell
  4058. DOM.removeChild(tr, cell.getElement());
  4059. orphan(cell);
  4060. visibleCells.remove(cell);
  4061. }
  4062. if (index < visibleCells.size()) {
  4063. // insert to right slot
  4064. DOM.insertChild(tr, cell.getElement(), index);
  4065. adopt(cell);
  4066. visibleCells.add(index, cell);
  4067. } else if (index == visibleCells.size()) {
  4068. // simply append
  4069. DOM.appendChild(tr, cell.getElement());
  4070. adopt(cell);
  4071. visibleCells.add(cell);
  4072. } else {
  4073. throw new RuntimeException(
  4074. "Header cells must be appended in order");
  4075. }
  4076. }
  4077. /**
  4078. * Remove a cell by using the columnId
  4079. *
  4080. * @param colKey
  4081. * The columnId to remove
  4082. */
  4083. public void removeCell(String colKey) {
  4084. final FooterCell c = getFooterCell(colKey);
  4085. remove(c);
  4086. }
  4087. /**
  4088. * Enable a column (Sets the footer cell)
  4089. *
  4090. * @param cid
  4091. * The columnId
  4092. * @param index
  4093. * The index of the column
  4094. */
  4095. public void enableColumn(String cid, int index) {
  4096. final FooterCell c = getFooterCell(cid);
  4097. if (!c.isEnabled() || getFooterCell(index) != c) {
  4098. setFooterCell(index, c);
  4099. if (initializedAndAttached) {
  4100. headerChangedDuringUpdate = true;
  4101. }
  4102. }
  4103. }
  4104. /**
  4105. * Disable browser measurement of the table width
  4106. */
  4107. public void disableBrowserIntelligence() {
  4108. hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
  4109. }
  4110. /**
  4111. * Enable browser measurement of the table width
  4112. */
  4113. public void enableBrowserIntelligence() {
  4114. hTableContainer.getStyle().clearWidth();
  4115. }
  4116. /**
  4117. * Set the horizontal position in the cell in the footer. This is done
  4118. * when a horizontal scrollbar is present.
  4119. *
  4120. * @param scrollLeft
  4121. * The value of the leftScroll
  4122. */
  4123. public void setHorizontalScrollPosition(int scrollLeft) {
  4124. hTableWrapper.setScrollLeft(scrollLeft);
  4125. }
  4126. /**
  4127. * Swap cells when the column are dragged
  4128. *
  4129. * @param oldIndex
  4130. * The old index of the cell
  4131. * @param newIndex
  4132. * The new index of the cell
  4133. */
  4134. public void moveCell(int oldIndex, int newIndex) {
  4135. final FooterCell hCell = getFooterCell(oldIndex);
  4136. final Element cell = hCell.getElement();
  4137. visibleCells.remove(oldIndex);
  4138. DOM.removeChild(tr, cell);
  4139. DOM.insertChild(tr, cell, newIndex);
  4140. visibleCells.add(newIndex, hCell);
  4141. }
  4142. }
  4143. /**
  4144. * This Panel can only contain VScrollTableRow type of widgets. This
  4145. * "simulates" very large table, keeping spacers which take room of
  4146. * unrendered rows.
  4147. *
  4148. */
  4149. public class VScrollTableBody extends Panel {
  4150. public static final int DEFAULT_ROW_HEIGHT = 24;
  4151. private double rowHeight = -1;
  4152. private final LinkedList<Widget> renderedRows = new LinkedList<Widget>();
  4153. /**
  4154. * Due some optimizations row height measuring is deferred and initial
  4155. * set of rows is rendered detached. Flag set on when table body has
  4156. * been attached in dom and rowheight has been measured.
  4157. */
  4158. private boolean tBodyMeasurementsDone = false;
  4159. Element preSpacer = DOM.createDiv();
  4160. Element postSpacer = DOM.createDiv();
  4161. Element container = DOM.createDiv();
  4162. TableSectionElement tBodyElement = Document.get().createTBodyElement();
  4163. Element table = DOM.createTable();
  4164. private int firstRendered;
  4165. private int lastRendered;
  4166. private char[] aligns;
  4167. protected VScrollTableBody() {
  4168. constructDOM();
  4169. setElement(container);
  4170. }
  4171. public void setLastRendered(int lastRendered) {
  4172. if (totalRows >= 0 && lastRendered > totalRows) {
  4173. VConsole.log("setLastRendered: " + this.lastRendered + " -> "
  4174. + lastRendered);
  4175. this.lastRendered = totalRows - 1;
  4176. } else {
  4177. this.lastRendered = lastRendered;
  4178. }
  4179. }
  4180. public int getLastRendered() {
  4181. return lastRendered;
  4182. }
  4183. public int getFirstRendered() {
  4184. return firstRendered;
  4185. }
  4186. public VScrollTableRow getRowByRowIndex(int indexInTable) {
  4187. int internalIndex = indexInTable - firstRendered;
  4188. if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
  4189. return (VScrollTableRow) renderedRows.get(internalIndex);
  4190. } else {
  4191. return null;
  4192. }
  4193. }
  4194. /**
  4195. * @return the height of scrollable body, subpixels ceiled.
  4196. */
  4197. public int getRequiredHeight() {
  4198. return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
  4199. + WidgetUtil.getRequiredHeight(table);
  4200. }
  4201. private void constructDOM() {
  4202. if (BrowserInfo.get().isIE()) {
  4203. table.setPropertyInt("cellSpacing", 0);
  4204. }
  4205. table.appendChild(tBodyElement);
  4206. DOM.appendChild(container, preSpacer);
  4207. DOM.appendChild(container, table);
  4208. DOM.appendChild(container, postSpacer);
  4209. if (BrowserInfo.get().requiresTouchScrollDelegate()) {
  4210. NodeList<Node> childNodes = container.getChildNodes();
  4211. for (int i = 0; i < childNodes.getLength(); i++) {
  4212. Element item = (Element) childNodes.getItem(i);
  4213. item.getStyle().setProperty("webkitTransform",
  4214. "translate3d(0,0,0)");
  4215. }
  4216. }
  4217. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  4218. }
  4219. protected void updateStyleNames(String primaryStyleName) {
  4220. table.setClassName(primaryStyleName + "-table");
  4221. preSpacer.setClassName(primaryStyleName + "-row-spacer");
  4222. postSpacer.setClassName(primaryStyleName + "-row-spacer");
  4223. for (Widget w : renderedRows) {
  4224. VScrollTableRow row = (VScrollTableRow) w;
  4225. row.updateStyleNames(primaryStyleName);
  4226. }
  4227. }
  4228. public int getAvailableWidth() {
  4229. int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
  4230. return availW;
  4231. }
  4232. public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
  4233. firstRendered = firstIndex;
  4234. setLastRendered(firstIndex + rows - 1);
  4235. final Iterator<?> it = rowData.getChildIterator();
  4236. aligns = tHead.getColumnAlignments();
  4237. while (it.hasNext()) {
  4238. final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
  4239. addRow(row);
  4240. }
  4241. if (isAttached()) {
  4242. fixSpacers();
  4243. }
  4244. }
  4245. public void renderRows(UIDL rowData, int firstIndex, int rows) {
  4246. // FIXME REVIEW
  4247. aligns = tHead.getColumnAlignments();
  4248. final Iterator<?> it = rowData.getChildIterator();
  4249. if (firstIndex == lastRendered + 1) {
  4250. while (it.hasNext()) {
  4251. final VScrollTableRow row = prepareRow((UIDL) it.next());
  4252. addRow(row);
  4253. setLastRendered(lastRendered + 1);
  4254. }
  4255. fixSpacers();
  4256. } else if (firstIndex + rows == firstRendered) {
  4257. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  4258. int i = rows;
  4259. while (it.hasNext()) {
  4260. i--;
  4261. rowArray[i] = prepareRow((UIDL) it.next());
  4262. }
  4263. for (i = 0; i < rows; i++) {
  4264. addRowBeforeFirstRendered(rowArray[i]);
  4265. firstRendered--;
  4266. }
  4267. } else {
  4268. // completely new set of rows
  4269. // there can't be sanity checks for last rendered within this
  4270. // while loop regardless of what has been set previously, so
  4271. // change it temporarily to true and then return the original
  4272. // value
  4273. boolean temp = postponeSanityCheckForLastRendered;
  4274. postponeSanityCheckForLastRendered = true;
  4275. while (lastRendered + 1 > firstRendered) {
  4276. unlinkRow(false);
  4277. }
  4278. postponeSanityCheckForLastRendered = temp;
  4279. VScrollTableRow row = prepareRow((UIDL) it.next());
  4280. firstRendered = firstIndex;
  4281. setLastRendered(firstIndex - 1);
  4282. addRow(row);
  4283. setLastRendered(lastRendered + 1);
  4284. setContainerHeight();
  4285. fixSpacers();
  4286. while (it.hasNext()) {
  4287. addRow(prepareRow((UIDL) it.next()));
  4288. setLastRendered(lastRendered + 1);
  4289. }
  4290. fixSpacers();
  4291. }
  4292. // this may be a new set of rows due content change,
  4293. // ensure we have proper cache rows
  4294. ensureCacheFilled();
  4295. }
  4296. /**
  4297. * Ensure we have the correct set of rows on client side, e.g. if the
  4298. * content on the server side has changed, or the client scroll position
  4299. * has changed since the last request.
  4300. */
  4301. protected void ensureCacheFilled() {
  4302. /**
  4303. * Fixes cache issue #13576 where unnecessary rows are fetched
  4304. */
  4305. if (isLazyScrollerActive()) {
  4306. return;
  4307. }
  4308. int reactFirstRow = (int) (firstRowInViewPort - pageLength
  4309. * cache_react_rate);
  4310. int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
  4311. * cache_react_rate);
  4312. if (reactFirstRow < 0) {
  4313. reactFirstRow = 0;
  4314. }
  4315. if (reactLastRow >= totalRows) {
  4316. reactLastRow = totalRows - 1;
  4317. }
  4318. if (lastRendered < reactFirstRow || firstRendered > reactLastRow) {
  4319. /*
  4320. * #8040 - scroll position is completely changed since the
  4321. * latest request, so request a new set of rows.
  4322. *
  4323. * TODO: We should probably check whether the fetched rows match
  4324. * the current scroll position right when they arrive, so as to
  4325. * not waste time rendering a set of rows that will never be
  4326. * visible...
  4327. */
  4328. rowRequestHandler.triggerRowFetch(reactFirstRow, reactLastRow
  4329. - reactFirstRow + 1, 1);
  4330. } else if (lastRendered < reactLastRow) {
  4331. // get some cache rows below visible area
  4332. rowRequestHandler.triggerRowFetch(lastRendered + 1,
  4333. reactLastRow - lastRendered, 1);
  4334. } else if (firstRendered > reactFirstRow) {
  4335. /*
  4336. * Branch for fetching cache above visible area.
  4337. *
  4338. * If cache needed for both before and after visible area, this
  4339. * will be rendered after-cache is received and rendered. So in
  4340. * some rare situations the table may make two cache visits to
  4341. * server.
  4342. */
  4343. rowRequestHandler.triggerRowFetch(reactFirstRow, firstRendered
  4344. - reactFirstRow, 1);
  4345. }
  4346. }
  4347. /**
  4348. * Inserts rows as provided in the rowData starting at firstIndex.
  4349. *
  4350. * @param rowData
  4351. * @param firstIndex
  4352. * @param rows
  4353. * the number of rows
  4354. * @return a list of the rows added.
  4355. */
  4356. protected List<VScrollTableRow> insertRows(UIDL rowData,
  4357. int firstIndex, int rows) {
  4358. aligns = tHead.getColumnAlignments();
  4359. final Iterator<?> it = rowData.getChildIterator();
  4360. List<VScrollTableRow> insertedRows = new ArrayList<VScrollTableRow>();
  4361. if (firstIndex == lastRendered + 1) {
  4362. while (it.hasNext()) {
  4363. final VScrollTableRow row = prepareRow((UIDL) it.next());
  4364. addRow(row);
  4365. insertedRows.add(row);
  4366. if (postponeSanityCheckForLastRendered) {
  4367. lastRendered++;
  4368. } else {
  4369. setLastRendered(lastRendered + 1);
  4370. }
  4371. }
  4372. fixSpacers();
  4373. } else if (firstIndex + rows == firstRendered) {
  4374. final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
  4375. int i = rows;
  4376. while (it.hasNext()) {
  4377. i--;
  4378. rowArray[i] = prepareRow((UIDL) it.next());
  4379. }
  4380. for (i = 0; i < rows; i++) {
  4381. addRowBeforeFirstRendered(rowArray[i]);
  4382. insertedRows.add(rowArray[i]);
  4383. firstRendered--;
  4384. }
  4385. } else {
  4386. // insert in the middle
  4387. int ix = firstIndex;
  4388. while (it.hasNext()) {
  4389. VScrollTableRow row = prepareRow((UIDL) it.next());
  4390. insertRowAt(row, ix);
  4391. insertedRows.add(row);
  4392. if (postponeSanityCheckForLastRendered) {
  4393. lastRendered++;
  4394. } else {
  4395. setLastRendered(lastRendered + 1);
  4396. }
  4397. ix++;
  4398. }
  4399. fixSpacers();
  4400. }
  4401. return insertedRows;
  4402. }
  4403. protected List<VScrollTableRow> insertAndReindexRows(UIDL rowData,
  4404. int firstIndex, int rows) {
  4405. List<VScrollTableRow> inserted = insertRows(rowData, firstIndex,
  4406. rows);
  4407. int actualIxOfFirstRowAfterInserted = firstIndex + rows
  4408. - firstRendered;
  4409. for (int ix = actualIxOfFirstRowAfterInserted; ix < renderedRows
  4410. .size(); ix++) {
  4411. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  4412. r.setIndex(r.getIndex() + rows);
  4413. }
  4414. setContainerHeight();
  4415. return inserted;
  4416. }
  4417. protected void insertRowsDeleteBelow(UIDL rowData, int firstIndex,
  4418. int rows) {
  4419. unlinkAllRowsStartingAt(firstIndex);
  4420. insertRows(rowData, firstIndex, rows);
  4421. setContainerHeight();
  4422. }
  4423. /**
  4424. * This method is used to instantiate new rows for this table. It
  4425. * automatically sets correct widths to rows cells and assigns correct
  4426. * client reference for child widgets.
  4427. *
  4428. * This method can be called only after table has been initialized
  4429. *
  4430. * @param uidl
  4431. */
  4432. private VScrollTableRow prepareRow(UIDL uidl) {
  4433. final VScrollTableRow row = createRow(uidl, aligns);
  4434. row.initCellWidths();
  4435. return row;
  4436. }
  4437. protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
  4438. if (uidl.hasAttribute("gen_html")) {
  4439. // This is a generated row.
  4440. return new VScrollTableGeneratedRow(uidl, aligns2);
  4441. }
  4442. return new VScrollTableRow(uidl, aligns2);
  4443. }
  4444. private void addRowBeforeFirstRendered(VScrollTableRow row) {
  4445. row.setIndex(firstRendered - 1);
  4446. if (row.isSelected()) {
  4447. row.addStyleName("v-selected");
  4448. }
  4449. tBodyElement.insertBefore(row.getElement(),
  4450. tBodyElement.getFirstChild());
  4451. adopt(row);
  4452. renderedRows.add(0, row);
  4453. }
  4454. private void addRow(VScrollTableRow row) {
  4455. row.setIndex(firstRendered + renderedRows.size());
  4456. if (row.isSelected()) {
  4457. row.addStyleName("v-selected");
  4458. }
  4459. tBodyElement.appendChild(row.getElement());
  4460. // Add to renderedRows before adopt so iterator() will return also
  4461. // this row if called in an attach handler (#9264)
  4462. renderedRows.add(row);
  4463. adopt(row);
  4464. }
  4465. private void insertRowAt(VScrollTableRow row, int index) {
  4466. row.setIndex(index);
  4467. if (row.isSelected()) {
  4468. row.addStyleName("v-selected");
  4469. }
  4470. if (index > 0) {
  4471. VScrollTableRow sibling = getRowByRowIndex(index - 1);
  4472. tBodyElement
  4473. .insertAfter(row.getElement(), sibling.getElement());
  4474. } else {
  4475. VScrollTableRow sibling = getRowByRowIndex(index);
  4476. tBodyElement.insertBefore(row.getElement(),
  4477. sibling.getElement());
  4478. }
  4479. adopt(row);
  4480. int actualIx = index - firstRendered;
  4481. renderedRows.add(actualIx, row);
  4482. }
  4483. @Override
  4484. public Iterator<Widget> iterator() {
  4485. return renderedRows.iterator();
  4486. }
  4487. /**
  4488. * @return false if couldn't remove row
  4489. */
  4490. protected boolean unlinkRow(boolean fromBeginning) {
  4491. if (lastRendered - firstRendered < 0) {
  4492. return false;
  4493. }
  4494. int actualIx;
  4495. if (fromBeginning) {
  4496. actualIx = 0;
  4497. firstRendered++;
  4498. } else {
  4499. actualIx = renderedRows.size() - 1;
  4500. if (postponeSanityCheckForLastRendered) {
  4501. --lastRendered;
  4502. } else {
  4503. setLastRendered(lastRendered - 1);
  4504. }
  4505. }
  4506. if (actualIx >= 0) {
  4507. unlinkRowAtActualIndex(actualIx);
  4508. fixSpacers();
  4509. return true;
  4510. }
  4511. return false;
  4512. }
  4513. protected void unlinkRows(int firstIndex, int count) {
  4514. if (count < 1) {
  4515. return;
  4516. }
  4517. if (firstRendered > firstIndex
  4518. && firstRendered < firstIndex + count) {
  4519. count = count - (firstRendered - firstIndex);
  4520. firstIndex = firstRendered;
  4521. }
  4522. int lastIndex = firstIndex + count - 1;
  4523. if (lastRendered < lastIndex) {
  4524. lastIndex = lastRendered;
  4525. }
  4526. for (int ix = lastIndex; ix >= firstIndex; ix--) {
  4527. unlinkRowAtActualIndex(actualIndex(ix));
  4528. if (postponeSanityCheckForLastRendered) {
  4529. // partialUpdate handles sanity check later
  4530. lastRendered--;
  4531. } else {
  4532. setLastRendered(lastRendered - 1);
  4533. }
  4534. }
  4535. fixSpacers();
  4536. }
  4537. protected void unlinkAndReindexRows(int firstIndex, int count) {
  4538. unlinkRows(firstIndex, count);
  4539. int actualFirstIx = firstIndex - firstRendered;
  4540. for (int ix = actualFirstIx; ix < renderedRows.size(); ix++) {
  4541. VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
  4542. r.setIndex(r.getIndex() - count);
  4543. }
  4544. setContainerHeight();
  4545. }
  4546. protected void unlinkAllRowsStartingAt(int index) {
  4547. if (firstRendered > index) {
  4548. index = firstRendered;
  4549. }
  4550. for (int ix = renderedRows.size() - 1; ix >= index; ix--) {
  4551. unlinkRowAtActualIndex(actualIndex(ix));
  4552. setLastRendered(lastRendered - 1);
  4553. }
  4554. fixSpacers();
  4555. }
  4556. private int actualIndex(int index) {
  4557. return index - firstRendered;
  4558. }
  4559. private void unlinkRowAtActualIndex(int index) {
  4560. final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
  4561. .get(index);
  4562. tBodyElement.removeChild(toBeRemoved.getElement());
  4563. orphan(toBeRemoved);
  4564. renderedRows.remove(index);
  4565. }
  4566. @Override
  4567. public boolean remove(Widget w) {
  4568. throw new UnsupportedOperationException();
  4569. }
  4570. /**
  4571. * Fix container blocks height according to totalRows to avoid
  4572. * "bouncing" when scrolling
  4573. */
  4574. private void setContainerHeight() {
  4575. fixSpacers();
  4576. container.getStyle().setHeight(measureRowHeightOffset(totalRows),
  4577. Unit.PX);
  4578. }
  4579. private void fixSpacers() {
  4580. int prepx = measureRowHeightOffset(firstRendered);
  4581. if (prepx < 0) {
  4582. prepx = 0;
  4583. }
  4584. preSpacer.getStyle().setPropertyPx("height", prepx);
  4585. int postpx;
  4586. if (pageLength == 0 && totalRows == pageLength) {
  4587. /*
  4588. * TreeTable depends on having lastRendered out of sync in some
  4589. * situations, which makes this method miss the special
  4590. * situation in which one row worth of post spacer to be added
  4591. * if there are no rows in the table. #9203
  4592. */
  4593. postpx = measureRowHeightOffset(1);
  4594. } else {
  4595. postpx = measureRowHeightOffset(totalRows - 1)
  4596. - measureRowHeightOffset(lastRendered);
  4597. }
  4598. if (postpx < 0) {
  4599. postpx = 0;
  4600. }
  4601. postSpacer.getStyle().setPropertyPx("height", postpx);
  4602. }
  4603. public double getRowHeight() {
  4604. return getRowHeight(false);
  4605. }
  4606. public double getRowHeight(boolean forceUpdate) {
  4607. if (tBodyMeasurementsDone && !forceUpdate) {
  4608. return rowHeight;
  4609. } else {
  4610. if (tBodyElement.getRows().getLength() > 0) {
  4611. int tableHeight = getTableHeight();
  4612. int rowCount = tBodyElement.getRows().getLength();
  4613. rowHeight = tableHeight / (double) rowCount;
  4614. } else {
  4615. // Special cases if we can't just measure the current rows
  4616. if (!Double.isNaN(lastKnownRowHeight)) {
  4617. // Use previous value if available
  4618. if (BrowserInfo.get().isIE()) {
  4619. /*
  4620. * IE needs to reflow the table element at this
  4621. * point to work correctly (e.g.
  4622. * com.vaadin.tests.components.table.
  4623. * ContainerSizeChange) - the other code paths
  4624. * already trigger reflows, but here it must be done
  4625. * explicitly.
  4626. */
  4627. getTableHeight();
  4628. }
  4629. rowHeight = lastKnownRowHeight;
  4630. } else if (isAttached()) {
  4631. // measure row height by adding a dummy row
  4632. VScrollTableRow scrollTableRow = new VScrollTableRow();
  4633. tBodyElement.appendChild(scrollTableRow.getElement());
  4634. getRowHeight(forceUpdate);
  4635. tBodyElement.removeChild(scrollTableRow.getElement());
  4636. } else {
  4637. // TODO investigate if this can never happen anymore
  4638. return DEFAULT_ROW_HEIGHT;
  4639. }
  4640. }
  4641. lastKnownRowHeight = rowHeight;
  4642. tBodyMeasurementsDone = true;
  4643. return rowHeight;
  4644. }
  4645. }
  4646. public int getTableHeight() {
  4647. return table.getOffsetHeight();
  4648. }
  4649. /**
  4650. * Returns the width available for column content.
  4651. *
  4652. * @param columnIndex
  4653. * @return
  4654. */
  4655. public int getColWidth(int columnIndex) {
  4656. if (tBodyMeasurementsDone) {
  4657. if (renderedRows.isEmpty()) {
  4658. // no rows yet rendered
  4659. return 0;
  4660. }
  4661. for (Widget row : renderedRows) {
  4662. if (!(row instanceof VScrollTableGeneratedRow)) {
  4663. TableRowElement tr = row.getElement().cast();
  4664. Element wrapperdiv = tr.getCells().getItem(columnIndex)
  4665. .getFirstChildElement().cast();
  4666. return wrapperdiv.getOffsetWidth();
  4667. }
  4668. }
  4669. return 0;
  4670. } else {
  4671. return 0;
  4672. }
  4673. }
  4674. /**
  4675. * Sets the content width of a column.
  4676. *
  4677. * Due IE limitation, we must set the width to a wrapper elements inside
  4678. * table cells (with overflow hidden, which does not work on td
  4679. * elements).
  4680. *
  4681. * To get this work properly crossplatform, we will also set the width
  4682. * of td.
  4683. *
  4684. * @param colIndex
  4685. * @param w
  4686. */
  4687. public void setColWidth(int colIndex, int w) {
  4688. for (Widget row : renderedRows) {
  4689. ((VScrollTableRow) row).setCellWidth(colIndex, w);
  4690. }
  4691. }
  4692. private int cellExtraWidth = -1;
  4693. /**
  4694. * Method to return the space used for cell paddings + border.
  4695. */
  4696. private int getCellExtraWidth() {
  4697. if (cellExtraWidth < 0) {
  4698. detectExtrawidth();
  4699. }
  4700. return cellExtraWidth;
  4701. }
  4702. /**
  4703. * This method exists for the needs of {@link VTreeTable} only. May be
  4704. * removed or replaced in the future.</br> </br> Returns the maximum
  4705. * indent of the hierarcyColumn, if applicable.
  4706. *
  4707. * @see {@link VScrollTable#getHierarchyColumnIndex()}
  4708. *
  4709. * @return maximum indent in pixels
  4710. */
  4711. protected int getMaxIndent() {
  4712. return 0;
  4713. }
  4714. /**
  4715. * This method exists for the needs of {@link VTreeTable} only. May be
  4716. * removed or replaced in the future.</br> </br> Calculates the maximum
  4717. * indent of the hierarcyColumn, if applicable.
  4718. */
  4719. protected void calculateMaxIndent() {
  4720. // NOP
  4721. }
  4722. private void detectExtrawidth() {
  4723. NodeList<TableRowElement> rows = tBodyElement.getRows();
  4724. if (rows.getLength() == 0) {
  4725. /* need to temporary add empty row and detect */
  4726. VScrollTableRow scrollTableRow = new VScrollTableRow();
  4727. scrollTableRow.updateStyleNames(VScrollTable.this
  4728. .getStylePrimaryName());
  4729. tBodyElement.appendChild(scrollTableRow.getElement());
  4730. detectExtrawidth();
  4731. tBodyElement.removeChild(scrollTableRow.getElement());
  4732. } else {
  4733. boolean noCells = false;
  4734. TableRowElement item = rows.getItem(0);
  4735. TableCellElement firstTD = item.getCells().getItem(0);
  4736. if (firstTD == null) {
  4737. // content is currently empty, we need to add a fake cell
  4738. // for measuring
  4739. noCells = true;
  4740. VScrollTableRow next = (VScrollTableRow) iterator().next();
  4741. boolean sorted = tHead.getHeaderCell(0) != null ? tHead
  4742. .getHeaderCell(0).isSorted() : false;
  4743. next.addCell(null, "", ALIGN_LEFT, "", true, sorted);
  4744. firstTD = item.getCells().getItem(0);
  4745. }
  4746. com.google.gwt.dom.client.Element wrapper = firstTD
  4747. .getFirstChildElement();
  4748. cellExtraWidth = firstTD.getOffsetWidth()
  4749. - wrapper.getOffsetWidth();
  4750. if (noCells) {
  4751. firstTD.getParentElement().removeChild(firstTD);
  4752. }
  4753. }
  4754. }
  4755. public void moveCol(int oldIndex, int newIndex) {
  4756. // loop all rows and move given index to its new place
  4757. final Iterator<?> rows = iterator();
  4758. while (rows.hasNext()) {
  4759. final VScrollTableRow row = (VScrollTableRow) rows.next();
  4760. final Element td = DOM.getChild(row.getElement(), oldIndex);
  4761. if (td != null) {
  4762. DOM.removeChild(row.getElement(), td);
  4763. DOM.insertChild(row.getElement(), td, newIndex);
  4764. }
  4765. }
  4766. }
  4767. /**
  4768. * Restore row visibility which is set to "none" when the row is
  4769. * rendered (due a performance optimization).
  4770. */
  4771. private void restoreRowVisibility() {
  4772. for (Widget row : renderedRows) {
  4773. row.getElement().getStyle().setProperty("visibility", "");
  4774. }
  4775. }
  4776. public int indexOf(Widget row) {
  4777. int relIx = -1;
  4778. for (int ix = 0; ix < renderedRows.size(); ix++) {
  4779. if (renderedRows.get(ix) == row) {
  4780. relIx = ix;
  4781. break;
  4782. }
  4783. }
  4784. if (relIx >= 0) {
  4785. return firstRendered + relIx;
  4786. }
  4787. return -1;
  4788. }
  4789. public class VScrollTableRow extends Panel implements ActionOwner,
  4790. ContextMenuOwner {
  4791. private static final int TOUCHSCROLL_TIMEOUT = 100;
  4792. private static final int DRAGMODE_MULTIROW = 2;
  4793. protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
  4794. private boolean selected = false;
  4795. protected final int rowKey;
  4796. private String[] actionKeys = null;
  4797. private final TableRowElement rowElement;
  4798. private int index;
  4799. private Event touchStart;
  4800. private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
  4801. private Timer contextTouchTimeout;
  4802. private Timer dragTouchTimeout;
  4803. private int touchStartY;
  4804. private int touchStartX;
  4805. private TouchContextProvider touchContextProvider = new TouchContextProvider(
  4806. this);
  4807. private TooltipInfo tooltipInfo = null;
  4808. private Map<TableCellElement, TooltipInfo> cellToolTips = new HashMap<TableCellElement, TooltipInfo>();
  4809. private boolean isDragging = false;
  4810. private String rowStyle = null;
  4811. protected boolean applyZeroWidthFix = true;
  4812. private VScrollTableRow(int rowKey) {
  4813. this.rowKey = rowKey;
  4814. rowElement = Document.get().createTRElement();
  4815. setElement(rowElement);
  4816. DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
  4817. | Event.TOUCHEVENTS | Event.ONDBLCLICK
  4818. | Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS);
  4819. }
  4820. public VScrollTableRow(UIDL uidl, char[] aligns) {
  4821. this(uidl.getIntAttribute("key"));
  4822. /*
  4823. * Rendering the rows as hidden improves Firefox and Safari
  4824. * performance drastically.
  4825. */
  4826. getElement().getStyle().setProperty("visibility", "hidden");
  4827. rowStyle = uidl.getStringAttribute("rowstyle");
  4828. updateStyleNames(VScrollTable.this.getStylePrimaryName());
  4829. String rowDescription = uidl.getStringAttribute("rowdescr");
  4830. if (rowDescription != null && !rowDescription.equals("")) {
  4831. tooltipInfo = new TooltipInfo(rowDescription, null, this);
  4832. } else {
  4833. tooltipInfo = null;
  4834. }
  4835. tHead.getColumnAlignments();
  4836. int col = 0;
  4837. int visibleColumnIndex = -1;
  4838. // row header
  4839. if (showRowHeaders) {
  4840. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4841. addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
  4842. "rowheader", true, sorted);
  4843. visibleColumnIndex++;
  4844. }
  4845. if (uidl.hasAttribute("al")) {
  4846. actionKeys = uidl.getStringArrayAttribute("al");
  4847. }
  4848. addCellsFromUIDL(uidl, aligns, col, visibleColumnIndex);
  4849. if (uidl.hasAttribute("selected") && !isSelected()) {
  4850. toggleSelection();
  4851. }
  4852. }
  4853. protected void updateStyleNames(String primaryStyleName) {
  4854. if (getStylePrimaryName().contains("odd")) {
  4855. setStyleName(primaryStyleName + "-row-odd");
  4856. } else {
  4857. setStyleName(primaryStyleName + "-row");
  4858. }
  4859. if (rowStyle != null) {
  4860. addStyleName(primaryStyleName + "-row-" + rowStyle);
  4861. }
  4862. for (int i = 0; i < rowElement.getChildCount(); i++) {
  4863. TableCellElement cell = (TableCellElement) rowElement
  4864. .getChild(i);
  4865. updateCellStyleNames(cell, primaryStyleName);
  4866. }
  4867. }
  4868. public TooltipInfo getTooltipInfo() {
  4869. return tooltipInfo;
  4870. }
  4871. /**
  4872. * Add a dummy row, used for measurements if Table is empty.
  4873. */
  4874. public VScrollTableRow() {
  4875. this(0);
  4876. addCell(null, "_", 'b', "", true, false);
  4877. }
  4878. protected void initCellWidths() {
  4879. final int cells = tHead.getVisibleCellCount();
  4880. for (int i = 0; i < cells; i++) {
  4881. int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
  4882. if (w < 0) {
  4883. w = 0;
  4884. }
  4885. setCellWidth(i, w);
  4886. }
  4887. }
  4888. protected void setCellWidth(int cellIx, int width) {
  4889. final Element cell = DOM.getChild(getElement(), cellIx);
  4890. Style wrapperStyle = cell.getFirstChildElement().getStyle();
  4891. int wrapperWidth = width;
  4892. if (BrowserInfo.get().isWebkit()
  4893. || BrowserInfo.get().isOpera10()) {
  4894. /*
  4895. * Some versions of Webkit and Opera ignore the width
  4896. * definition of zero width table cells. Instead, use 1px
  4897. * and compensate with a negative margin.
  4898. */
  4899. if (applyZeroWidthFix && width == 0) {
  4900. wrapperWidth = 1;
  4901. wrapperStyle.setMarginRight(-1, Unit.PX);
  4902. } else {
  4903. wrapperStyle.clearMarginRight();
  4904. }
  4905. }
  4906. wrapperStyle.setPropertyPx("width", wrapperWidth);
  4907. cell.getStyle().setPropertyPx("width", width);
  4908. }
  4909. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  4910. int visibleColumnIndex) {
  4911. final Iterator<?> cells = uidl.getChildIterator();
  4912. while (cells.hasNext()) {
  4913. final Object cell = cells.next();
  4914. visibleColumnIndex++;
  4915. String columnId = visibleColOrder[visibleColumnIndex];
  4916. String style = "";
  4917. if (uidl.hasAttribute("style-" + columnId)) {
  4918. style = uidl.getStringAttribute("style-" + columnId);
  4919. }
  4920. String description = null;
  4921. if (uidl.hasAttribute("descr-" + columnId)) {
  4922. description = uidl.getStringAttribute("descr-"
  4923. + columnId);
  4924. }
  4925. boolean sorted = tHead.getHeaderCell(col).isSorted();
  4926. if (cell instanceof String) {
  4927. addCell(uidl, cell.toString(), aligns[col++], style,
  4928. isRenderHtmlInCells(), sorted, description);
  4929. } else {
  4930. final ComponentConnector cellContent = client
  4931. .getPaintable((UIDL) cell);
  4932. addCell(uidl, cellContent.getWidget(), aligns[col++],
  4933. style, sorted, description);
  4934. }
  4935. }
  4936. }
  4937. /**
  4938. * Overriding this and returning true causes all text cells to be
  4939. * rendered as HTML.
  4940. *
  4941. * @return always returns false in the default implementation
  4942. */
  4943. protected boolean isRenderHtmlInCells() {
  4944. return false;
  4945. }
  4946. /**
  4947. * Detects whether row is visible in tables viewport.
  4948. *
  4949. * @return
  4950. */
  4951. public boolean isInViewPort() {
  4952. int absoluteTop = getAbsoluteTop();
  4953. int absoluteBottom = absoluteTop + getOffsetHeight();
  4954. int viewPortTop = scrollBodyPanel.getAbsoluteTop();
  4955. int viewPortBottom = viewPortTop
  4956. + scrollBodyPanel.getOffsetHeight();
  4957. return absoluteBottom > viewPortTop
  4958. && absoluteTop < viewPortBottom;
  4959. }
  4960. /**
  4961. * Makes a check based on indexes whether the row is before the
  4962. * compared row.
  4963. *
  4964. * @param row1
  4965. * @return true if this rows index is smaller than in the row1
  4966. */
  4967. public boolean isBefore(VScrollTableRow row1) {
  4968. return getIndex() < row1.getIndex();
  4969. }
  4970. /**
  4971. * Sets the index of the row in the whole table. Currently used just
  4972. * to set even/odd classname
  4973. *
  4974. * @param indexInWholeTable
  4975. */
  4976. private void setIndex(int indexInWholeTable) {
  4977. index = indexInWholeTable;
  4978. boolean isOdd = indexInWholeTable % 2 == 0;
  4979. // Inverted logic to be backwards compatible with earlier 6.4.
  4980. // It is very strange because rows 1,3,5 are considered "even"
  4981. // and 2,4,6 "odd".
  4982. //
  4983. // First remove any old styles so that both styles aren't
  4984. // applied when indexes are updated.
  4985. String primaryStyleName = getStylePrimaryName();
  4986. if (primaryStyleName != null && !primaryStyleName.equals("")) {
  4987. removeStyleName(getStylePrimaryName());
  4988. }
  4989. if (!isOdd) {
  4990. addStyleName(VScrollTable.this.getStylePrimaryName()
  4991. + "-row-odd");
  4992. } else {
  4993. addStyleName(VScrollTable.this.getStylePrimaryName()
  4994. + "-row");
  4995. }
  4996. }
  4997. public int getIndex() {
  4998. return index;
  4999. }
  5000. @Override
  5001. protected void onDetach() {
  5002. super.onDetach();
  5003. client.getContextMenu().ensureHidden(this);
  5004. }
  5005. public String getKey() {
  5006. return String.valueOf(rowKey);
  5007. }
  5008. public void addCell(UIDL rowUidl, String text, char align,
  5009. String style, boolean textIsHTML, boolean sorted) {
  5010. addCell(rowUidl, text, align, style, textIsHTML, sorted, null);
  5011. }
  5012. public void addCell(UIDL rowUidl, String text, char align,
  5013. String style, boolean textIsHTML, boolean sorted,
  5014. String description) {
  5015. // String only content is optimized by not using Label widget
  5016. final TableCellElement td = DOM.createTD().cast();
  5017. initCellWithText(text, align, style, textIsHTML, sorted,
  5018. description, td);
  5019. }
  5020. protected void initCellWithText(String text, char align,
  5021. String style, boolean textIsHTML, boolean sorted,
  5022. String description, final TableCellElement td) {
  5023. final Element container = DOM.createDiv();
  5024. container.setClassName(VScrollTable.this.getStylePrimaryName()
  5025. + "-cell-wrapper");
  5026. td.setClassName(VScrollTable.this.getStylePrimaryName()
  5027. + "-cell-content");
  5028. if (style != null && !style.equals("")) {
  5029. td.addClassName(VScrollTable.this.getStylePrimaryName()
  5030. + "-cell-content-" + style);
  5031. }
  5032. if (sorted) {
  5033. td.addClassName(VScrollTable.this.getStylePrimaryName()
  5034. + "-cell-content-sorted");
  5035. }
  5036. if (textIsHTML) {
  5037. container.setInnerHTML(text);
  5038. } else {
  5039. container.setInnerText(text);
  5040. }
  5041. setAlign(align, container);
  5042. setTooltip(td, description);
  5043. td.appendChild(container);
  5044. getElement().appendChild(td);
  5045. }
  5046. protected void updateCellStyleNames(TableCellElement td,
  5047. String primaryStyleName) {
  5048. Element container = td.getFirstChild().cast();
  5049. container.setClassName(primaryStyleName + "-cell-wrapper");
  5050. /*
  5051. * Replace old primary style name with new one
  5052. */
  5053. String className = td.getClassName();
  5054. String oldPrimaryName = className.split("-cell-content")[0];
  5055. td.setClassName(className.replaceAll(oldPrimaryName,
  5056. primaryStyleName));
  5057. }
  5058. public void addCell(UIDL rowUidl, Widget w, char align,
  5059. String style, boolean sorted, String description) {
  5060. final TableCellElement td = DOM.createTD().cast();
  5061. initCellWithWidget(w, align, style, sorted, td);
  5062. setTooltip(td, description);
  5063. }
  5064. private void setTooltip(TableCellElement td, String description) {
  5065. if (description != null && !description.equals("")) {
  5066. TooltipInfo info = new TooltipInfo(description, null, this);
  5067. cellToolTips.put(td, info);
  5068. } else {
  5069. cellToolTips.remove(td);
  5070. }
  5071. }
  5072. private void setAlign(char align, final Element container) {
  5073. switch (align) {
  5074. case ALIGN_CENTER:
  5075. container.getStyle().setProperty("textAlign", "center");
  5076. break;
  5077. case ALIGN_LEFT:
  5078. container.getStyle().setProperty("textAlign", "left");
  5079. break;
  5080. case ALIGN_RIGHT:
  5081. default:
  5082. container.getStyle().setProperty("textAlign", "right");
  5083. break;
  5084. }
  5085. }
  5086. protected void initCellWithWidget(Widget w, char align,
  5087. String style, boolean sorted, final TableCellElement td) {
  5088. final Element container = DOM.createDiv();
  5089. String className = VScrollTable.this.getStylePrimaryName()
  5090. + "-cell-content";
  5091. if (style != null && !style.equals("")) {
  5092. className += " " + VScrollTable.this.getStylePrimaryName()
  5093. + "-cell-content-" + style;
  5094. }
  5095. if (sorted) {
  5096. className += " " + VScrollTable.this.getStylePrimaryName()
  5097. + "-cell-content-sorted";
  5098. }
  5099. td.setClassName(className);
  5100. container.setClassName(VScrollTable.this.getStylePrimaryName()
  5101. + "-cell-wrapper");
  5102. setAlign(align, container);
  5103. td.appendChild(container);
  5104. getElement().appendChild(td);
  5105. // ensure widget not attached to another element (possible tBody
  5106. // change)
  5107. w.removeFromParent();
  5108. container.appendChild(w.getElement());
  5109. adopt(w);
  5110. childWidgets.add(w);
  5111. }
  5112. @Override
  5113. public Iterator<Widget> iterator() {
  5114. return childWidgets.iterator();
  5115. }
  5116. @Override
  5117. public boolean remove(Widget w) {
  5118. if (childWidgets.contains(w)) {
  5119. orphan(w);
  5120. DOM.removeChild(DOM.getParent(w.getElement()),
  5121. w.getElement());
  5122. childWidgets.remove(w);
  5123. return true;
  5124. } else {
  5125. return false;
  5126. }
  5127. }
  5128. /**
  5129. * If there are registered click listeners, sends a click event and
  5130. * returns true. Otherwise, does nothing and returns false.
  5131. *
  5132. * @param event
  5133. * @param targetTdOrTr
  5134. * @param immediate
  5135. * Whether the event is sent immediately
  5136. * @return Whether a click event was sent
  5137. */
  5138. private boolean handleClickEvent(Event event, Element targetTdOrTr,
  5139. boolean immediate) {
  5140. if (!client.hasEventListeners(VScrollTable.this,
  5141. TableConstants.ITEM_CLICK_EVENT_ID)) {
  5142. // Don't send an event if nobody is listening
  5143. return false;
  5144. }
  5145. // This row was clicked
  5146. client.updateVariable(paintableId, "clickedKey", "" + rowKey,
  5147. false);
  5148. if (getElement() == targetTdOrTr.getParentElement()) {
  5149. // A specific column was clicked
  5150. int childIndex = DOM.getChildIndex(getElement(),
  5151. targetTdOrTr);
  5152. String colKey = null;
  5153. colKey = tHead.getHeaderCell(childIndex).getColKey();
  5154. client.updateVariable(paintableId, "clickedColKey", colKey,
  5155. false);
  5156. }
  5157. MouseEventDetails details = MouseEventDetailsBuilder
  5158. .buildMouseEventDetails(event);
  5159. client.updateVariable(paintableId, "clickEvent",
  5160. details.toString(), immediate);
  5161. return true;
  5162. }
  5163. public TooltipInfo getTooltip(
  5164. com.google.gwt.dom.client.Element target) {
  5165. TooltipInfo info = null;
  5166. final Element targetTdOrTr = getTdOrTr(target);
  5167. if (targetTdOrTr != null
  5168. && "td".equals(targetTdOrTr.getTagName().toLowerCase())) {
  5169. TableCellElement td = (TableCellElement) targetTdOrTr
  5170. .cast();
  5171. info = cellToolTips.get(td);
  5172. }
  5173. if (info == null) {
  5174. info = tooltipInfo;
  5175. }
  5176. return info;
  5177. }
  5178. private Element getTdOrTr(Element target) {
  5179. Element thisTrElement = getElement();
  5180. if (target == thisTrElement) {
  5181. // This was a on the TR element
  5182. return target;
  5183. }
  5184. // Iterate upwards until we find the TR element
  5185. Element element = target;
  5186. while (element != null
  5187. && element.getParentElement() != thisTrElement) {
  5188. element = element.getParentElement();
  5189. }
  5190. return element;
  5191. }
  5192. /**
  5193. * Special handler for touch devices that support native scrolling
  5194. *
  5195. * @return Whether the event was handled by this method.
  5196. */
  5197. private boolean handleTouchEvent(final Event event) {
  5198. boolean touchEventHandled = false;
  5199. if (enabled && hasNativeTouchScrolling) {
  5200. touchContextProvider.handleTouchEvent(event);
  5201. final Element targetTdOrTr = getEventTargetTdOrTr(event);
  5202. final int type = event.getTypeInt();
  5203. switch (type) {
  5204. case Event.ONTOUCHSTART:
  5205. touchEventHandled = true;
  5206. touchStart = event;
  5207. isDragging = false;
  5208. Touch touch = event.getChangedTouches().get(0);
  5209. // save position to fields, touches in events are same
  5210. // instance during the operation.
  5211. touchStartX = touch.getClientX();
  5212. touchStartY = touch.getClientY();
  5213. if (dragmode != 0) {
  5214. if (dragTouchTimeout == null) {
  5215. dragTouchTimeout = new Timer() {
  5216. @Override
  5217. public void run() {
  5218. if (touchStart != null) {
  5219. // Start a drag if a finger is held
  5220. // in place long enough, then moved
  5221. isDragging = true;
  5222. }
  5223. }
  5224. };
  5225. }
  5226. dragTouchTimeout.schedule(TOUCHSCROLL_TIMEOUT);
  5227. }
  5228. if (actionKeys != null) {
  5229. if (contextTouchTimeout == null) {
  5230. contextTouchTimeout = new Timer() {
  5231. @Override
  5232. public void run() {
  5233. if (touchStart != null) {
  5234. // Open the context menu if finger
  5235. // is held in place long enough.
  5236. showContextMenu(touchStart);
  5237. event.preventDefault();
  5238. touchStart = null;
  5239. }
  5240. }
  5241. };
  5242. }
  5243. contextTouchTimeout
  5244. .schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  5245. event.stopPropagation();
  5246. }
  5247. break;
  5248. case Event.ONTOUCHMOVE:
  5249. touchEventHandled = true;
  5250. if (isSignificantMove(event)) {
  5251. if (contextTouchTimeout != null) {
  5252. // Moved finger before the context menu timer
  5253. // expired, so let the browser handle this as a
  5254. // scroll.
  5255. contextTouchTimeout.cancel();
  5256. contextTouchTimeout = null;
  5257. }
  5258. if (!isDragging && dragTouchTimeout != null) {
  5259. // Moved finger before the drag timer expired,
  5260. // so let the browser handle this as a scroll.
  5261. dragTouchTimeout.cancel();
  5262. dragTouchTimeout = null;
  5263. }
  5264. if (dragmode != 0 && touchStart != null
  5265. && isDragging) {
  5266. event.preventDefault();
  5267. event.stopPropagation();
  5268. startRowDrag(touchStart, type, targetTdOrTr);
  5269. }
  5270. touchStart = null;
  5271. }
  5272. break;
  5273. case Event.ONTOUCHEND:
  5274. case Event.ONTOUCHCANCEL:
  5275. touchEventHandled = true;
  5276. if (contextTouchTimeout != null) {
  5277. contextTouchTimeout.cancel();
  5278. }
  5279. if (dragTouchTimeout != null) {
  5280. dragTouchTimeout.cancel();
  5281. }
  5282. if (touchStart != null) {
  5283. if (!BrowserInfo.get().isAndroid()) {
  5284. event.preventDefault();
  5285. WidgetUtil.simulateClickFromTouchEvent(
  5286. touchStart, this);
  5287. }
  5288. event.stopPropagation();
  5289. touchStart = null;
  5290. }
  5291. isDragging = false;
  5292. break;
  5293. }
  5294. }
  5295. return touchEventHandled;
  5296. }
  5297. /*
  5298. * React on click that occur on content cells only
  5299. */
  5300. @Override
  5301. public void onBrowserEvent(final Event event) {
  5302. final boolean touchEventHandled = handleTouchEvent(event);
  5303. if (enabled && !touchEventHandled) {
  5304. final int type = event.getTypeInt();
  5305. final Element targetTdOrTr = getEventTargetTdOrTr(event);
  5306. if (type == Event.ONCONTEXTMENU) {
  5307. showContextMenu(event);
  5308. if (enabled
  5309. && (actionKeys != null || client
  5310. .hasEventListeners(
  5311. VScrollTable.this,
  5312. TableConstants.ITEM_CLICK_EVENT_ID))) {
  5313. /*
  5314. * Prevent browser context menu only if there are
  5315. * action handlers or item click listeners
  5316. * registered
  5317. */
  5318. event.stopPropagation();
  5319. event.preventDefault();
  5320. }
  5321. return;
  5322. }
  5323. boolean targetCellOrRowFound = targetTdOrTr != null;
  5324. switch (type) {
  5325. case Event.ONDBLCLICK:
  5326. if (targetCellOrRowFound) {
  5327. handleClickEvent(event, targetTdOrTr, true);
  5328. }
  5329. break;
  5330. case Event.ONMOUSEUP:
  5331. /*
  5332. * Only fire a click if the mouseup hits the same
  5333. * element as the corresponding mousedown. This is first
  5334. * checked in the event preview but we can't fire the
  5335. * event there as the event might get canceled before it
  5336. * gets here.
  5337. */
  5338. if (mouseUpPreviewMatched
  5339. && lastMouseDownTarget != null
  5340. && lastMouseDownTarget == getElementTdOrTr(WidgetUtil
  5341. .getElementUnderMouse(event))) {
  5342. // "Click" with left, right or middle button
  5343. if (targetCellOrRowFound) {
  5344. /*
  5345. * Queue here, send at the same time as the
  5346. * corresponding value change event - see #7127
  5347. */
  5348. boolean clickEventSent = handleClickEvent(
  5349. event, targetTdOrTr, false);
  5350. if (event.getButton() == Event.BUTTON_LEFT
  5351. && isSelectable()) {
  5352. // Ctrl+Shift click
  5353. if ((event.getCtrlKey() || event
  5354. .getMetaKey())
  5355. && event.getShiftKey()
  5356. && isMultiSelectModeDefault()) {
  5357. toggleShiftSelection(false);
  5358. setRowFocus(this);
  5359. // Ctrl click
  5360. } else if ((event.getCtrlKey() || event
  5361. .getMetaKey())
  5362. && isMultiSelectModeDefault()) {
  5363. boolean wasSelected = isSelected();
  5364. toggleSelection();
  5365. setRowFocus(this);
  5366. /*
  5367. * next possible range select must start
  5368. * on this row
  5369. */
  5370. selectionRangeStart = this;
  5371. if (wasSelected) {
  5372. removeRowFromUnsentSelectionRanges(this);
  5373. }
  5374. } else if ((event.getCtrlKey() || event
  5375. .getMetaKey())
  5376. && isSingleSelectMode()) {
  5377. // Ctrl (or meta) click (Single
  5378. // selection)
  5379. if (!isSelected()
  5380. || (isSelected() && nullSelectionAllowed)) {
  5381. if (!isSelected()) {
  5382. deselectAll();
  5383. }
  5384. toggleSelection();
  5385. setRowFocus(this);
  5386. }
  5387. } else if (event.getShiftKey()
  5388. && isMultiSelectModeDefault()) {
  5389. // Shift click
  5390. toggleShiftSelection(true);
  5391. } else {
  5392. // click
  5393. boolean currentlyJustThisRowSelected = selectedRowKeys
  5394. .size() == 1
  5395. && selectedRowKeys
  5396. .contains(getKey());
  5397. if (!currentlyJustThisRowSelected) {
  5398. if (isSingleSelectMode()
  5399. || isMultiSelectModeDefault()) {
  5400. /*
  5401. * For default multi select mode
  5402. * (ctrl/shift) and for single
  5403. * select mode we need to clear
  5404. * the previous selection before
  5405. * selecting a new one when the
  5406. * user clicks on a row. Only in
  5407. * multiselect/simple mode the
  5408. * old selection should remain
  5409. * after a normal click.
  5410. */
  5411. deselectAll();
  5412. }
  5413. toggleSelection();
  5414. } else if ((isSingleSelectMode() || isMultiSelectModeSimple())
  5415. && nullSelectionAllowed) {
  5416. toggleSelection();
  5417. }/*
  5418. * else NOP to avoid excessive server
  5419. * visits (selection is removed with
  5420. * CTRL/META click)
  5421. */
  5422. selectionRangeStart = this;
  5423. setRowFocus(this);
  5424. }
  5425. // Remove IE text selection hack
  5426. if (BrowserInfo.get().isIE()) {
  5427. ((Element) event.getEventTarget()
  5428. .cast()).setPropertyJSO(
  5429. "onselectstart", null);
  5430. }
  5431. // Queue value change
  5432. sendSelectedRows(false);
  5433. }
  5434. /*
  5435. * Send queued click and value change events if
  5436. * any If a click event is sent, send value
  5437. * change with it regardless of the immediate
  5438. * flag, see #7127
  5439. */
  5440. if (immediate || clickEventSent) {
  5441. client.sendPendingVariableChanges();
  5442. }
  5443. }
  5444. }
  5445. mouseUpPreviewMatched = false;
  5446. lastMouseDownTarget = null;
  5447. break;
  5448. case Event.ONTOUCHEND:
  5449. case Event.ONTOUCHCANCEL:
  5450. if (touchStart != null) {
  5451. /*
  5452. * Touch has not been handled as neither context or
  5453. * drag start, handle it as a click.
  5454. */
  5455. WidgetUtil.simulateClickFromTouchEvent(touchStart,
  5456. this);
  5457. touchStart = null;
  5458. }
  5459. touchContextProvider.cancel();
  5460. break;
  5461. case Event.ONTOUCHMOVE:
  5462. if (isSignificantMove(event)) {
  5463. /*
  5464. * TODO figure out scroll delegate don't eat events
  5465. * if row is selected. Null check for active
  5466. * delegate is as a workaround.
  5467. */
  5468. if (dragmode != 0
  5469. && touchStart != null
  5470. && (TouchScrollDelegate
  5471. .getActiveScrollDelegate() == null)) {
  5472. startRowDrag(touchStart, type, targetTdOrTr);
  5473. }
  5474. touchContextProvider.cancel();
  5475. /*
  5476. * Avoid clicks and drags by clearing touch start
  5477. * flag.
  5478. */
  5479. touchStart = null;
  5480. }
  5481. break;
  5482. case Event.ONTOUCHSTART:
  5483. touchStart = event;
  5484. Touch touch = event.getChangedTouches().get(0);
  5485. // save position to fields, touches in events are same
  5486. // instance during the operation.
  5487. touchStartX = touch.getClientX();
  5488. touchStartY = touch.getClientY();
  5489. /*
  5490. * Prevent simulated mouse events.
  5491. */
  5492. touchStart.preventDefault();
  5493. if (dragmode != 0 || actionKeys != null) {
  5494. new Timer() {
  5495. @Override
  5496. public void run() {
  5497. TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
  5498. .getActiveScrollDelegate();
  5499. /*
  5500. * If there's a scroll delegate, check if
  5501. * we're actually scrolling and handle it.
  5502. * If no delegate, do nothing here and let
  5503. * the row handle potential drag'n'drop or
  5504. * context menu.
  5505. */
  5506. if (activeScrollDelegate != null) {
  5507. if (activeScrollDelegate.isMoved()) {
  5508. /*
  5509. * Prevent the row from handling
  5510. * touch move/end events (the
  5511. * delegate handles those) and from
  5512. * doing drag'n'drop or opening a
  5513. * context menu.
  5514. */
  5515. touchStart = null;
  5516. } else {
  5517. /*
  5518. * Scrolling hasn't started, so
  5519. * cancel delegate and let the row
  5520. * handle potential drag'n'drop or
  5521. * context menu.
  5522. */
  5523. activeScrollDelegate
  5524. .stopScrolling();
  5525. }
  5526. }
  5527. }
  5528. }.schedule(TOUCHSCROLL_TIMEOUT);
  5529. if (contextTouchTimeout == null
  5530. && actionKeys != null) {
  5531. contextTouchTimeout = new Timer() {
  5532. @Override
  5533. public void run() {
  5534. if (touchStart != null) {
  5535. showContextMenu(touchStart);
  5536. touchStart = null;
  5537. }
  5538. }
  5539. };
  5540. }
  5541. if (contextTouchTimeout != null) {
  5542. contextTouchTimeout.cancel();
  5543. contextTouchTimeout
  5544. .schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  5545. }
  5546. }
  5547. break;
  5548. case Event.ONMOUSEDOWN:
  5549. /*
  5550. * When getting a mousedown event, we must detect where
  5551. * the corresponding mouseup event if it's on a
  5552. * different part of the page.
  5553. */
  5554. lastMouseDownTarget = getElementTdOrTr(WidgetUtil
  5555. .getElementUnderMouse(event));
  5556. mouseUpPreviewMatched = false;
  5557. mouseUpEventPreviewRegistration = Event
  5558. .addNativePreviewHandler(mouseUpPreviewHandler);
  5559. if (targetCellOrRowFound) {
  5560. setRowFocus(this);
  5561. ensureFocus();
  5562. if (dragmode != 0
  5563. && (event.getButton() == NativeEvent.BUTTON_LEFT)) {
  5564. startRowDrag(event, type, targetTdOrTr);
  5565. } else if (event.getCtrlKey()
  5566. || event.getShiftKey()
  5567. || event.getMetaKey()
  5568. && isMultiSelectModeDefault()) {
  5569. // Prevent default text selection in Firefox
  5570. event.preventDefault();
  5571. // Prevent default text selection in IE
  5572. if (BrowserInfo.get().isIE()) {
  5573. ((Element) event.getEventTarget().cast())
  5574. .setPropertyJSO(
  5575. "onselectstart",
  5576. getPreventTextSelectionIEHack());
  5577. }
  5578. event.stopPropagation();
  5579. }
  5580. }
  5581. break;
  5582. case Event.ONMOUSEOUT:
  5583. break;
  5584. default:
  5585. break;
  5586. }
  5587. }
  5588. super.onBrowserEvent(event);
  5589. }
  5590. private boolean isSignificantMove(Event event) {
  5591. if (touchStart == null) {
  5592. // no touch start
  5593. return false;
  5594. }
  5595. /*
  5596. * TODO calculate based on real distance instead of separate
  5597. * axis checks
  5598. */
  5599. Touch touch = event.getChangedTouches().get(0);
  5600. if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  5601. return true;
  5602. }
  5603. if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
  5604. return true;
  5605. }
  5606. return false;
  5607. }
  5608. /**
  5609. * Checks if the row represented by the row key has been selected
  5610. *
  5611. * @param key
  5612. * The generated row key
  5613. */
  5614. private boolean rowKeyIsSelected(int rowKey) {
  5615. // Check single selections
  5616. if (selectedRowKeys.contains("" + rowKey)) {
  5617. return true;
  5618. }
  5619. // Check range selections
  5620. for (SelectionRange r : selectedRowRanges) {
  5621. if (r.inRange(getRenderedRowByKey("" + rowKey))) {
  5622. return true;
  5623. }
  5624. }
  5625. return false;
  5626. }
  5627. protected void startRowDrag(Event event, final int type,
  5628. Element targetTdOrTr) {
  5629. VTransferable transferable = new VTransferable();
  5630. transferable.setDragSource(ConnectorMap.get(client)
  5631. .getConnector(VScrollTable.this));
  5632. transferable.setData("itemId", "" + rowKey);
  5633. NodeList<TableCellElement> cells = rowElement.getCells();
  5634. for (int i = 0; i < cells.getLength(); i++) {
  5635. if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
  5636. HeaderCell headerCell = tHead.getHeaderCell(i);
  5637. transferable.setData("propertyId", headerCell.cid);
  5638. break;
  5639. }
  5640. }
  5641. VDragEvent ev = VDragAndDropManager.get().startDrag(
  5642. transferable, event, true);
  5643. if (dragmode == DRAGMODE_MULTIROW && isMultiSelectModeAny()
  5644. && rowKeyIsSelected(rowKey)) {
  5645. // Create a drag image of ALL rows
  5646. ev.createDragImage(scrollBody.tBodyElement, true);
  5647. // Hide rows which are not selected
  5648. Element dragImage = ev.getDragImage();
  5649. int i = 0;
  5650. for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
  5651. .hasNext();) {
  5652. VScrollTableRow next = (VScrollTableRow) iterator
  5653. .next();
  5654. Element child = (Element) dragImage.getChild(i++);
  5655. if (!rowKeyIsSelected(next.rowKey)) {
  5656. child.getStyle().setVisibility(Visibility.HIDDEN);
  5657. }
  5658. }
  5659. } else {
  5660. ev.createDragImage(getElement(), true);
  5661. }
  5662. if (type == Event.ONMOUSEDOWN) {
  5663. event.preventDefault();
  5664. }
  5665. event.stopPropagation();
  5666. }
  5667. /**
  5668. * Finds the TD that the event interacts with. Returns null if the
  5669. * target of the event should not be handled. If the event target is
  5670. * the row directly this method returns the TR element instead of
  5671. * the TD.
  5672. *
  5673. * @param event
  5674. * @return TD or TR element that the event targets (the actual event
  5675. * target is this element or a child of it)
  5676. */
  5677. private Element getEventTargetTdOrTr(Event event) {
  5678. final Element eventTarget = event.getEventTarget().cast();
  5679. return getElementTdOrTr(eventTarget);
  5680. }
  5681. private Element getElementTdOrTr(Element element) {
  5682. Widget widget = WidgetUtil.findWidget(element, null);
  5683. if (widget != this) {
  5684. /*
  5685. * This is a workaround to make Labels, read only TextFields
  5686. * and Embedded in a Table clickable (see #2688). It is
  5687. * really not a fix as it does not work with a custom read
  5688. * only components (not extending VLabel/VEmbedded).
  5689. */
  5690. while (widget != null && widget.getParent() != this) {
  5691. widget = widget.getParent();
  5692. }
  5693. if (!(widget instanceof VLabel)
  5694. && !(widget instanceof VEmbedded)
  5695. && !(widget instanceof VTextField && ((VTextField) widget)
  5696. .isReadOnly())) {
  5697. return null;
  5698. }
  5699. }
  5700. return getTdOrTr(element);
  5701. }
  5702. @Override
  5703. public void showContextMenu(Event event) {
  5704. if (enabled && actionKeys != null) {
  5705. // Show context menu if there are registered action handlers
  5706. int left = WidgetUtil.getTouchOrMouseClientX(event)
  5707. + Window.getScrollLeft();
  5708. int top = WidgetUtil.getTouchOrMouseClientY(event)
  5709. + Window.getScrollTop();
  5710. showContextMenu(left, top);
  5711. }
  5712. }
  5713. public void showContextMenu(int left, int top) {
  5714. VContextMenu menu = client.getContextMenu();
  5715. contextMenu = new ContextMenuDetails(menu, getKey(), left, top);
  5716. menu.showAt(this, left, top);
  5717. }
  5718. /**
  5719. * Has the row been selected?
  5720. *
  5721. * @return Returns true if selected, else false
  5722. */
  5723. public boolean isSelected() {
  5724. return selected;
  5725. }
  5726. /**
  5727. * Toggle the selection of the row
  5728. */
  5729. public void toggleSelection() {
  5730. selected = !selected;
  5731. selectionChanged = true;
  5732. if (selected) {
  5733. selectedRowKeys.add(String.valueOf(rowKey));
  5734. addStyleName("v-selected");
  5735. } else {
  5736. removeStyleName("v-selected");
  5737. selectedRowKeys.remove(String.valueOf(rowKey));
  5738. }
  5739. }
  5740. /**
  5741. * Is called when a user clicks an item when holding SHIFT key down.
  5742. * This will select a new range from the last focused row
  5743. *
  5744. * @param deselectPrevious
  5745. * Should the previous selected range be deselected
  5746. */
  5747. private void toggleShiftSelection(boolean deselectPrevious) {
  5748. /*
  5749. * Ensures that we are in multiselect mode and that we have a
  5750. * previous selection which was not a deselection
  5751. */
  5752. if (isSingleSelectMode()) {
  5753. // No previous selection found
  5754. deselectAll();
  5755. toggleSelection();
  5756. return;
  5757. }
  5758. // Set the selectable range
  5759. VScrollTableRow endRow = this;
  5760. VScrollTableRow startRow = selectionRangeStart;
  5761. if (startRow == null) {
  5762. startRow = focusedRow;
  5763. selectionRangeStart = focusedRow;
  5764. // If start row is null then we have a multipage selection
  5765. // from above
  5766. if (startRow == null) {
  5767. startRow = (VScrollTableRow) scrollBody.iterator()
  5768. .next();
  5769. setRowFocus(endRow);
  5770. }
  5771. } else if (!startRow.isSelected()) {
  5772. // The start row is no longer selected (probably removed)
  5773. // and so we select from above
  5774. startRow = (VScrollTableRow) scrollBody.iterator().next();
  5775. setRowFocus(endRow);
  5776. }
  5777. // Deselect previous items if so desired
  5778. if (deselectPrevious) {
  5779. deselectAll();
  5780. }
  5781. // we'll ensure GUI state from top down even though selection
  5782. // was the opposite way
  5783. if (!startRow.isBefore(endRow)) {
  5784. VScrollTableRow tmp = startRow;
  5785. startRow = endRow;
  5786. endRow = tmp;
  5787. }
  5788. SelectionRange range = new SelectionRange(startRow, endRow);
  5789. for (Widget w : scrollBody) {
  5790. VScrollTableRow row = (VScrollTableRow) w;
  5791. if (range.inRange(row)) {
  5792. if (!row.isSelected()) {
  5793. row.toggleSelection();
  5794. }
  5795. selectedRowKeys.add(row.getKey());
  5796. }
  5797. }
  5798. // Add range
  5799. if (startRow != endRow) {
  5800. selectedRowRanges.add(range);
  5801. }
  5802. }
  5803. /*
  5804. * (non-Javadoc)
  5805. *
  5806. * @see com.vaadin.client.ui.IActionOwner#getActions ()
  5807. */
  5808. @Override
  5809. public Action[] getActions() {
  5810. if (actionKeys == null) {
  5811. return new Action[] {};
  5812. }
  5813. final Action[] actions = new Action[actionKeys.length];
  5814. for (int i = 0; i < actions.length; i++) {
  5815. final String actionKey = actionKeys[i];
  5816. final TreeAction a = new TreeAction(this,
  5817. String.valueOf(rowKey), actionKey) {
  5818. @Override
  5819. public void execute() {
  5820. super.execute();
  5821. lazyRevertFocusToRow(VScrollTableRow.this);
  5822. }
  5823. };
  5824. a.setCaption(getActionCaption(actionKey));
  5825. a.setIconUrl(getActionIcon(actionKey));
  5826. actions[i] = a;
  5827. }
  5828. return actions;
  5829. }
  5830. @Override
  5831. public ApplicationConnection getClient() {
  5832. return client;
  5833. }
  5834. @Override
  5835. public String getPaintableId() {
  5836. return paintableId;
  5837. }
  5838. private int getColIndexOf(Widget child) {
  5839. com.google.gwt.dom.client.Element widgetCell = child
  5840. .getElement().getParentElement().getParentElement();
  5841. NodeList<TableCellElement> cells = rowElement.getCells();
  5842. for (int i = 0; i < cells.getLength(); i++) {
  5843. if (cells.getItem(i) == widgetCell) {
  5844. return i;
  5845. }
  5846. }
  5847. return -1;
  5848. }
  5849. public Widget getWidgetForPaintable() {
  5850. return this;
  5851. }
  5852. }
  5853. protected class VScrollTableGeneratedRow extends VScrollTableRow {
  5854. private boolean spanColumns;
  5855. private boolean htmlContentAllowed;
  5856. public VScrollTableGeneratedRow(UIDL uidl, char[] aligns) {
  5857. super(uidl, aligns);
  5858. addStyleName("v-table-generated-row");
  5859. }
  5860. public boolean isSpanColumns() {
  5861. return spanColumns;
  5862. }
  5863. @Override
  5864. protected void initCellWidths() {
  5865. if (spanColumns) {
  5866. setSpannedColumnWidthAfterDOMFullyInited();
  5867. } else {
  5868. super.initCellWidths();
  5869. }
  5870. }
  5871. private void setSpannedColumnWidthAfterDOMFullyInited() {
  5872. // Defer setting width on spanned columns to make sure that
  5873. // they are added to the DOM before trying to calculate
  5874. // widths.
  5875. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  5876. @Override
  5877. public void execute() {
  5878. if (showRowHeaders) {
  5879. setCellWidth(0, tHead.getHeaderCell(0)
  5880. .getWidthWithIndent());
  5881. calcAndSetSpanWidthOnCell(1);
  5882. } else {
  5883. calcAndSetSpanWidthOnCell(0);
  5884. }
  5885. }
  5886. });
  5887. }
  5888. @Override
  5889. protected boolean isRenderHtmlInCells() {
  5890. return htmlContentAllowed;
  5891. }
  5892. @Override
  5893. protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
  5894. int visibleColumnIndex) {
  5895. htmlContentAllowed = uidl.getBooleanAttribute("gen_html");
  5896. spanColumns = uidl.getBooleanAttribute("gen_span");
  5897. final Iterator<?> cells = uidl.getChildIterator();
  5898. if (spanColumns) {
  5899. int colCount = uidl.getChildCount();
  5900. if (cells.hasNext()) {
  5901. final Object cell = cells.next();
  5902. if (cell instanceof String) {
  5903. addSpannedCell(uidl, cell.toString(), aligns[0],
  5904. "", htmlContentAllowed, false, null,
  5905. colCount);
  5906. } else {
  5907. addSpannedCell(uidl, (Widget) cell, aligns[0], "",
  5908. false, colCount);
  5909. }
  5910. }
  5911. } else {
  5912. super.addCellsFromUIDL(uidl, aligns, col,
  5913. visibleColumnIndex);
  5914. }
  5915. }
  5916. private void addSpannedCell(UIDL rowUidl, Widget w, char align,
  5917. String style, boolean sorted, int colCount) {
  5918. TableCellElement td = DOM.createTD().cast();
  5919. td.setColSpan(colCount);
  5920. initCellWithWidget(w, align, style, sorted, td);
  5921. }
  5922. private void addSpannedCell(UIDL rowUidl, String text, char align,
  5923. String style, boolean textIsHTML, boolean sorted,
  5924. String description, int colCount) {
  5925. // String only content is optimized by not using Label widget
  5926. final TableCellElement td = DOM.createTD().cast();
  5927. td.setColSpan(colCount);
  5928. initCellWithText(text, align, style, textIsHTML, sorted,
  5929. description, td);
  5930. }
  5931. @Override
  5932. protected void setCellWidth(int cellIx, int width) {
  5933. if (isSpanColumns()) {
  5934. if (showRowHeaders) {
  5935. if (cellIx == 0) {
  5936. super.setCellWidth(0, width);
  5937. } else {
  5938. // We need to recalculate the spanning TDs width for
  5939. // every cellIx in order to support column resizing.
  5940. calcAndSetSpanWidthOnCell(1);
  5941. }
  5942. } else {
  5943. // Same as above.
  5944. calcAndSetSpanWidthOnCell(0);
  5945. }
  5946. } else {
  5947. super.setCellWidth(cellIx, width);
  5948. }
  5949. }
  5950. private void calcAndSetSpanWidthOnCell(final int cellIx) {
  5951. int spanWidth = 0;
  5952. for (int ix = (showRowHeaders ? 1 : 0); ix < tHead
  5953. .getVisibleCellCount(); ix++) {
  5954. spanWidth += tHead.getHeaderCell(ix).getOffsetWidth();
  5955. }
  5956. WidgetUtil.setWidthExcludingPaddingAndBorder(
  5957. (Element) getElement().getChild(cellIx), spanWidth, 13,
  5958. false);
  5959. }
  5960. }
  5961. /**
  5962. * Ensure the component has a focus.
  5963. *
  5964. * TODO the current implementation simply always calls focus for the
  5965. * component. In case the Table at some point implements focus/blur
  5966. * listeners, this method needs to be evolved to conditionally call
  5967. * focus only if not currently focused.
  5968. */
  5969. protected void ensureFocus() {
  5970. if (!hasFocus) {
  5971. scrollBodyPanel.setFocus(true);
  5972. }
  5973. }
  5974. }
  5975. /**
  5976. * Deselects all items
  5977. */
  5978. public void deselectAll() {
  5979. for (Widget w : scrollBody) {
  5980. VScrollTableRow row = (VScrollTableRow) w;
  5981. if (row.isSelected()) {
  5982. row.toggleSelection();
  5983. }
  5984. }
  5985. // still ensure all selects are removed from (not necessary rendered)
  5986. selectedRowKeys.clear();
  5987. selectedRowRanges.clear();
  5988. // also notify server that it clears all previous selections (the client
  5989. // side does not know about the invisible ones)
  5990. instructServerToForgetPreviousSelections();
  5991. }
  5992. /**
  5993. * Used in multiselect mode when the client side knows that all selections
  5994. * are in the next request.
  5995. */
  5996. private void instructServerToForgetPreviousSelections() {
  5997. client.updateVariable(paintableId, "clearSelections", true, false);
  5998. }
  5999. /**
  6000. * Determines the pagelength when the table height is fixed.
  6001. */
  6002. public void updatePageLength() {
  6003. // Only update if visible and enabled
  6004. if (!isVisible() || !enabled) {
  6005. return;
  6006. }
  6007. if (scrollBody == null) {
  6008. return;
  6009. }
  6010. if (isDynamicHeight()) {
  6011. return;
  6012. }
  6013. int rowHeight = (int) Math.round(scrollBody.getRowHeight());
  6014. int bodyH = scrollBodyPanel.getOffsetHeight();
  6015. int rowsAtOnce = bodyH / rowHeight;
  6016. boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
  6017. if (anotherPartlyVisible) {
  6018. rowsAtOnce++;
  6019. }
  6020. if (pageLength != rowsAtOnce) {
  6021. pageLength = rowsAtOnce;
  6022. client.updateVariable(paintableId, "pagelength", pageLength, false);
  6023. if (!rendering) {
  6024. int currentlyVisible = scrollBody.getLastRendered()
  6025. - scrollBody.getFirstRendered();
  6026. if (currentlyVisible < pageLength
  6027. && currentlyVisible < totalRows) {
  6028. // shake scrollpanel to fill empty space
  6029. scrollBodyPanel.setScrollPosition(scrollTop + 1);
  6030. scrollBodyPanel.setScrollPosition(scrollTop - 1);
  6031. }
  6032. sizeNeedsInit = true;
  6033. }
  6034. }
  6035. }
  6036. /** For internal use only. May be removed or replaced in the future. */
  6037. public void updateWidth() {
  6038. if (!isVisible()) {
  6039. /*
  6040. * Do not update size when the table is hidden as all column widths
  6041. * will be set to zero and they won't be recalculated when the table
  6042. * is set visible again (until the size changes again)
  6043. */
  6044. return;
  6045. }
  6046. if (!isDynamicWidth()) {
  6047. int innerPixels = getOffsetWidth() - getBorderWidth();
  6048. if (innerPixels < 0) {
  6049. innerPixels = 0;
  6050. }
  6051. setContentWidth(innerPixels);
  6052. // readjust undefined width columns
  6053. triggerLazyColumnAdjustment(false);
  6054. } else {
  6055. sizeNeedsInit = true;
  6056. // readjust undefined width columns
  6057. triggerLazyColumnAdjustment(false);
  6058. }
  6059. /*
  6060. * setting width may affect wheter the component has scrollbars -> needs
  6061. * scrolling or not
  6062. */
  6063. setProperTabIndex();
  6064. }
  6065. private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
  6066. private final Timer lazyAdjustColumnWidths = new Timer() {
  6067. /**
  6068. * Check for column widths, and available width, to see if we can fix
  6069. * column widths "optimally". Doing this lazily to avoid expensive
  6070. * calculation when resizing is not yet finished.
  6071. */
  6072. @Override
  6073. public void run() {
  6074. if (scrollBody == null) {
  6075. // Try again later if we get here before scrollBody has been
  6076. // initalized
  6077. triggerLazyColumnAdjustment(false);
  6078. return;
  6079. }
  6080. Iterator<Widget> headCells = tHead.iterator();
  6081. int usedMinimumWidth = 0;
  6082. int totalExplicitColumnsWidths = 0;
  6083. float expandRatioDivider = 0;
  6084. int colIndex = 0;
  6085. int hierarchyColumnIndent = scrollBody.getMaxIndent();
  6086. int hierarchyColumnIndex = getHierarchyColumnIndex();
  6087. HeaderCell hierarchyHeaderInNeedOfFurtherHandling = null;
  6088. while (headCells.hasNext()) {
  6089. final HeaderCell hCell = (HeaderCell) headCells.next();
  6090. boolean hasIndent = hierarchyColumnIndent > 0
  6091. && hCell.isHierarchyColumn();
  6092. if (hCell.isDefinedWidth()) {
  6093. // get width without indent to find out whether adjustments
  6094. // are needed (requires special handling further ahead)
  6095. int w = hCell.getWidth();
  6096. if (hasIndent && w < hierarchyColumnIndent) {
  6097. // enforce indent if necessary
  6098. w = hierarchyColumnIndent;
  6099. hierarchyHeaderInNeedOfFurtherHandling = hCell;
  6100. }
  6101. totalExplicitColumnsWidths += w;
  6102. usedMinimumWidth += w;
  6103. } else {
  6104. // natural width already includes indent if any
  6105. int naturalColumnWidth = hCell
  6106. .getNaturalColumnWidth(colIndex);
  6107. /*
  6108. * TODO If there is extra width, expand ratios are for
  6109. * additional extra widths, not for absolute column widths.
  6110. * Should be fixed in sizeInit(), too.
  6111. */
  6112. if (hCell.getExpandRatio() > 0) {
  6113. naturalColumnWidth = 0;
  6114. }
  6115. usedMinimumWidth += naturalColumnWidth;
  6116. expandRatioDivider += hCell.getExpandRatio();
  6117. if (hasIndent) {
  6118. hierarchyHeaderInNeedOfFurtherHandling = hCell;
  6119. }
  6120. }
  6121. colIndex++;
  6122. }
  6123. int availW = scrollBody.getAvailableWidth();
  6124. // Hey IE, are you really sure about this?
  6125. availW = scrollBody.getAvailableWidth();
  6126. int visibleCellCount = tHead.getVisibleCellCount();
  6127. int totalExtraWidth = scrollBody.getCellExtraWidth()
  6128. * visibleCellCount;
  6129. if (willHaveScrollbars()) {
  6130. totalExtraWidth += WidgetUtil.getNativeScrollbarSize();
  6131. // if there will be vertical scrollbar, let's enable it
  6132. scrollBodyPanel.getElement().getStyle().clearOverflowY();
  6133. } else {
  6134. // if there is no need for vertical scrollbar, let's disable it
  6135. // this is necessary since sometimes the browsers insist showing
  6136. // the scrollbar even if the content would fit perfectly
  6137. scrollBodyPanel.getElement().getStyle()
  6138. .setOverflowY(Overflow.HIDDEN);
  6139. }
  6140. availW -= totalExtraWidth;
  6141. int forceScrollBodyWidth = -1;
  6142. int extraSpace = availW - usedMinimumWidth;
  6143. if (extraSpace < 0) {
  6144. if (getTotalRows() == 0) {
  6145. /*
  6146. * Too wide header combined with no rows in the table.
  6147. *
  6148. * No horizontal scrollbars would be displayed because
  6149. * there's no rows that grows too wide causing the
  6150. * scrollBody container div to overflow. Must explicitely
  6151. * force a width to a scrollbar. (see #9187)
  6152. */
  6153. forceScrollBodyWidth = usedMinimumWidth + totalExtraWidth;
  6154. }
  6155. extraSpace = 0;
  6156. // if there will be horizontal scrollbar, let's enable it
  6157. scrollBodyPanel.getElement().getStyle().clearOverflowX();
  6158. } else {
  6159. // if there is no need for horizontal scrollbar, let's disable
  6160. // it
  6161. // this is necessary since sometimes the browsers insist showing
  6162. // the scrollbar even if the content would fit perfectly
  6163. scrollBodyPanel.getElement().getStyle()
  6164. .setOverflowX(Overflow.HIDDEN);
  6165. }
  6166. if (forceScrollBodyWidth > 0) {
  6167. scrollBody.container.getStyle().setWidth(forceScrollBodyWidth,
  6168. Unit.PX);
  6169. } else {
  6170. // Clear width that might have been set to force horizontal
  6171. // scrolling if there are no rows
  6172. scrollBody.container.getStyle().clearWidth();
  6173. }
  6174. int totalUndefinedNaturalWidths = usedMinimumWidth
  6175. - totalExplicitColumnsWidths;
  6176. if (hierarchyHeaderInNeedOfFurtherHandling != null
  6177. && !hierarchyHeaderInNeedOfFurtherHandling.isDefinedWidth()) {
  6178. // ensure the cell gets enough space for the indent
  6179. int w = hierarchyHeaderInNeedOfFurtherHandling
  6180. .getNaturalColumnWidth(hierarchyColumnIndex);
  6181. int newSpace = Math.round(w + (float) extraSpace * (float) w
  6182. / totalUndefinedNaturalWidths);
  6183. if (newSpace >= hierarchyColumnIndent) {
  6184. // no special handling required
  6185. hierarchyHeaderInNeedOfFurtherHandling = null;
  6186. } else {
  6187. // treat as a defined width column of indent's width
  6188. totalExplicitColumnsWidths += hierarchyColumnIndent;
  6189. usedMinimumWidth -= w - hierarchyColumnIndent;
  6190. totalUndefinedNaturalWidths = usedMinimumWidth
  6191. - totalExplicitColumnsWidths;
  6192. expandRatioDivider += hierarchyHeaderInNeedOfFurtherHandling
  6193. .getExpandRatio();
  6194. extraSpace = Math.max(availW - usedMinimumWidth, 0);
  6195. }
  6196. }
  6197. // we have some space that can be divided optimally
  6198. HeaderCell hCell;
  6199. colIndex = 0;
  6200. headCells = tHead.iterator();
  6201. int checksum = 0;
  6202. while (headCells.hasNext()) {
  6203. hCell = (HeaderCell) headCells.next();
  6204. if (hCell.isResizing) {
  6205. continue;
  6206. }
  6207. if (!hCell.isDefinedWidth()) {
  6208. int w = hCell.getNaturalColumnWidth(colIndex);
  6209. int newSpace;
  6210. if (expandRatioDivider > 0) {
  6211. // divide excess space by expand ratios
  6212. if (hCell.getExpandRatio() > 0) {
  6213. w = 0;
  6214. }
  6215. newSpace = Math.round((w + extraSpace
  6216. * hCell.getExpandRatio() / expandRatioDivider));
  6217. } else {
  6218. if (hierarchyHeaderInNeedOfFurtherHandling == hCell) {
  6219. // still exists, so needs exactly the indent's width
  6220. newSpace = hierarchyColumnIndent;
  6221. } else if (totalUndefinedNaturalWidths != 0) {
  6222. // divide relatively to natural column widths
  6223. newSpace = Math.round(w + (float) extraSpace
  6224. * (float) w / totalUndefinedNaturalWidths);
  6225. } else {
  6226. newSpace = w;
  6227. }
  6228. }
  6229. checksum += newSpace;
  6230. setColWidth(colIndex, newSpace, false);
  6231. } else {
  6232. if (hierarchyHeaderInNeedOfFurtherHandling == hCell) {
  6233. // defined with enforced into indent width
  6234. checksum += hierarchyColumnIndent;
  6235. setColWidth(colIndex, hierarchyColumnIndent, false);
  6236. } else {
  6237. int cellWidth = hCell.getWidthWithIndent();
  6238. checksum += cellWidth;
  6239. if (hCell.isHierarchyColumn()) {
  6240. // update in case the indent has changed
  6241. // (not detectable earlier)
  6242. setColWidth(colIndex, cellWidth, true);
  6243. }
  6244. }
  6245. }
  6246. colIndex++;
  6247. }
  6248. if (extraSpace > 0 && checksum != availW) {
  6249. /*
  6250. * There might be in some cases a rounding error of 1px when
  6251. * extra space is divided so if there is one then we give the
  6252. * first undefined column 1 more pixel
  6253. */
  6254. headCells = tHead.iterator();
  6255. colIndex = 0;
  6256. while (headCells.hasNext()) {
  6257. HeaderCell hc = (HeaderCell) headCells.next();
  6258. if (!hc.isResizing && !hc.isDefinedWidth()) {
  6259. setColWidth(colIndex, hc.getWidthWithIndent() + availW
  6260. - checksum, false);
  6261. break;
  6262. }
  6263. colIndex++;
  6264. }
  6265. }
  6266. if (isDynamicHeight() && totalRows == pageLength) {
  6267. // fix body height (may vary if lazy loading is offhorizontal
  6268. // scrollbar appears/disappears)
  6269. int bodyHeight = scrollBody.getRequiredHeight();
  6270. boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
  6271. if (needsSpaceForHorizontalScrollbar) {
  6272. bodyHeight += WidgetUtil.getNativeScrollbarSize();
  6273. }
  6274. int heightBefore = getOffsetHeight();
  6275. scrollBodyPanel.setHeight(bodyHeight + "px");
  6276. if (heightBefore != getOffsetHeight()) {
  6277. Util.notifyParentOfSizeChange(VScrollTable.this, rendering);
  6278. }
  6279. }
  6280. forceRealignColumnHeaders();
  6281. }
  6282. };
  6283. private void forceRealignColumnHeaders() {
  6284. if (BrowserInfo.get().isIE()) {
  6285. /*
  6286. * IE does not fire onscroll event if scroll position is reverted to
  6287. * 0 due to the content element size growth. Ensure headers are in
  6288. * sync with content manually. Safe to use null event as we don't
  6289. * actually use the event object in listener.
  6290. */
  6291. onScroll(null);
  6292. }
  6293. }
  6294. /**
  6295. * helper to set pixel size of head and body part
  6296. *
  6297. * @param pixels
  6298. */
  6299. private void setContentWidth(int pixels) {
  6300. tHead.setWidth(pixels + "px");
  6301. scrollBodyPanel.setWidth(pixels + "px");
  6302. tFoot.setWidth(pixels + "px");
  6303. }
  6304. private int borderWidth = -1;
  6305. /**
  6306. * @return border left + border right
  6307. */
  6308. private int getBorderWidth() {
  6309. if (borderWidth < 0) {
  6310. borderWidth = WidgetUtil.measureHorizontalPaddingAndBorder(
  6311. scrollBodyPanel.getElement(), 2);
  6312. if (borderWidth < 0) {
  6313. borderWidth = 0;
  6314. }
  6315. }
  6316. return borderWidth;
  6317. }
  6318. /**
  6319. * Ensures scrollable area is properly sized. This method is used when fixed
  6320. * size is used.
  6321. */
  6322. private int containerHeight;
  6323. private void setContainerHeight() {
  6324. if (!isDynamicHeight()) {
  6325. /*
  6326. * Android 2.3 cannot measure the height of the inline-block
  6327. * properly, and will return the wrong offset height. So for android
  6328. * 2.3 we set the element to a block element while measuring and
  6329. * then restore it which yields the correct result. #11331
  6330. */
  6331. if (BrowserInfo.get().isAndroid23()) {
  6332. getElement().getStyle().setDisplay(Display.BLOCK);
  6333. }
  6334. containerHeight = getOffsetHeight();
  6335. containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
  6336. containerHeight -= tFoot.getOffsetHeight();
  6337. containerHeight -= getContentAreaBorderHeight();
  6338. if (containerHeight < 0) {
  6339. containerHeight = 0;
  6340. }
  6341. scrollBodyPanel.setHeight(containerHeight + "px");
  6342. if (BrowserInfo.get().isAndroid23()) {
  6343. getElement().getStyle().clearDisplay();
  6344. }
  6345. }
  6346. }
  6347. private int contentAreaBorderHeight = -1;
  6348. private int scrollLeft;
  6349. private int scrollTop;
  6350. /** For internal use only. May be removed or replaced in the future. */
  6351. public VScrollTableDropHandler dropHandler;
  6352. private boolean navKeyDown;
  6353. /** For internal use only. May be removed or replaced in the future. */
  6354. public boolean multiselectPending;
  6355. /**
  6356. * @return border top + border bottom of the scrollable area of table
  6357. */
  6358. private int getContentAreaBorderHeight() {
  6359. if (contentAreaBorderHeight < 0) {
  6360. scrollBodyPanel.getElement().getStyle()
  6361. .setOverflow(Overflow.HIDDEN);
  6362. int oh = scrollBodyPanel.getOffsetHeight();
  6363. int ch = scrollBodyPanel.getElement()
  6364. .getPropertyInt("clientHeight");
  6365. contentAreaBorderHeight = oh - ch;
  6366. scrollBodyPanel.getElement().getStyle().setOverflow(Overflow.AUTO);
  6367. }
  6368. return contentAreaBorderHeight;
  6369. }
  6370. @Override
  6371. public void setHeight(String height) {
  6372. if (height.length() == 0
  6373. && getElement().getStyle().getHeight().length() != 0) {
  6374. /*
  6375. * Changing from defined to undefined size -> should do a size init
  6376. * to take page length into account again
  6377. */
  6378. sizeNeedsInit = true;
  6379. }
  6380. super.setHeight(height);
  6381. }
  6382. /** For internal use only. May be removed or replaced in the future. */
  6383. public void updateHeight() {
  6384. setContainerHeight();
  6385. if (initializedAndAttached) {
  6386. updatePageLength();
  6387. }
  6388. triggerLazyColumnAdjustment(false);
  6389. /*
  6390. * setting height may affect wheter the component has scrollbars ->
  6391. * needs scrolling or not
  6392. */
  6393. setProperTabIndex();
  6394. }
  6395. /*
  6396. * Overridden due Table might not survive of visibility change (scroll pos
  6397. * lost). Example ITabPanel just set contained components invisible and back
  6398. * when changing tabs.
  6399. */
  6400. @Override
  6401. public void setVisible(boolean visible) {
  6402. if (isVisible() != visible) {
  6403. super.setVisible(visible);
  6404. if (initializedAndAttached) {
  6405. if (visible) {
  6406. Scheduler.get().scheduleDeferred(new Command() {
  6407. @Override
  6408. public void execute() {
  6409. scrollBodyPanel
  6410. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  6411. }
  6412. });
  6413. }
  6414. }
  6415. }
  6416. }
  6417. /**
  6418. * Helper function to build html snippet for column or row headers
  6419. *
  6420. * @param uidl
  6421. * possibly with values caption and icon
  6422. * @return html snippet containing possibly an icon + caption text
  6423. */
  6424. protected String buildCaptionHtmlSnippet(UIDL uidl) {
  6425. String s = uidl.hasAttribute("caption") ? uidl
  6426. .getStringAttribute("caption") : "";
  6427. if (uidl.hasAttribute("icon")) {
  6428. Icon icon = client.getIcon(uidl.getStringAttribute("icon"));
  6429. icon.setAlternateText("icon");
  6430. s = icon.getElement().getString() + s;
  6431. }
  6432. return s;
  6433. }
  6434. // Updates first visible row for the case we cannot wait
  6435. // for onScroll
  6436. private void updateFirstVisibleRow() {
  6437. scrollTop = scrollBodyPanel.getScrollPosition();
  6438. firstRowInViewPort = calcFirstRowInViewPort();
  6439. int maxFirstRow = totalRows - pageLength;
  6440. if (firstRowInViewPort > maxFirstRow && maxFirstRow >= 0) {
  6441. firstRowInViewPort = maxFirstRow;
  6442. }
  6443. lastRequestedFirstvisible = firstRowInViewPort;
  6444. client.updateVariable(paintableId, "firstvisible", firstRowInViewPort,
  6445. false);
  6446. }
  6447. /**
  6448. * This method has logic which rows needs to be requested from server when
  6449. * user scrolls
  6450. */
  6451. @Override
  6452. public void onScroll(ScrollEvent event) {
  6453. // Do not handle scroll events while there is scroll initiated from
  6454. // server side which is not yet executed (#11454)
  6455. if (isLazyScrollerActive()) {
  6456. return;
  6457. }
  6458. scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
  6459. scrollTop = scrollBodyPanel.getScrollPosition();
  6460. /*
  6461. * #6970 - IE sometimes fires scroll events for a detached table.
  6462. *
  6463. * FIXME initializedAndAttached should probably be renamed - its name
  6464. * doesn't seem to reflect its semantics. onDetach() doesn't set it to
  6465. * false, and changing that might break something else, so we need to
  6466. * check isAttached() separately.
  6467. */
  6468. if (!initializedAndAttached || !isAttached()) {
  6469. return;
  6470. }
  6471. if (!enabled) {
  6472. scrollBodyPanel
  6473. .setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
  6474. return;
  6475. }
  6476. rowRequestHandler.cancel();
  6477. if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
  6478. // due to the webkitoverflowworkaround, top may sometimes report 0
  6479. // for webkit, although it really is not. Expecting to have the
  6480. // correct
  6481. // value available soon.
  6482. Scheduler.get().scheduleDeferred(new Command() {
  6483. @Override
  6484. public void execute() {
  6485. onScroll(null);
  6486. }
  6487. });
  6488. return;
  6489. }
  6490. // fix headers horizontal scrolling
  6491. tHead.setHorizontalScrollPosition(scrollLeft);
  6492. // fix footers horizontal scrolling
  6493. tFoot.setHorizontalScrollPosition(scrollLeft);
  6494. if (totalRows == 0) {
  6495. // No rows, no need to fetch new rows
  6496. return;
  6497. }
  6498. firstRowInViewPort = calcFirstRowInViewPort();
  6499. int maxFirstRow = totalRows - pageLength;
  6500. if (firstRowInViewPort > maxFirstRow && maxFirstRow >= 0) {
  6501. firstRowInViewPort = maxFirstRow;
  6502. }
  6503. int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
  6504. * cache_react_rate);
  6505. if (postLimit > totalRows - 1) {
  6506. postLimit = totalRows - 1;
  6507. }
  6508. int preLimit = (int) (firstRowInViewPort - pageLength
  6509. * cache_react_rate);
  6510. if (preLimit < 0) {
  6511. preLimit = 0;
  6512. }
  6513. final int lastRendered = scrollBody.getLastRendered();
  6514. final int firstRendered = scrollBody.getFirstRendered();
  6515. if (postLimit <= lastRendered && preLimit >= firstRendered) {
  6516. // we're within no-react area, no need to request more rows
  6517. // remember which firstvisible we requested, in case the server has
  6518. // a differing opinion
  6519. lastRequestedFirstvisible = firstRowInViewPort;
  6520. client.updateVariable(paintableId, "firstvisible",
  6521. firstRowInViewPort, false);
  6522. return;
  6523. }
  6524. if (allRenderedRowsAreNew()) {
  6525. // need a totally new set of rows
  6526. rowRequestHandler
  6527. .setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
  6528. int last = firstRowInViewPort + (int) (cache_rate * pageLength)
  6529. + pageLength - 1;
  6530. if (last >= totalRows) {
  6531. last = totalRows - 1;
  6532. }
  6533. rowRequestHandler.setReqRows(last
  6534. - rowRequestHandler.getReqFirstRow() + 1);
  6535. updatedReqRows = false;
  6536. rowRequestHandler.deferRowFetch();
  6537. return;
  6538. }
  6539. if (preLimit < firstRendered) {
  6540. // need some rows to the beginning of the rendered area
  6541. rowRequestHandler
  6542. .setReqFirstRow((int) (firstRowInViewPort - pageLength
  6543. * cache_rate));
  6544. rowRequestHandler.setReqRows(firstRendered
  6545. - rowRequestHandler.getReqFirstRow());
  6546. rowRequestHandler.deferRowFetch();
  6547. return;
  6548. }
  6549. if (postLimit > lastRendered) {
  6550. // need some rows to the end of the rendered area
  6551. int reqRows = (int) ((firstRowInViewPort + pageLength + pageLength
  6552. * cache_rate) - lastRendered);
  6553. rowRequestHandler.triggerRowFetch(lastRendered + 1, reqRows);
  6554. }
  6555. }
  6556. private boolean allRenderedRowsAreNew() {
  6557. int firstRowInViewPort = calcFirstRowInViewPort();
  6558. int firstRendered = scrollBody.getFirstRendered();
  6559. int lastRendered = scrollBody.getLastRendered();
  6560. return (firstRowInViewPort - pageLength * cache_rate > lastRendered || firstRowInViewPort
  6561. + pageLength + pageLength * cache_rate < firstRendered);
  6562. }
  6563. protected int calcFirstRowInViewPort() {
  6564. return (int) Math.ceil(scrollTop / scrollBody.getRowHeight());
  6565. }
  6566. @Override
  6567. public VScrollTableDropHandler getDropHandler() {
  6568. return dropHandler;
  6569. }
  6570. private static class TableDDDetails {
  6571. int overkey = -1;
  6572. VerticalDropLocation dropLocation;
  6573. String colkey;
  6574. @Override
  6575. public boolean equals(Object obj) {
  6576. if (obj instanceof TableDDDetails) {
  6577. TableDDDetails other = (TableDDDetails) obj;
  6578. return dropLocation == other.dropLocation
  6579. && overkey == other.overkey
  6580. && ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
  6581. }
  6582. return false;
  6583. }
  6584. //
  6585. // public int hashCode() {
  6586. // return overkey;
  6587. // }
  6588. }
  6589. public class VScrollTableDropHandler extends VAbstractDropHandler {
  6590. private static final String ROWSTYLEBASE = "v-table-row-drag-";
  6591. private TableDDDetails dropDetails;
  6592. private TableDDDetails lastEmphasized;
  6593. @Override
  6594. public void dragEnter(VDragEvent drag) {
  6595. updateDropDetails(drag);
  6596. super.dragEnter(drag);
  6597. }
  6598. private void updateDropDetails(VDragEvent drag) {
  6599. dropDetails = new TableDDDetails();
  6600. Element elementOver = drag.getElementOver();
  6601. Class<? extends Widget> clazz = getRowClass();
  6602. VScrollTableRow row = null;
  6603. if (clazz != null) {
  6604. row = WidgetUtil.findWidget(elementOver, clazz);
  6605. }
  6606. if (row != null) {
  6607. dropDetails.overkey = row.rowKey;
  6608. Element tr = row.getElement();
  6609. Element element = elementOver;
  6610. while (element != null && element.getParentElement() != tr) {
  6611. element = element.getParentElement();
  6612. }
  6613. int childIndex = DOM.getChildIndex(tr, element);
  6614. dropDetails.colkey = tHead.getHeaderCell(childIndex)
  6615. .getColKey();
  6616. dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
  6617. row.getElement(), drag.getCurrentGwtEvent(), 0.2);
  6618. }
  6619. drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
  6620. drag.getDropDetails().put(
  6621. "detail",
  6622. dropDetails.dropLocation != null ? dropDetails.dropLocation
  6623. .toString() : null);
  6624. }
  6625. private Class<? extends Widget> getRowClass() {
  6626. // get the row type this way to make dd work in derived
  6627. // implementations
  6628. Iterator<Widget> iterator = scrollBody.iterator();
  6629. if (iterator.hasNext()) {
  6630. return iterator.next().getClass();
  6631. } else {
  6632. return null;
  6633. }
  6634. }
  6635. @Override
  6636. public void dragOver(VDragEvent drag) {
  6637. TableDDDetails oldDetails = dropDetails;
  6638. updateDropDetails(drag);
  6639. if (!oldDetails.equals(dropDetails)) {
  6640. deEmphasis();
  6641. final TableDDDetails newDetails = dropDetails;
  6642. VAcceptCallback cb = new VAcceptCallback() {
  6643. @Override
  6644. public void accepted(VDragEvent event) {
  6645. if (newDetails.equals(dropDetails)) {
  6646. dragAccepted(event);
  6647. }
  6648. /*
  6649. * Else new target slot already defined, ignore
  6650. */
  6651. }
  6652. };
  6653. validate(cb, drag);
  6654. }
  6655. }
  6656. @Override
  6657. public void dragLeave(VDragEvent drag) {
  6658. deEmphasis();
  6659. super.dragLeave(drag);
  6660. }
  6661. @Override
  6662. public boolean drop(VDragEvent drag) {
  6663. deEmphasis();
  6664. return super.drop(drag);
  6665. }
  6666. private void deEmphasis() {
  6667. UIObject.setStyleName(getElement(),
  6668. getStylePrimaryName() + "-drag", false);
  6669. if (lastEmphasized == null) {
  6670. return;
  6671. }
  6672. for (Widget w : scrollBody.renderedRows) {
  6673. VScrollTableRow row = (VScrollTableRow) w;
  6674. if (lastEmphasized != null
  6675. && row.rowKey == lastEmphasized.overkey) {
  6676. String stylename = ROWSTYLEBASE
  6677. + lastEmphasized.dropLocation.toString()
  6678. .toLowerCase();
  6679. VScrollTableRow.setStyleName(row.getElement(), stylename,
  6680. false);
  6681. lastEmphasized = null;
  6682. return;
  6683. }
  6684. }
  6685. }
  6686. /**
  6687. * TODO needs different drop modes ?? (on cells, on rows), now only
  6688. * supports rows
  6689. */
  6690. private void emphasis(TableDDDetails details) {
  6691. deEmphasis();
  6692. UIObject.setStyleName(getElement(),
  6693. getStylePrimaryName() + "-drag", true);
  6694. // iterate old and new emphasized row
  6695. for (Widget w : scrollBody.renderedRows) {
  6696. VScrollTableRow row = (VScrollTableRow) w;
  6697. if (details != null && details.overkey == row.rowKey) {
  6698. String stylename = ROWSTYLEBASE
  6699. + details.dropLocation.toString().toLowerCase();
  6700. VScrollTableRow.setStyleName(row.getElement(), stylename,
  6701. true);
  6702. lastEmphasized = details;
  6703. return;
  6704. }
  6705. }
  6706. }
  6707. @Override
  6708. protected void dragAccepted(VDragEvent drag) {
  6709. emphasis(dropDetails);
  6710. }
  6711. @Override
  6712. public ComponentConnector getConnector() {
  6713. return ConnectorMap.get(client).getConnector(VScrollTable.this);
  6714. }
  6715. @Override
  6716. public ApplicationConnection getApplicationConnection() {
  6717. return client;
  6718. }
  6719. }
  6720. protected VScrollTableRow getFocusedRow() {
  6721. return focusedRow;
  6722. }
  6723. /**
  6724. * Moves the selection head to a specific row
  6725. *
  6726. * @param row
  6727. * The row to where the selection head should move
  6728. * @return Returns true if focus was moved successfully, else false
  6729. */
  6730. public boolean setRowFocus(VScrollTableRow row) {
  6731. if (!isSelectable()) {
  6732. return false;
  6733. }
  6734. // Remove previous selection
  6735. if (focusedRow != null && focusedRow != row) {
  6736. focusedRow.removeStyleName(getStylePrimaryName() + "-focus");
  6737. }
  6738. if (row != null) {
  6739. // Apply focus style to new selection
  6740. row.addStyleName(getStylePrimaryName() + "-focus");
  6741. /*
  6742. * Trying to set focus on already focused row
  6743. */
  6744. if (row == focusedRow) {
  6745. return false;
  6746. }
  6747. // Set new focused row
  6748. focusedRow = row;
  6749. if (hasFocus) {
  6750. ensureRowIsVisible(row);
  6751. }
  6752. return true;
  6753. }
  6754. return false;
  6755. }
  6756. /**
  6757. * Ensures that the row is visible
  6758. *
  6759. * @param row
  6760. * The row to ensure is visible
  6761. */
  6762. private void ensureRowIsVisible(VScrollTableRow row) {
  6763. if (BrowserInfo.get().isTouchDevice()) {
  6764. // Skip due to android devices that have broken scrolltop will may
  6765. // get odd scrolling here.
  6766. return;
  6767. }
  6768. /*
  6769. * FIXME The next line doesn't always do what expected, because if the
  6770. * row is not in the DOM it won't scroll to it.
  6771. */
  6772. WidgetUtil.scrollIntoViewVertically(row.getElement());
  6773. }
  6774. /**
  6775. * Handles the keyboard events handled by the table
  6776. *
  6777. * @param event
  6778. * The keyboard event received
  6779. * @return true iff the navigation event was handled
  6780. */
  6781. protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  6782. if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
  6783. // Do not handle tab key
  6784. return false;
  6785. }
  6786. // Down navigation
  6787. if (!isSelectable() && keycode == getNavigationDownKey()) {
  6788. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  6789. .getScrollPosition() + scrollingVelocity);
  6790. return true;
  6791. } else if (keycode == getNavigationDownKey()) {
  6792. if (isMultiSelectModeAny() && moveFocusDown()) {
  6793. selectFocusedRow(ctrl, shift);
  6794. } else if (isSingleSelectMode() && !shift && moveFocusDown()) {
  6795. selectFocusedRow(ctrl, shift);
  6796. }
  6797. return true;
  6798. }
  6799. // Up navigation
  6800. if (!isSelectable() && keycode == getNavigationUpKey()) {
  6801. scrollBodyPanel.setScrollPosition(scrollBodyPanel
  6802. .getScrollPosition() - scrollingVelocity);
  6803. return true;
  6804. } else if (keycode == getNavigationUpKey()) {
  6805. if (isMultiSelectModeAny() && moveFocusUp()) {
  6806. selectFocusedRow(ctrl, shift);
  6807. } else if (isSingleSelectMode() && !shift && moveFocusUp()) {
  6808. selectFocusedRow(ctrl, shift);
  6809. }
  6810. return true;
  6811. }
  6812. if (keycode == getNavigationLeftKey()) {
  6813. // Left navigation
  6814. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  6815. .getHorizontalScrollPosition() - scrollingVelocity);
  6816. return true;
  6817. } else if (keycode == getNavigationRightKey()) {
  6818. // Right navigation
  6819. scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
  6820. .getHorizontalScrollPosition() + scrollingVelocity);
  6821. return true;
  6822. }
  6823. // Select navigation
  6824. if (isSelectable() && keycode == getNavigationSelectKey()) {
  6825. if (isSingleSelectMode()) {
  6826. boolean wasSelected = focusedRow.isSelected();
  6827. deselectAll();
  6828. if (!wasSelected || !nullSelectionAllowed) {
  6829. focusedRow.toggleSelection();
  6830. }
  6831. } else {
  6832. focusedRow.toggleSelection();
  6833. removeRowFromUnsentSelectionRanges(focusedRow);
  6834. }
  6835. sendSelectedRows();
  6836. return true;
  6837. }
  6838. // Page Down navigation
  6839. if (keycode == getNavigationPageDownKey()) {
  6840. if (isSelectable()) {
  6841. /*
  6842. * If selectable we plagiate MSW behaviour: first scroll to the
  6843. * end of current view. If at the end, scroll down one page
  6844. * length and keep the selected row in the bottom part of
  6845. * visible area.
  6846. */
  6847. if (!isFocusAtTheEndOfTable()) {
  6848. VScrollTableRow lastVisibleRowInViewPort = scrollBody
  6849. .getRowByRowIndex(firstRowInViewPort
  6850. + getFullyVisibleRowCount() - 1);
  6851. if (lastVisibleRowInViewPort != null
  6852. && lastVisibleRowInViewPort != focusedRow) {
  6853. // focused row is not at the end of the table, move
  6854. // focus and select the last visible row
  6855. setRowFocus(lastVisibleRowInViewPort);
  6856. selectFocusedRow(ctrl, shift);
  6857. updateFirstVisibleAndSendSelectedRows();
  6858. } else {
  6859. int indexOfToBeFocused = focusedRow.getIndex()
  6860. + getFullyVisibleRowCount();
  6861. if (indexOfToBeFocused >= totalRows) {
  6862. indexOfToBeFocused = totalRows - 1;
  6863. }
  6864. VScrollTableRow toBeFocusedRow = scrollBody
  6865. .getRowByRowIndex(indexOfToBeFocused);
  6866. if (toBeFocusedRow != null) {
  6867. /*
  6868. * if the next focused row is rendered
  6869. */
  6870. setRowFocus(toBeFocusedRow);
  6871. selectFocusedRow(ctrl, shift);
  6872. // TODO needs scrollintoview ?
  6873. updateFirstVisibleAndSendSelectedRows();
  6874. } else {
  6875. // scroll down by pixels and return, to wait for
  6876. // new rows, then select the last item in the
  6877. // viewport
  6878. selectLastItemInNextRender = true;
  6879. multiselectPending = shift;
  6880. scrollByPagelength(1);
  6881. }
  6882. }
  6883. }
  6884. } else {
  6885. /* No selections, go page down by scrolling */
  6886. scrollByPagelength(1);
  6887. }
  6888. return true;
  6889. }
  6890. // Page Up navigation
  6891. if (keycode == getNavigationPageUpKey()) {
  6892. if (isSelectable()) {
  6893. /*
  6894. * If selectable we plagiate MSW behaviour: first scroll to the
  6895. * end of current view. If at the end, scroll down one page
  6896. * length and keep the selected row in the bottom part of
  6897. * visible area.
  6898. */
  6899. if (!isFocusAtTheBeginningOfTable()) {
  6900. VScrollTableRow firstVisibleRowInViewPort = scrollBody
  6901. .getRowByRowIndex(firstRowInViewPort);
  6902. if (firstVisibleRowInViewPort != null
  6903. && firstVisibleRowInViewPort != focusedRow) {
  6904. // focus is not at the beginning of the table, move
  6905. // focus and select the first visible row
  6906. setRowFocus(firstVisibleRowInViewPort);
  6907. selectFocusedRow(ctrl, shift);
  6908. updateFirstVisibleAndSendSelectedRows();
  6909. } else {
  6910. int indexOfToBeFocused = focusedRow.getIndex()
  6911. - getFullyVisibleRowCount();
  6912. if (indexOfToBeFocused < 0) {
  6913. indexOfToBeFocused = 0;
  6914. }
  6915. VScrollTableRow toBeFocusedRow = scrollBody
  6916. .getRowByRowIndex(indexOfToBeFocused);
  6917. if (toBeFocusedRow != null) { // if the next focused row
  6918. // is rendered
  6919. setRowFocus(toBeFocusedRow);
  6920. selectFocusedRow(ctrl, shift);
  6921. // TODO needs scrollintoview ?
  6922. updateFirstVisibleAndSendSelectedRows();
  6923. } else {
  6924. // unless waiting for the next rowset already
  6925. // scroll down by pixels and return, to wait for
  6926. // new rows, then select the last item in the
  6927. // viewport
  6928. selectFirstItemInNextRender = true;
  6929. multiselectPending = shift;
  6930. scrollByPagelength(-1);
  6931. }
  6932. }
  6933. }
  6934. } else {
  6935. /* No selections, go page up by scrolling */
  6936. scrollByPagelength(-1);
  6937. }
  6938. return true;
  6939. }
  6940. // Goto start navigation
  6941. if (keycode == getNavigationStartKey()) {
  6942. scrollBodyPanel.setScrollPosition(0);
  6943. if (isSelectable()) {
  6944. if (focusedRow != null && focusedRow.getIndex() == 0) {
  6945. return false;
  6946. } else {
  6947. VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
  6948. .iterator().next();
  6949. if (rowByRowIndex.getIndex() == 0) {
  6950. setRowFocus(rowByRowIndex);
  6951. selectFocusedRow(ctrl, shift);
  6952. updateFirstVisibleAndSendSelectedRows();
  6953. } else {
  6954. // first row of table will come in next row fetch
  6955. if (ctrl) {
  6956. focusFirstItemInNextRender = true;
  6957. } else {
  6958. selectFirstItemInNextRender = true;
  6959. multiselectPending = shift;
  6960. }
  6961. }
  6962. }
  6963. }
  6964. return true;
  6965. }
  6966. // Goto end navigation
  6967. if (keycode == getNavigationEndKey()) {
  6968. scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
  6969. if (isSelectable()) {
  6970. final int lastRendered = scrollBody.getLastRendered();
  6971. if (lastRendered + 1 == totalRows) {
  6972. VScrollTableRow rowByRowIndex = scrollBody
  6973. .getRowByRowIndex(lastRendered);
  6974. if (focusedRow != rowByRowIndex) {
  6975. setRowFocus(rowByRowIndex);
  6976. selectFocusedRow(ctrl, shift);
  6977. updateFirstVisibleAndSendSelectedRows();
  6978. }
  6979. } else {
  6980. if (ctrl) {
  6981. focusLastItemInNextRender = true;
  6982. } else {
  6983. selectLastItemInNextRender = true;
  6984. multiselectPending = shift;
  6985. }
  6986. }
  6987. }
  6988. return true;
  6989. }
  6990. return false;
  6991. }
  6992. private boolean isFocusAtTheBeginningOfTable() {
  6993. return focusedRow.getIndex() == 0;
  6994. }
  6995. private boolean isFocusAtTheEndOfTable() {
  6996. return focusedRow.getIndex() + 1 >= totalRows;
  6997. }
  6998. private int getFullyVisibleRowCount() {
  6999. return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
  7000. .getRowHeight());
  7001. }
  7002. private void scrollByPagelength(int i) {
  7003. int pixels = i * scrollBodyPanel.getOffsetHeight();
  7004. int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
  7005. if (newPixels < 0) {
  7006. newPixels = 0;
  7007. } // else if too high, NOP (all know browsers accept illegally big
  7008. // values here)
  7009. scrollBodyPanel.setScrollPosition(newPixels);
  7010. }
  7011. /*
  7012. * (non-Javadoc)
  7013. *
  7014. * @see
  7015. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  7016. * .dom.client.FocusEvent)
  7017. */
  7018. @Override
  7019. public void onFocus(FocusEvent event) {
  7020. if (isFocusable()) {
  7021. hasFocus = true;
  7022. // Focus a row if no row is in focus
  7023. if (focusedRow == null) {
  7024. focusRowFromBody();
  7025. } else {
  7026. setRowFocus(focusedRow);
  7027. }
  7028. }
  7029. }
  7030. /*
  7031. * (non-Javadoc)
  7032. *
  7033. * @see
  7034. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  7035. * .dom.client.BlurEvent)
  7036. */
  7037. @Override
  7038. public void onBlur(BlurEvent event) {
  7039. hasFocus = false;
  7040. navKeyDown = false;
  7041. if (BrowserInfo.get().isIE()) {
  7042. /*
  7043. * IE sometimes moves focus to a clicked table cell... (#7965)
  7044. * ...and sometimes it sends blur events even though the focus
  7045. * handler is still active. (#10464)
  7046. */
  7047. Element focusedElement = WidgetUtil.getFocusedElement();
  7048. if (Util.getConnectorForElement(client, getParent(), focusedElement) == this
  7049. && focusedElement != null
  7050. && focusedElement != scrollBodyPanel.getFocusElement()) {
  7051. /*
  7052. * Steal focus back to the focus handler if it was moved to some
  7053. * other part of the table. Avoid stealing focus in other cases.
  7054. */
  7055. focus();
  7056. return;
  7057. }
  7058. }
  7059. if (isFocusable()) {
  7060. // Unfocus any row
  7061. setRowFocus(null);
  7062. }
  7063. }
  7064. /**
  7065. * Removes a key from a range if the key is found in a selected range
  7066. *
  7067. * @param key
  7068. * The key to remove
  7069. */
  7070. private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
  7071. Collection<SelectionRange> newRanges = null;
  7072. for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
  7073. .hasNext();) {
  7074. SelectionRange range = iterator.next();
  7075. if (range.inRange(row)) {
  7076. // Split the range if given row is in range
  7077. Collection<SelectionRange> splitranges = range.split(row);
  7078. if (newRanges == null) {
  7079. newRanges = new ArrayList<SelectionRange>();
  7080. }
  7081. newRanges.addAll(splitranges);
  7082. iterator.remove();
  7083. }
  7084. }
  7085. if (newRanges != null) {
  7086. selectedRowRanges.addAll(newRanges);
  7087. }
  7088. }
  7089. /**
  7090. * Can the Table be focused?
  7091. *
  7092. * @return True if the table can be focused, else false
  7093. */
  7094. public boolean isFocusable() {
  7095. if (scrollBody != null && enabled) {
  7096. return !(!hasHorizontalScrollbar() && !hasVerticalScrollbar() && !isSelectable());
  7097. }
  7098. return false;
  7099. }
  7100. private boolean hasHorizontalScrollbar() {
  7101. return scrollBody.getOffsetWidth() > scrollBodyPanel.getOffsetWidth();
  7102. }
  7103. private boolean hasVerticalScrollbar() {
  7104. return scrollBody.getOffsetHeight() > scrollBodyPanel.getOffsetHeight();
  7105. }
  7106. /*
  7107. * (non-Javadoc)
  7108. *
  7109. * @see com.vaadin.client.Focusable#focus()
  7110. */
  7111. @Override
  7112. public void focus() {
  7113. if (isFocusable()) {
  7114. scrollBodyPanel.focus();
  7115. }
  7116. }
  7117. /**
  7118. * Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
  7119. * component).
  7120. * <p>
  7121. * If the component has no explicit tabIndex a zero is given (default
  7122. * tabbing order based on dom hierarchy) or -1 if the component does not
  7123. * need to gain focus. The component needs no focus if it has no scrollabars
  7124. * (not scrollable) and not selectable. Note that in the future shortcut
  7125. * actions may need focus.
  7126. * <p>
  7127. * For internal use only. May be removed or replaced in the future.
  7128. */
  7129. public void setProperTabIndex() {
  7130. int storedScrollTop = 0;
  7131. int storedScrollLeft = 0;
  7132. if (BrowserInfo.get().getOperaVersion() >= 11) {
  7133. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  7134. storedScrollTop = scrollBodyPanel.getScrollPosition();
  7135. storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
  7136. }
  7137. if (tabIndex == 0 && !isFocusable()) {
  7138. scrollBodyPanel.setTabIndex(-1);
  7139. } else {
  7140. scrollBodyPanel.setTabIndex(tabIndex);
  7141. }
  7142. if (BrowserInfo.get().getOperaVersion() >= 11) {
  7143. // Workaround for Opera scroll bug when changing tabIndex (#6222)
  7144. scrollBodyPanel.setScrollPosition(storedScrollTop);
  7145. scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
  7146. }
  7147. }
  7148. public void startScrollingVelocityTimer() {
  7149. if (scrollingVelocityTimer == null) {
  7150. scrollingVelocityTimer = new Timer() {
  7151. @Override
  7152. public void run() {
  7153. scrollingVelocity++;
  7154. }
  7155. };
  7156. scrollingVelocityTimer.scheduleRepeating(100);
  7157. }
  7158. }
  7159. public void cancelScrollingVelocityTimer() {
  7160. if (scrollingVelocityTimer != null) {
  7161. // Remove velocityTimer if it exists and the Table is disabled
  7162. scrollingVelocityTimer.cancel();
  7163. scrollingVelocityTimer = null;
  7164. scrollingVelocity = 10;
  7165. }
  7166. }
  7167. /**
  7168. *
  7169. * @param keyCode
  7170. * @return true if the given keyCode is used by the table for navigation
  7171. */
  7172. private boolean isNavigationKey(int keyCode) {
  7173. return keyCode == getNavigationUpKey()
  7174. || keyCode == getNavigationLeftKey()
  7175. || keyCode == getNavigationRightKey()
  7176. || keyCode == getNavigationDownKey()
  7177. || keyCode == getNavigationPageUpKey()
  7178. || keyCode == getNavigationPageDownKey()
  7179. || keyCode == getNavigationEndKey()
  7180. || keyCode == getNavigationStartKey();
  7181. }
  7182. public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
  7183. Scheduler.get().scheduleFinally(new ScheduledCommand() {
  7184. @Override
  7185. public void execute() {
  7186. if (currentlyFocusedRow != null) {
  7187. setRowFocus(currentlyFocusedRow);
  7188. } else {
  7189. VConsole.log("no row?");
  7190. focusRowFromBody();
  7191. }
  7192. scrollBody.ensureFocus();
  7193. }
  7194. });
  7195. }
  7196. @Override
  7197. public Action[] getActions() {
  7198. if (bodyActionKeys == null) {
  7199. return new Action[] {};
  7200. }
  7201. final Action[] actions = new Action[bodyActionKeys.length];
  7202. for (int i = 0; i < actions.length; i++) {
  7203. final String actionKey = bodyActionKeys[i];
  7204. Action bodyAction = new TreeAction(this, null, actionKey);
  7205. bodyAction.setCaption(getActionCaption(actionKey));
  7206. bodyAction.setIconUrl(getActionIcon(actionKey));
  7207. actions[i] = bodyAction;
  7208. }
  7209. return actions;
  7210. }
  7211. @Override
  7212. public ApplicationConnection getClient() {
  7213. return client;
  7214. }
  7215. @Override
  7216. public String getPaintableId() {
  7217. return paintableId;
  7218. }
  7219. /**
  7220. * Add this to the element mouse down event by using element.setPropertyJSO
  7221. * ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
  7222. * when the mouse is depressed in the mouse up event.
  7223. *
  7224. * @return Returns the JSO preventing text selection
  7225. */
  7226. private static native JavaScriptObject getPreventTextSelectionIEHack()
  7227. /*-{
  7228. return function(){ return false; };
  7229. }-*/;
  7230. public void triggerLazyColumnAdjustment(boolean now) {
  7231. lazyAdjustColumnWidths.cancel();
  7232. if (now) {
  7233. lazyAdjustColumnWidths.run();
  7234. } else {
  7235. lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
  7236. }
  7237. }
  7238. private boolean isDynamicWidth() {
  7239. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  7240. this);
  7241. return paintable.isUndefinedWidth();
  7242. }
  7243. private boolean isDynamicHeight() {
  7244. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  7245. this);
  7246. if (paintable == null) {
  7247. // This should be refactored. As isDynamicHeight can be called from
  7248. // a timer it is possible that the connector has been unregistered
  7249. // when this method is called, causing getConnector to return null.
  7250. return false;
  7251. }
  7252. return paintable.isUndefinedHeight();
  7253. }
  7254. private void debug(String msg) {
  7255. if (enableDebug) {
  7256. VConsole.error(msg);
  7257. }
  7258. }
  7259. public Widget getWidgetForPaintable() {
  7260. return this;
  7261. }
  7262. private static final String SUBPART_HEADER = "header";
  7263. private static final String SUBPART_FOOTER = "footer";
  7264. private static final String SUBPART_ROW = "row";
  7265. private static final String SUBPART_COL = "col";
  7266. /**
  7267. * Matches header[ix] - used for extracting the index of the targeted header
  7268. * cell
  7269. */
  7270. private static final RegExp SUBPART_HEADER_REGEXP = RegExp
  7271. .compile(SUBPART_HEADER + "\\[(\\d+)\\]");
  7272. /**
  7273. * Matches footer[ix] - used for extracting the index of the targeted footer
  7274. * cell
  7275. */
  7276. private static final RegExp SUBPART_FOOTER_REGEXP = RegExp
  7277. .compile(SUBPART_FOOTER + "\\[(\\d+)\\]");
  7278. /** Matches row[ix] - used for extracting the index of the targeted row */
  7279. private static final RegExp SUBPART_ROW_REGEXP = RegExp.compile(SUBPART_ROW
  7280. + "\\[(\\d+)]");
  7281. /** Matches col[ix] - used for extracting the index of the targeted column */
  7282. private static final RegExp SUBPART_ROW_COL_REGEXP = RegExp
  7283. .compile(SUBPART_ROW + "\\[(\\d+)\\]/" + SUBPART_COL
  7284. + "\\[(\\d+)\\]");
  7285. @Override
  7286. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  7287. if (SUBPART_ROW_COL_REGEXP.test(subPart)) {
  7288. MatchResult result = SUBPART_ROW_COL_REGEXP.exec(subPart);
  7289. int rowIx = Integer.valueOf(result.getGroup(1));
  7290. int colIx = Integer.valueOf(result.getGroup(2));
  7291. VScrollTableRow row = scrollBody.getRowByRowIndex(rowIx);
  7292. if (row != null) {
  7293. Element rowElement = row.getElement();
  7294. if (colIx < rowElement.getChildCount()) {
  7295. return rowElement.getChild(colIx).getFirstChild().cast();
  7296. }
  7297. }
  7298. } else if (SUBPART_ROW_REGEXP.test(subPart)) {
  7299. MatchResult result = SUBPART_ROW_REGEXP.exec(subPart);
  7300. int rowIx = Integer.valueOf(result.getGroup(1));
  7301. VScrollTableRow row = scrollBody.getRowByRowIndex(rowIx);
  7302. if (row != null) {
  7303. return row.getElement();
  7304. }
  7305. } else if (SUBPART_HEADER_REGEXP.test(subPart)) {
  7306. MatchResult result = SUBPART_HEADER_REGEXP.exec(subPart);
  7307. int headerIx = Integer.valueOf(result.getGroup(1));
  7308. HeaderCell headerCell = tHead.getHeaderCell(headerIx);
  7309. if (headerCell != null) {
  7310. return headerCell.getElement();
  7311. }
  7312. } else if (SUBPART_FOOTER_REGEXP.test(subPart)) {
  7313. MatchResult result = SUBPART_FOOTER_REGEXP.exec(subPart);
  7314. int footerIx = Integer.valueOf(result.getGroup(1));
  7315. FooterCell footerCell = tFoot.getFooterCell(footerIx);
  7316. if (footerCell != null) {
  7317. return footerCell.getElement();
  7318. }
  7319. }
  7320. // Nothing found.
  7321. return null;
  7322. }
  7323. @Override
  7324. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  7325. Widget widget = WidgetUtil.findWidget(subElement, null);
  7326. if (widget instanceof HeaderCell) {
  7327. return SUBPART_HEADER + "[" + tHead.visibleCells.indexOf(widget)
  7328. + "]";
  7329. } else if (widget instanceof FooterCell) {
  7330. return SUBPART_FOOTER + "[" + tFoot.visibleCells.indexOf(widget)
  7331. + "]";
  7332. } else if (widget instanceof VScrollTableRow) {
  7333. // a cell in a row
  7334. VScrollTableRow row = (VScrollTableRow) widget;
  7335. int rowIx = scrollBody.indexOf(row);
  7336. if (rowIx >= 0) {
  7337. int colIx = -1;
  7338. for (int ix = 0; ix < row.getElement().getChildCount(); ix++) {
  7339. if (row.getElement().getChild(ix).isOrHasChild(subElement)) {
  7340. colIx = ix;
  7341. break;
  7342. }
  7343. }
  7344. if (colIx >= 0) {
  7345. return SUBPART_ROW + "[" + rowIx + "]/" + SUBPART_COL + "["
  7346. + colIx + "]";
  7347. }
  7348. return SUBPART_ROW + "[" + rowIx + "]";
  7349. }
  7350. }
  7351. // Nothing found.
  7352. return null;
  7353. }
  7354. /**
  7355. * @since 7.2.6
  7356. */
  7357. public void onUnregister() {
  7358. if (addCloseHandler != null) {
  7359. addCloseHandler.removeHandler();
  7360. }
  7361. }
  7362. /*
  7363. * Return true if component need to perform some work and false otherwise.
  7364. */
  7365. @Override
  7366. public boolean isWorkPending() {
  7367. return lazyAdjustColumnWidths.isRunning();
  7368. }
  7369. private static Logger getLogger() {
  7370. return Logger.getLogger(VScrollTable.class.getName());
  7371. }
  7372. }