1 /* 2 * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package javafx.scene.control.skin; 27 28 import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler; 29 import com.sun.javafx.scene.control.Properties; 30 import com.sun.javafx.scene.control.TableColumnBaseHelper; 31 import javafx.beans.property.DoubleProperty; 32 import javafx.beans.property.ReadOnlyObjectProperty; 33 import javafx.beans.property.ReadOnlyObjectWrapper; 34 import javafx.beans.value.WritableValue; 35 import javafx.collections.ListChangeListener; 36 import javafx.collections.ObservableList; 37 import javafx.collections.WeakListChangeListener; 38 import javafx.css.CssMetaData; 39 import javafx.css.PseudoClass; 40 import javafx.css.Styleable; 41 import javafx.css.StyleableDoubleProperty; 42 import javafx.css.StyleableProperty; 43 import javafx.event.EventHandler; 44 import javafx.geometry.HPos; 45 import javafx.geometry.Insets; 46 import javafx.geometry.Pos; 47 import javafx.geometry.VPos; 48 import javafx.scene.AccessibleAttribute; 49 import javafx.scene.AccessibleRole; 50 import javafx.scene.Node; 51 import javafx.scene.control.ContextMenu; 52 import javafx.scene.control.Label; 53 import javafx.scene.control.TableColumn; 54 import javafx.scene.control.TableColumnBase; 55 import javafx.scene.input.ContextMenuEvent; 56 import javafx.scene.input.MouseEvent; 57 import javafx.scene.layout.GridPane; 58 import javafx.scene.layout.HBox; 59 import javafx.scene.layout.Priority; 60 import javafx.scene.layout.Region; 61 62 import java.util.ArrayList; 63 import java.util.Collections; 64 import java.util.List; 65 import java.util.Locale; 66 67 import javafx.css.converter.SizeConverter; 68 69 import static com.sun.javafx.scene.control.TableColumnSortTypeWrapper.getSortTypeName; 70 import static com.sun.javafx.scene.control.TableColumnSortTypeWrapper.getSortTypeProperty; 71 import static com.sun.javafx.scene.control.TableColumnSortTypeWrapper.isAscending; 72 import static com.sun.javafx.scene.control.TableColumnSortTypeWrapper.isDescending; 73 import static com.sun.javafx.scene.control.TableColumnSortTypeWrapper.setSortType; 74 75 76 /** 77 * Region responsible for painting a single column header. 78 * 79 * @since 9 80 */ 81 public class TableColumnHeader extends Region { 82 83 /*************************************************************************** 84 * * 85 * Static Fields * 86 * * 87 **************************************************************************/ 88 89 // Copied from TableColumn. The value here should always be in-sync with 90 // the value in TableColumn 91 static final double DEFAULT_COLUMN_WIDTH = 80.0F; 92 93 94 95 /*************************************************************************** 96 * * 97 * Private Fields * 98 * * 99 **************************************************************************/ 100 101 private boolean autoSizeComplete = false; 102 103 private double dragOffset; 104 private final TableViewSkinBase<?,?,?,?,TableColumnBase<?,?>> skin; 105 private NestedTableColumnHeader nestedColumnHeader; 106 private TableHeaderRow tableHeaderRow; 107 private NestedTableColumnHeader parentHeader; 108 109 // work out where this column currently is within its parent 110 Label label; 111 112 // sort order 113 int sortPos = -1; 114 private Region arrow; 115 private Label sortOrderLabel; 116 private HBox sortOrderDots; 117 private Node sortArrow; 118 private boolean isSortColumn; 119 120 private boolean isSizeDirty = false; 121 122 boolean isLastVisibleColumn = false; 123 124 // package for testing 125 int columnIndex = -1; 126 127 private int newColumnPos; 128 129 // the line drawn in the table when a user presses and moves a column header 130 // to indicate where the column will be dropped. This is provided by the 131 // table skin, but manipulated by the header 132 final Region columnReorderLine; 133 134 135 136 /*************************************************************************** 137 * * 138 * Constructor * 139 * * 140 **************************************************************************/ 141 142 /** 143 * Creates a new TableColumnHeader instance to visually represent the given 144 * {@link TableColumnBase} instance. 145 * 146 * @param skin The skin used by the UI control. 147 * @param tc The table column to be visually represented by this instance. 148 */ 149 public TableColumnHeader(final TableViewSkinBase skin, final TableColumnBase tc) { 150 this.skin = skin; 151 setTableColumn(tc); 152 this.columnReorderLine = skin.getColumnReorderLine(); 153 154 setFocusTraversable(false); 155 156 updateColumnIndex(); 157 initUI(); 158 159 // change listener for multiple properties 160 changeListenerHandler = new LambdaMultiplePropertyChangeListenerHandler(); 161 changeListenerHandler.registerChangeListener(sceneProperty(), e -> updateScene()); 162 163 if (getTableColumn() != null) { 164 updateSortPosition(); 165 TableSkinUtils.getSortOrder(skin).addListener(weakSortOrderListener); 166 TableSkinUtils.getVisibleLeafColumns(skin).addListener(weakVisibleLeafColumnsListener); 167 } 168 169 if (getTableColumn() != null) { 170 changeListenerHandler.registerChangeListener(tc.idProperty(), e -> setId(tc.getId())); 171 changeListenerHandler.registerChangeListener(tc.styleProperty(), e -> setStyle(tc.getStyle())); 172 changeListenerHandler.registerChangeListener(tc.widthProperty(), e -> { 173 // It is this that ensures that when a column is resized that the header 174 // visually adjusts its width as necessary. 175 isSizeDirty = true; 176 requestLayout(); 177 }); 178 changeListenerHandler.registerChangeListener(tc.visibleProperty(), e -> setVisible(getTableColumn().isVisible())); 179 changeListenerHandler.registerChangeListener(tc.sortNodeProperty(), e -> updateSortGrid()); 180 changeListenerHandler.registerChangeListener(tc.sortableProperty(), e -> { 181 // we need to notify all headers that a sortable state has changed, 182 // in case the sort grid in other columns needs to be updated. 183 if (TableSkinUtils.getSortOrder(skin).contains(getTableColumn())) { 184 NestedTableColumnHeader root = getTableHeaderRow().getRootHeader(); 185 updateAllHeaders(root); 186 } 187 }); 188 changeListenerHandler.registerChangeListener(tc.textProperty(), e -> label.setText(tc.getText())); 189 changeListenerHandler.registerChangeListener(tc.graphicProperty(), e -> label.setGraphic(tc.getGraphic())); 190 191 tc.getStyleClass().addListener(weakStyleClassListener); 192 193 setId(tc.getId()); 194 setStyle(tc.getStyle()); 195 updateStyleClass(); 196 /* Having TableColumn role parented by TableColumn causes VoiceOver to be unhappy */ 197 setAccessibleRole(AccessibleRole.TABLE_COLUMN); 198 } 199 } 200 201 202 203 /*************************************************************************** 204 * * 205 * Listeners * 206 * * 207 **************************************************************************/ 208 209 final LambdaMultiplePropertyChangeListenerHandler changeListenerHandler; 210 211 private ListChangeListener<TableColumnBase<?,?>> sortOrderListener = c -> { 212 updateSortPosition(); 213 }; 214 215 private ListChangeListener<TableColumnBase<?,?>> visibleLeafColumnsListener = c -> { 216 updateColumnIndex(); 217 updateSortPosition(); 218 }; 219 220 private ListChangeListener<String> styleClassListener = c -> { 221 updateStyleClass(); 222 }; 223 224 private WeakListChangeListener<TableColumnBase<?,?>> weakSortOrderListener = 225 new WeakListChangeListener<TableColumnBase<?,?>>(sortOrderListener); 226 private final WeakListChangeListener<TableColumnBase<?,?>> weakVisibleLeafColumnsListener = 227 new WeakListChangeListener<TableColumnBase<?,?>>(visibleLeafColumnsListener); 228 private final WeakListChangeListener<String> weakStyleClassListener = 229 new WeakListChangeListener<String>(styleClassListener); 230 231 private static final EventHandler<MouseEvent> mousePressedHandler = me -> { 232 if (me.isConsumed()) return; 233 me.consume(); 234 235 TableColumnHeader header = (TableColumnHeader) me.getSource(); 236 header.getTableHeaderRow().columnDragLock = true; 237 238 // pass focus to the table, so that the user immediately sees 239 // the focus rectangle around the table control. 240 header.getTableViewSkin().getSkinnable().requestFocus(); 241 242 if (me.isPrimaryButtonDown() && header.isColumnReorderingEnabled()) { 243 header.columnReorderingStarted(me.getX()); 244 } 245 }; 246 247 private static final EventHandler<MouseEvent> mouseDraggedHandler = me -> { 248 if (me.isConsumed()) return; 249 me.consume(); 250 251 TableColumnHeader header = (TableColumnHeader) me.getSource(); 252 253 if (me.isPrimaryButtonDown() && header.isColumnReorderingEnabled()) { 254 header.columnReordering(me.getSceneX(), me.getSceneY()); 255 } 256 }; 257 258 private static final EventHandler<MouseEvent> mouseReleasedHandler = me -> { 259 if (me.isPopupTrigger()) return; 260 if (me.isConsumed()) return; 261 me.consume(); 262 263 TableColumnHeader header = (TableColumnHeader) me.getSource(); 264 header.getTableHeaderRow().columnDragLock = false; 265 266 TableColumnBase tableColumn = header.getTableColumn(); 267 268 ContextMenu menu = tableColumn.getContextMenu(); 269 if (menu != null && menu.isShowing()) return; 270 if (header.getTableHeaderRow().isReordering() && header.isColumnReorderingEnabled()) { 271 header.columnReorderingComplete(); 272 } else if (me.isStillSincePress()) { 273 header.sortColumn(me.isShiftDown()); 274 } 275 }; 276 277 private static final EventHandler<ContextMenuEvent> contextMenuRequestedHandler = me -> { 278 TableColumnHeader header = (TableColumnHeader) me.getSource(); 279 TableColumnBase tableColumn = header.getTableColumn(); 280 281 ContextMenu menu = tableColumn.getContextMenu(); 282 if (menu != null) { 283 menu.show(header, me.getScreenX(), me.getScreenY()); 284 me.consume(); 285 } 286 }; 287 288 289 290 /*************************************************************************** 291 * * 292 * Properties * 293 * * 294 **************************************************************************/ 295 296 // --- size 297 private DoubleProperty size; 298 private final double getSize() { 299 return size == null ? 20.0 : size.doubleValue(); 300 } 301 private final DoubleProperty sizeProperty() { 302 if (size == null) { 303 size = new StyleableDoubleProperty(20) { 304 @Override 305 protected void invalidated() { 306 double value = get(); 307 if (value <= 0) { 308 if (isBound()) { 309 unbind(); 310 } 311 set(20); 312 throw new IllegalArgumentException("Size cannot be 0 or negative"); 313 } 314 } 315 316 317 318 @Override public Object getBean() { 319 return TableColumnHeader.this; 320 } 321 322 @Override public String getName() { 323 return "size"; 324 } 325 326 @Override public CssMetaData<TableColumnHeader,Number> getCssMetaData() { 327 return StyleableProperties.SIZE; 328 } 329 }; 330 } 331 return size; 332 } 333 334 335 /** 336 * A property that refers to the {@link TableColumnBase} instance that this 337 * header is visually represents. 338 */ 339 // --- table column 340 private ReadOnlyObjectWrapper<TableColumnBase<?,?>> tableColumn = new ReadOnlyObjectWrapper<>(this, "tableColumn"); 341 private final void setTableColumn(TableColumnBase<?,?> column) { 342 tableColumn.set(column); 343 } 344 public final TableColumnBase<?,?> getTableColumn() { 345 return tableColumn.get(); 346 } 347 public final ReadOnlyObjectProperty<TableColumnBase<?,?>> tableColumnProperty() { 348 return tableColumn.getReadOnlyProperty(); 349 } 350 351 352 353 /*************************************************************************** 354 * * 355 * Public API * 356 * * 357 **************************************************************************/ 358 359 /** {@inheritDoc} */ 360 @Override protected void layoutChildren() { 361 if (isSizeDirty) { 362 resize(getTableColumn().getWidth(), getHeight()); 363 isSizeDirty = false; 364 } 365 366 double sortWidth = 0; 367 double w = snapSizeX(getWidth()) - (snappedLeftInset() + snappedRightInset()); 368 double h = getHeight() - (snappedTopInset() + snappedBottomInset()); 369 double x = w; 370 371 // a bit hacky, but we REALLY don't want the arrow shape to fluctuate 372 // in size 373 if (arrow != null) { 374 arrow.setMaxSize(arrow.prefWidth(-1), arrow.prefHeight(-1)); 375 } 376 377 if (sortArrow != null && sortArrow.isVisible()) { 378 sortWidth = sortArrow.prefWidth(-1); 379 x -= sortWidth; 380 sortArrow.resize(sortWidth, sortArrow.prefHeight(-1)); 381 positionInArea(sortArrow, x, snappedTopInset(), 382 sortWidth, h, 0, HPos.CENTER, VPos.CENTER); 383 } 384 385 if (label != null) { 386 double labelWidth = w - sortWidth; 387 label.resizeRelocate(snappedLeftInset(), 0, labelWidth, getHeight()); 388 } 389 } 390 391 /** {@inheritDoc} */ 392 @Override protected double computePrefWidth(double height) { 393 if (getNestedColumnHeader() != null) { 394 double width = getNestedColumnHeader().prefWidth(height); 395 396 if (getTableColumn() != null) { 397 TableColumnBaseHelper.setWidth(getTableColumn(), width); 398 } 399 400 return width; 401 } else if (getTableColumn() != null && getTableColumn().isVisible()) { 402 return getTableColumn().getWidth(); 403 } 404 405 return 0; 406 } 407 408 /** {@inheritDoc} */ 409 @Override protected double computeMinHeight(double width) { 410 return label == null ? 0 : label.minHeight(width); 411 } 412 413 /** {@inheritDoc} */ 414 @Override protected double computePrefHeight(double width) { 415 if (getTableColumn() == null) return 0; 416 return Math.max(getSize(), label.prefHeight(-1)); 417 } 418 419 /** {@inheritDoc} */ 420 @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { 421 return getClassCssMetaData(); 422 } 423 424 /** {@inheritDoc} */ 425 @Override public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) { 426 switch (attribute) { 427 case INDEX: return getIndex(getTableColumn()); 428 case TEXT: return getTableColumn() != null ? getTableColumn().getText() : null; 429 default: return super.queryAccessibleAttribute(attribute, parameters); 430 } 431 } 432 433 434 435 /*************************************************************************** 436 * * 437 * Private Implementation * 438 * * 439 **************************************************************************/ 440 441 TableViewSkinBase<?,?,?,?,TableColumnBase<?,?>> getTableViewSkin() { 442 return skin; 443 } 444 445 NestedTableColumnHeader getNestedColumnHeader() { return nestedColumnHeader; } 446 void setNestedColumnHeader(NestedTableColumnHeader nch) { nestedColumnHeader = nch; } 447 448 TableHeaderRow getTableHeaderRow() { return tableHeaderRow; } 449 void setTableHeaderRow(TableHeaderRow thr) { tableHeaderRow = thr; } 450 451 NestedTableColumnHeader getParentHeader() { return parentHeader; } 452 void setParentHeader(NestedTableColumnHeader ph) { parentHeader = ph; } 453 454 // RT-29682: When the sortable property of a TableColumnBase changes this 455 // may impact other TableColumnHeaders, as they may need to change their 456 // sort order representation. Rather than install listeners across all 457 // TableColumn in the sortOrder list for their sortable property, we simply 458 // update the sortPosition of all headers whenever the sortOrder property 459 // changes, assuming the column is within the sortOrder list. 460 private void updateAllHeaders(TableColumnHeader header) { 461 if (header instanceof NestedTableColumnHeader) { 462 List<TableColumnHeader> children = ((NestedTableColumnHeader)header).getColumnHeaders(); 463 for (int i = 0; i < children.size(); i++) { 464 updateAllHeaders(children.get(i)); 465 } 466 } else { 467 header.updateSortPosition(); 468 } 469 } 470 471 private void updateStyleClass() { 472 // For now we leave the 'column-header' style class intact so that the 473 // appropriate border styles are shown, etc. 474 getStyleClass().setAll("column-header"); 475 getStyleClass().addAll(getTableColumn().getStyleClass()); 476 } 477 478 private void updateScene() { 479 // RT-17684: If the TableColumn widths are all currently the default, 480 // we attempt to 'auto-size' based on the preferred width of the first 481 // n rows (we can't do all rows, as that could conceivably be an unlimited 482 // number of rows retrieved from a very slow (e.g. remote) data source. 483 // Obviously, the bigger the value of n, the more likely the default 484 // width will be suitable for most values in the column 485 final int n = 30; 486 if (! autoSizeComplete) { 487 if (getTableColumn() == null || getTableColumn().getWidth() != DEFAULT_COLUMN_WIDTH || getScene() == null) { 488 return; 489 } 490 doColumnAutoSize(getTableColumn(), n); 491 autoSizeComplete = true; 492 } 493 } 494 495 void dispose() { 496 TableViewSkinBase skin = getTableViewSkin(); 497 if (skin != null) { 498 TableSkinUtils.getVisibleLeafColumns(skin).removeListener(weakVisibleLeafColumnsListener); 499 TableSkinUtils.getSortOrder(skin).removeListener(weakSortOrderListener); 500 } 501 502 changeListenerHandler.dispose(); 503 } 504 505 private boolean isSortingEnabled() { 506 // this used to check if ! PlatformUtil.isEmbedded(), but has been changed 507 // to always return true (for now), as we want to support column sorting 508 // everywhere 509 return true; 510 } 511 512 private boolean isColumnReorderingEnabled() { 513 // we only allow for column reordering if there are more than one column, 514 return !Properties.IS_TOUCH_SUPPORTED && TableSkinUtils.getVisibleLeafColumns(getTableViewSkin()).size() > 1; 515 } 516 517 private void initUI() { 518 // TableColumn will be null if we are dealing with the root NestedTableColumnHeader 519 if (getTableColumn() == null) return; 520 521 // set up mouse events 522 setOnMousePressed(mousePressedHandler); 523 setOnMouseDragged(mouseDraggedHandler); 524 setOnDragDetected(event -> event.consume()); 525 setOnContextMenuRequested(contextMenuRequestedHandler); 526 setOnMouseReleased(mouseReleasedHandler); 527 528 // --- label 529 label = new Label(); 530 label.setText(getTableColumn().getText()); 531 label.setGraphic(getTableColumn().getGraphic()); 532 label.setVisible(getTableColumn().isVisible()); 533 534 // ---- container for the sort arrow (which is not supported on embedded 535 // platforms) 536 if (isSortingEnabled()) { 537 // put together the grid 538 updateSortGrid(); 539 } 540 } 541 542 private void doColumnAutoSize(TableColumnBase<?,?> column, int cellsToMeasure) { 543 double prefWidth = column.getPrefWidth(); 544 545 // if the prefWidth has been set, we do _not_ autosize columns 546 if (prefWidth == DEFAULT_COLUMN_WIDTH) { 547 TableSkinUtils.resizeColumnToFitContent(getTableViewSkin(), column, cellsToMeasure); 548 // getTableViewSkin().resizeColumnToFitContent(column, cellsToMeasure); 549 } 550 } 551 552 private void updateSortPosition() { 553 this.sortPos = ! getTableColumn().isSortable() ? -1 : getSortPosition(); 554 updateSortGrid(); 555 } 556 557 private void updateSortGrid() { 558 // Fix for RT-14488 559 if (this instanceof NestedTableColumnHeader) return; 560 561 getChildren().clear(); 562 getChildren().add(label); 563 564 // we do not support sorting in embedded devices 565 if (! isSortingEnabled()) return; 566 567 isSortColumn = sortPos != -1; 568 if (! isSortColumn) { 569 if (sortArrow != null) { 570 sortArrow.setVisible(false); 571 } 572 return; 573 } 574 575 // RT-28016: if the tablecolumn is not a visible leaf column, we should ignore this 576 int visibleLeafIndex = TableSkinUtils.getVisibleLeafIndex(skin,getTableColumn()); 577 if (visibleLeafIndex == -1) return; 578 579 final int sortColumnCount = getVisibleSortOrderColumnCount(); 580 boolean showSortOrderDots = sortPos <= 3 && sortColumnCount > 1; 581 582 Node _sortArrow = null; 583 if (getTableColumn().getSortNode() != null) { 584 _sortArrow = getTableColumn().getSortNode(); 585 getChildren().add(_sortArrow); 586 } else { 587 GridPane sortArrowGrid = new GridPane(); 588 _sortArrow = sortArrowGrid; 589 sortArrowGrid.setPadding(new Insets(0, 3, 0, 0)); 590 getChildren().add(sortArrowGrid); 591 592 // if we are here, and the sort arrow is null, we better create it 593 if (arrow == null) { 594 arrow = new Region(); 595 arrow.getStyleClass().setAll("arrow"); 596 arrow.setVisible(true); 597 arrow.setRotate(isAscending(getTableColumn()) ? 180.0F : 0.0F); 598 changeListenerHandler.registerChangeListener(getSortTypeProperty(getTableColumn()), e -> { 599 updateSortGrid(); 600 if (arrow != null) { 601 arrow.setRotate(isAscending(getTableColumn()) ? 180 : 0.0); 602 } 603 }); 604 } 605 606 arrow.setVisible(isSortColumn); 607 608 if (sortPos > 2) { 609 if (sortOrderLabel == null) { 610 // ---- sort order label (for sort positions greater than 3) 611 sortOrderLabel = new Label(); 612 sortOrderLabel.getStyleClass().add("sort-order"); 613 } 614 615 // only show the label if the sortPos is greater than 3 (for sortPos 616 // values less than three, we show the sortOrderDots instead) 617 sortOrderLabel.setText("" + (sortPos + 1)); 618 sortOrderLabel.setVisible(sortColumnCount > 1); 619 620 // update the grid layout 621 sortArrowGrid.add(arrow, 1, 1); 622 GridPane.setHgrow(arrow, Priority.NEVER); 623 GridPane.setVgrow(arrow, Priority.NEVER); 624 sortArrowGrid.add(sortOrderLabel, 2, 1); 625 } else if (showSortOrderDots) { 626 if (sortOrderDots == null) { 627 sortOrderDots = new HBox(0); 628 sortOrderDots.getStyleClass().add("sort-order-dots-container"); 629 } 630 631 // show the sort order dots 632 boolean isAscending = isAscending(getTableColumn()); 633 int arrowRow = isAscending ? 1 : 2; 634 int dotsRow = isAscending ? 2 : 1; 635 636 sortArrowGrid.add(arrow, 1, arrowRow); 637 GridPane.setHalignment(arrow, HPos.CENTER); 638 sortArrowGrid.add(sortOrderDots, 1, dotsRow); 639 640 updateSortOrderDots(sortPos); 641 } else { 642 // only show the arrow 643 sortArrowGrid.add(arrow, 1, 1); 644 GridPane.setHgrow(arrow, Priority.NEVER); 645 GridPane.setVgrow(arrow, Priority.ALWAYS); 646 } 647 } 648 649 sortArrow = _sortArrow; 650 if (sortArrow != null) { 651 sortArrow.setVisible(isSortColumn); 652 } 653 654 requestLayout(); 655 } 656 657 private void updateSortOrderDots(int sortPos) { 658 double arrowWidth = arrow.prefWidth(-1); 659 660 sortOrderDots.getChildren().clear(); 661 662 for (int i = 0; i <= sortPos; i++) { 663 Region r = new Region(); 664 r.getStyleClass().add("sort-order-dot"); 665 666 String sortTypeName = getSortTypeName(getTableColumn()); 667 if (sortTypeName != null && ! sortTypeName.isEmpty()) { 668 r.getStyleClass().add(sortTypeName.toLowerCase(Locale.ROOT)); 669 } 670 671 sortOrderDots.getChildren().add(r); 672 673 // RT-34914: fine tuning the placement of the sort dots. We could have gone to a custom layout, but for now 674 // this works fine. 675 if (i < sortPos) { 676 Region spacer = new Region(); 677 double lp = sortPos == 1 ? 1 : 0; 678 spacer.setPadding(new Insets(0, 1, 0, lp)); 679 sortOrderDots.getChildren().add(spacer); 680 } 681 } 682 683 sortOrderDots.setAlignment(Pos.TOP_CENTER); 684 sortOrderDots.setMaxWidth(arrowWidth); 685 } 686 687 // Package for testing purposes only. 688 void moveColumn(TableColumnBase column, final int newColumnPos) { 689 if (column == null || newColumnPos < 0) return; 690 691 ObservableList<TableColumnBase<?,?>> columns = getColumns(column); 692 693 final int columnsCount = columns.size(); 694 final int currentPos = columns.indexOf(column); 695 696 int actualNewColumnPos = newColumnPos; 697 698 // Fix for RT-35141: We need to account for hidden columns. 699 // We keep iterating until we see 'requiredVisibleColumns' number of visible columns 700 final int requiredVisibleColumns = actualNewColumnPos; 701 int visibleColumnsSeen = 0; 702 for (int i = 0; i < columnsCount; i++) { 703 if (visibleColumnsSeen == (requiredVisibleColumns + 1)) { 704 break; 705 } 706 707 if (columns.get(i).isVisible()) { 708 visibleColumnsSeen++; 709 } else { 710 actualNewColumnPos++; 711 } 712 } 713 // --- end of RT-35141 fix 714 715 if (actualNewColumnPos >= columnsCount) { 716 actualNewColumnPos = columnsCount - 1; 717 } else if (actualNewColumnPos < 0) { 718 actualNewColumnPos = 0; 719 } 720 721 if (actualNewColumnPos == currentPos) return; 722 723 List<TableColumnBase<?,?>> tempList = new ArrayList<>(columns); 724 tempList.remove(column); 725 tempList.add(actualNewColumnPos, column); 726 727 columns.setAll(tempList); 728 } 729 730 private ObservableList<TableColumnBase<?,?>> getColumns(TableColumnBase column) { 731 return column.getParentColumn() == null ? 732 TableSkinUtils.getColumns(getTableViewSkin()) : 733 column.getParentColumn().getColumns(); 734 } 735 736 private int getIndex(TableColumnBase<?,?> column) { 737 if (column == null) return -1; 738 739 ObservableList<? extends TableColumnBase<?,?>> columns = getColumns(column); 740 741 int index = -1; 742 for (int i = 0; i < columns.size(); i++) { 743 TableColumnBase<?,?> _column = columns.get(i); 744 if (! _column.isVisible()) continue; 745 746 index++; 747 if (column.equals(_column)) break; 748 } 749 750 return index; 751 } 752 753 private void updateColumnIndex() { 754 // TableView tv = getTableView(); 755 TableViewSkinBase skin = getTableViewSkin(); 756 TableColumnBase tc = getTableColumn(); 757 columnIndex = skin == null || tc == null ? -1 :TableSkinUtils.getVisibleLeafIndex(skin,tc); 758 759 // update the pseudo class state regarding whether this is the last 760 // visible cell (i.e. the right-most). 761 isLastVisibleColumn = getTableColumn() != null && 762 columnIndex != -1 && 763 columnIndex == TableSkinUtils.getVisibleLeafColumns(skin).size() - 1; 764 pseudoClassStateChanged(PSEUDO_CLASS_LAST_VISIBLE, isLastVisibleColumn); 765 } 766 767 private void sortColumn(final boolean addColumn) { 768 if (! isSortingEnabled()) return; 769 770 // we only allow sorting on the leaf columns and columns 771 // that actually have comparators defined, and are sortable 772 if (getTableColumn() == null || getTableColumn().getColumns().size() != 0 || getTableColumn().getComparator() == null || !getTableColumn().isSortable()) return; 773 // final int sortPos = getTable().getSortOrder().indexOf(column); 774 // final boolean isSortColumn = sortPos != -1; 775 776 final ObservableList<TableColumnBase<?,?>> sortOrder = TableSkinUtils.getSortOrder(skin); 777 778 // addColumn is true e.g. when the user is holding down Shift 779 if (addColumn) { 780 if (!isSortColumn) { 781 setSortType(getTableColumn(), TableColumn.SortType.ASCENDING); 782 sortOrder.add(getTableColumn()); 783 } else if (isAscending(getTableColumn())) { 784 setSortType(getTableColumn(), TableColumn.SortType.DESCENDING); 785 } else { 786 int i = sortOrder.indexOf(getTableColumn()); 787 if (i != -1) { 788 sortOrder.remove(i); 789 } 790 } 791 } else { 792 // the user has clicked on a column header - we should add this to 793 // the TableView sortOrder list if it isn't already there. 794 if (isSortColumn && sortOrder.size() == 1) { 795 // the column is already being sorted, and it's the only column. 796 // We therefore move through the 2nd or 3rd states: 797 // 1st click: sort ascending 798 // 2nd click: sort descending 799 // 3rd click: natural sorting (sorting is switched off) 800 if (isAscending(getTableColumn())) { 801 setSortType(getTableColumn(), TableColumn.SortType.DESCENDING); 802 } else { 803 // remove from sort 804 sortOrder.remove(getTableColumn()); 805 } 806 } else if (isSortColumn) { 807 // the column is already being used to sort, so we toggle its 808 // sortAscending property, and also make the column become the 809 // primary sort column 810 if (isAscending(getTableColumn())) { 811 setSortType(getTableColumn(), TableColumn.SortType.DESCENDING); 812 } else if (isDescending(getTableColumn())) { 813 setSortType(getTableColumn(), TableColumn.SortType.ASCENDING); 814 } 815 816 // to prevent multiple sorts, we make a copy of the sort order 817 // list, moving the column value from the current position to 818 // its new position at the front of the list 819 List<TableColumnBase<?,?>> sortOrderCopy = new ArrayList<TableColumnBase<?,?>>(sortOrder); 820 sortOrderCopy.remove(getTableColumn()); 821 sortOrderCopy.add(0, getTableColumn()); 822 sortOrder.setAll(getTableColumn()); 823 } else { 824 // add to the sort order, in ascending form 825 setSortType(getTableColumn(), TableColumn.SortType.ASCENDING); 826 sortOrder.setAll(getTableColumn()); 827 } 828 } 829 } 830 831 // Because it is possible that some columns are in the sortOrder list but are 832 // not themselves sortable, we cannot just do sortOrderList.indexOf(column). 833 // Therefore, this method does the proper work required of iterating through 834 // and ignoring non-sortable (and null) columns in the sortOrder list. 835 private int getSortPosition() { 836 if (getTableColumn() == null) { 837 return -1; 838 } 839 840 final List<TableColumnBase> sortOrder = getVisibleSortOrderColumns(); 841 int pos = 0; 842 for (int i = 0; i < sortOrder.size(); i++) { 843 TableColumnBase _tc = sortOrder.get(i); 844 845 if (getTableColumn().equals(_tc)) { 846 return pos; 847 } 848 849 pos++; 850 } 851 852 return -1; 853 } 854 855 private List<TableColumnBase> getVisibleSortOrderColumns() { 856 final ObservableList<TableColumnBase<?,?>> sortOrder = TableSkinUtils.getSortOrder(skin); 857 858 List<TableColumnBase> visibleSortOrderColumns = new ArrayList<>(); 859 for (int i = 0; i < sortOrder.size(); i++) { 860 TableColumnBase _tc = sortOrder.get(i); 861 if (_tc == null || ! _tc.isSortable() || ! _tc.isVisible()) { 862 continue; 863 } 864 865 visibleSortOrderColumns.add(_tc); 866 } 867 868 return visibleSortOrderColumns; 869 } 870 871 // as with getSortPosition above, this method iterates through the sortOrder 872 // list ignoring the null and non-sortable columns, so that we get the correct 873 // number of columns in the sortOrder list. 874 private int getVisibleSortOrderColumnCount() { 875 return getVisibleSortOrderColumns().size(); 876 } 877 878 879 880 /*************************************************************************** 881 * * 882 * Private Implementation: Column Reordering * 883 * * 884 **************************************************************************/ 885 886 // package for testing 887 void columnReorderingStarted(double dragOffset) { 888 if (! getTableColumn().isReorderable()) return; 889 890 // Used to ensure the column ghost is positioned relative to where the 891 // user clicked on the column header 892 this.dragOffset = dragOffset; 893 894 // Note here that we only allow for reordering of 'root' columns 895 getTableHeaderRow().setReorderingColumn(getTableColumn()); 896 getTableHeaderRow().setReorderingRegion(this); 897 } 898 899 // package for testing 900 void columnReordering(double sceneX, double sceneY) { 901 if (! getTableColumn().isReorderable()) return; 902 903 // this is for handling the column drag to reorder columns. 904 // It shows a line to indicate where the 'drop' will be. 905 906 // indicate that we've started dragging so that the dragging 907 // line overlay is shown 908 getTableHeaderRow().setReordering(true); 909 910 // Firstly we need to determine where to draw the line. 911 // Find which column we're over 912 TableColumnHeader hoverHeader = null; 913 914 // x represents where the mouse is relative to the parent 915 // NestedTableColumnHeader 916 final double x = getParentHeader().sceneToLocal(sceneX, sceneY).getX(); 917 918 // calculate where the ghost column header should be 919 double dragX = getTableViewSkin().getSkinnable().sceneToLocal(sceneX, sceneY).getX() - dragOffset; 920 getTableHeaderRow().setDragHeaderX(dragX); 921 922 double startX = 0; 923 double endX = 0; 924 double headersWidth = 0; 925 newColumnPos = 0; 926 for (TableColumnHeader header : getParentHeader().getColumnHeaders()) { 927 if (! header.isVisible()) continue; 928 929 double headerWidth = header.prefWidth(-1); 930 headersWidth += headerWidth; 931 932 startX = header.getBoundsInParent().getMinX(); 933 endX = startX + headerWidth; 934 935 if (x >= startX && x < endX) { 936 hoverHeader = header; 937 break; 938 } 939 newColumnPos++; 940 } 941 942 // hoverHeader will be null if the drag occurs outside of the 943 // tableview. In this case we handle the newColumnPos specially 944 // and then short-circuit. This results in the drop action 945 // resulting in the correct result (the column will drop at 946 // the start or end of the table). 947 if (hoverHeader == null) { 948 newColumnPos = x > headersWidth ? (getParentHeader().getColumns().size() - 1) : 0; 949 return; 950 } 951 952 // This is the x-axis value midway through hoverHeader. It's 953 // used to determine whether the drop should be to the left 954 // or the right of hoverHeader. 955 double midPoint = startX + (endX - startX) / 2; 956 boolean beforeMidPoint = x <= midPoint; 957 958 // Based on where the mouse actually is, we have to shuffle 959 // where we want the column to end up. This code handles that. 960 int currentPos = getIndex(getTableColumn()); 961 newColumnPos += newColumnPos > currentPos && beforeMidPoint ? 962 -1 : (newColumnPos < currentPos && !beforeMidPoint ? 1 : 0); 963 964 double lineX = getTableHeaderRow().sceneToLocal(hoverHeader.localToScene(hoverHeader.getBoundsInLocal())).getMinX(); 965 lineX = lineX + ((beforeMidPoint) ? (0) : (hoverHeader.getWidth())); 966 967 if (lineX >= -0.5 && lineX <= getTableViewSkin().getSkinnable().getWidth()) { 968 columnReorderLine.setTranslateX(lineX); 969 970 // then if this is the first event, we set the property to true 971 // so that the line becomes visible until the drop is completed. 972 // We also set reordering to true so that the various reordering 973 // effects become visible (ghost, transparent overlay, etc). 974 columnReorderLine.setVisible(true); 975 } 976 977 getTableHeaderRow().setReordering(true); 978 } 979 980 // package for testing 981 void columnReorderingComplete() { 982 if (! getTableColumn().isReorderable()) return; 983 984 // Move col from where it is now to the new position. 985 moveColumn(getTableColumn(), newColumnPos); 986 987 // cleanup 988 columnReorderLine.setTranslateX(0.0F); 989 columnReorderLine.setLayoutX(0.0F); 990 newColumnPos = 0; 991 992 getTableHeaderRow().setReordering(false); 993 columnReorderLine.setVisible(false); 994 getTableHeaderRow().setReorderingColumn(null); 995 getTableHeaderRow().setReorderingRegion(null); 996 dragOffset = 0.0F; 997 } 998 999 double getDragRectHeight() { 1000 return getHeight(); 1001 } 1002 1003 // Used to test whether this column header properly represents the given column. 1004 // In particular, whether it has child column headers for all child columns 1005 boolean represents(TableColumnBase<?, ?> column) { 1006 if (!column.getColumns().isEmpty()) { 1007 // this column has children, but we are in a TableColumnHeader instance, 1008 // so the match is bad. 1009 return false; 1010 } 1011 return column == getTableColumn(); 1012 } 1013 1014 1015 1016 /*************************************************************************** 1017 * * 1018 * Stylesheet Handling * 1019 * * 1020 **************************************************************************/ 1021 1022 private static final PseudoClass PSEUDO_CLASS_LAST_VISIBLE = 1023 PseudoClass.getPseudoClass("last-visible"); 1024 1025 /* 1026 * Super-lazy instantiation pattern from Bill Pugh. 1027 */ 1028 private static class StyleableProperties { 1029 private static final CssMetaData<TableColumnHeader,Number> SIZE = 1030 new CssMetaData<TableColumnHeader,Number>("-fx-size", 1031 SizeConverter.getInstance(), 20.0) { 1032 1033 @Override 1034 public boolean isSettable(TableColumnHeader n) { 1035 return n.size == null || !n.size.isBound(); 1036 } 1037 1038 @Override 1039 public StyleableProperty<Number> getStyleableProperty(TableColumnHeader n) { 1040 return (StyleableProperty<Number>)(WritableValue<Number>)n.sizeProperty(); 1041 } 1042 }; 1043 1044 private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; 1045 static { 1046 1047 final List<CssMetaData<? extends Styleable, ?>> styleables = 1048 new ArrayList<CssMetaData<? extends Styleable, ?>>(Region.getClassCssMetaData()); 1049 styleables.add(SIZE); 1050 STYLEABLES = Collections.unmodifiableList(styleables); 1051 1052 } 1053 } 1054 1055 /** 1056 * Returnst he CssMetaData associated with this class, which may include the 1057 * CssMetaData of its super classes. 1058 */ 1059 public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { 1060 return StyleableProperties.STYLEABLES; 1061 } 1062 }