PageRenderTime 102ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 2ms

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

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