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 /* 27 * To change this template, choose Tools | Templates 28 * and open the template in the editor. 29 */ 30 31 package com.sun.javafx.scene.control.skin; 32 33 import com.sun.javafx.scene.NodeHelper; 34 import com.sun.javafx.scene.control.behavior.TextBinding; 35 import com.sun.javafx.scene.text.TextLayout; 36 import com.sun.javafx.tk.Toolkit; 37 import javafx.application.ConditionalFeature; 38 import javafx.application.Platform; 39 import javafx.beans.InvalidationListener; 40 import javafx.beans.Observable; 41 import javafx.beans.value.ObservableValue; 42 import javafx.collections.ObservableList; 43 import javafx.geometry.Bounds; 44 import javafx.geometry.HPos; 45 import javafx.geometry.Point2D; 46 import javafx.geometry.VPos; 47 import javafx.scene.Scene; 48 import javafx.scene.control.ContextMenu; 49 import javafx.scene.control.MenuItem; 50 import javafx.scene.control.OverrunStyle; 51 import com.sun.javafx.scene.control.ContextMenuContent; 52 import com.sun.javafx.scene.text.FontHelper; 53 import java.net.URL; 54 import javafx.scene.input.KeyCombination; 55 import javafx.scene.input.Mnemonic; 56 import javafx.scene.paint.Color; 57 import javafx.scene.text.Font; 58 import javafx.scene.text.Text; 59 import javafx.scene.text.TextBoundsType; 60 import javafx.scene.text.HitInfo; 61 62 import java.text.Bidi; 63 import java.util.Locale; 64 import java.util.function.Consumer; 65 66 import static javafx.scene.control.OverrunStyle.CENTER_ELLIPSIS; 67 import static javafx.scene.control.OverrunStyle.CENTER_WORD_ELLIPSIS; 68 import static javafx.scene.control.OverrunStyle.CLIP; 69 import static javafx.scene.control.OverrunStyle.ELLIPSIS; 70 import static javafx.scene.control.OverrunStyle.LEADING_ELLIPSIS; 71 import static javafx.scene.control.OverrunStyle.LEADING_WORD_ELLIPSIS; 72 import static javafx.scene.control.OverrunStyle.WORD_ELLIPSIS; 73 74 /** 75 * BE REALLY CAREFUL WITH RESTORING OR RESETTING STATE OF helper NODE AS LEFTOVER 76 * STATE CAUSES REALLY ODD NASTY BUGS! 77 * 78 * We expect all methods to set the Font property of helper but other than that 79 * any properties set should be restored to defaults. 80 */ 81 public class Utils { 82 83 static final Text helper = new Text(); 84 static final double DEFAULT_WRAPPING_WIDTH = helper.getWrappingWidth(); 85 static final double DEFAULT_LINE_SPACING = helper.getLineSpacing(); 86 static final String DEFAULT_TEXT = helper.getText(); 87 static final TextBoundsType DEFAULT_BOUNDS_TYPE = helper.getBoundsType(); 88 89 /* Using TextLayout directly for simple text measurement. 90 * Instead of restoring the TextLayout attributes to default values 91 * (each renders the TextLayout unable to efficiently cache layout data). 92 * It always sets all the attributes pertinent to calculation being performed. 93 * Note that lineSpacing and boundsType are important when computing the height 94 * but irrelevant when computing the width. 95 * 96 * Note: This code assumes that TextBoundsType#VISUAL is never used by controls. 97 * */ 98 static final TextLayout layout = Toolkit.getToolkit().getTextLayoutFactory().createLayout(); 99 100 public static double getAscent(Font font, TextBoundsType boundsType) { 101 layout.setContent("", FontHelper.getNativeFont(font)); 102 layout.setWrapWidth(0); 103 layout.setLineSpacing(0); 104 if (boundsType == TextBoundsType.LOGICAL_VERTICAL_CENTER) { 105 layout.setBoundsType(TextLayout.BOUNDS_CENTER); 106 } else { 107 layout.setBoundsType(0); 108 } 109 return -layout.getBounds().getMinY(); 110 } 111 112 public static double getLineHeight(Font font, TextBoundsType boundsType) { 113 layout.setContent("", FontHelper.getNativeFont(font)); 114 layout.setWrapWidth(0); 115 layout.setLineSpacing(0); 116 if (boundsType == TextBoundsType.LOGICAL_VERTICAL_CENTER) { 117 layout.setBoundsType(TextLayout.BOUNDS_CENTER); 118 } else { 119 layout.setBoundsType(0); 120 } 121 122 // RT-37092: Use the line bounds specifically, to include font leading. 123 return layout.getLines()[0].getBounds().getHeight(); 124 } 125 126 public static double computeTextWidth(Font font, String text, double wrappingWidth) { 127 layout.setContent(text != null ? text : "", FontHelper.getNativeFont(font)); 128 layout.setWrapWidth((float)wrappingWidth); 129 return layout.getBounds().getWidth(); 130 } 131 132 public static double computeTextHeight(Font font, String text, double wrappingWidth, TextBoundsType boundsType) { 133 return computeTextHeight(font, text, wrappingWidth, 0, boundsType); 134 } 135 136 @SuppressWarnings("deprecation") 137 public static double computeTextHeight(Font font, String text, double wrappingWidth, double lineSpacing, TextBoundsType boundsType) { 138 layout.setContent(text != null ? text : "", FontHelper.getNativeFont(font)); 139 layout.setWrapWidth((float)wrappingWidth); 140 layout.setLineSpacing((float)lineSpacing); 141 if (boundsType == TextBoundsType.LOGICAL_VERTICAL_CENTER) { 142 layout.setBoundsType(TextLayout.BOUNDS_CENTER); 143 } else { 144 layout.setBoundsType(0); 145 } 146 return layout.getBounds().getHeight(); 147 } 148 149 public static int computeTruncationIndex(Font font, String text, double width) { 150 helper.setText(text); 151 helper.setFont(font); 152 helper.setWrappingWidth(0); 153 helper.setLineSpacing(0); 154 // The -2 is a fudge to make sure the result more often matches 155 // what we get from using computeTextWidth instead. It's not yet 156 // clear what causes the small discrepancies. 157 Bounds bounds = helper.getLayoutBounds(); 158 Point2D endPoint = new Point2D(width - 2, bounds.getMinY() + bounds.getHeight() / 2); 159 final int index = helper.hitTest(endPoint).getCharIndex(); 160 // RESTORE STATE 161 helper.setWrappingWidth(DEFAULT_WRAPPING_WIDTH); 162 helper.setLineSpacing(DEFAULT_LINE_SPACING); 163 helper.setText(DEFAULT_TEXT); 164 return index; 165 } 166 167 public static String computeClippedText(Font font, String text, double width, 168 OverrunStyle type, String ellipsisString) { 169 if (font == null) { 170 throw new IllegalArgumentException("Must specify a font"); 171 } 172 OverrunStyle style = (type == null || type == CLIP) ? ELLIPSIS : type; 173 final String ellipsis = (type == CLIP) ? "" : ellipsisString; 174 // if the text is empty or null or no ellipsis, then it always fits 175 if (text == null || "".equals(text)) { 176 return text; 177 } 178 // if the string width is < the available width, then it fits and 179 // doesn't need to be clipped. We use a double point comparison 180 // of 0.001 (1/1000th of a pixel) to account for any numerical 181 // discrepancies introduced when the available width was calculated. 182 // MenuItemSkinBase.doLayout, for example, does a number of double 183 // point operations when computing the available width. 184 final double stringWidth = computeTextWidth(font, text, 0); 185 if (stringWidth - width < 0.0010F) { 186 return text; 187 } 188 // the width used by the ellipsis string 189 final double ellipsisWidth = computeTextWidth(font, ellipsis, 0); 190 // the available maximum width to fit chars into. This is essentially 191 // the width minus the space required for the ellipsis string 192 final double availableWidth = width - ellipsisWidth; 193 194 if (width < ellipsisWidth) { 195 // The ellipsis doesn't fit. 196 return ""; 197 } 198 199 // if we got here, then we must clip the text with an ellipsis. 200 // this can be pretty expensive depending on whether "complex" text 201 // layout needs to be taken into account. So each ellipsis option has 202 // to take into account two code paths: the easy way and the correct 203 // way. This is flagged by the "complexLayout" boolean 204 // TODO make sure this function call takes into account ligatures, kerning, 205 // and such as that will change the layout characteristics of the text 206 // and will require a full complex layout 207 // TODO since we don't have all the stuff available in FX to determine 208 // complex text, I'm going to for now assume complex text is always false. 209 final boolean complexLayout = false; 210 //requiresComplexLayout(font, text); 211 212 // generally all we want to do is count characters and add their widths. 213 // For ellipsis that breaks on words, we do NOT want to include any 214 // hanging whitespace. 215 if (style == ELLIPSIS || 216 style == WORD_ELLIPSIS || 217 style == LEADING_ELLIPSIS || 218 style == LEADING_WORD_ELLIPSIS) { 219 220 final boolean wordTrim = 221 (style == WORD_ELLIPSIS || style == LEADING_WORD_ELLIPSIS); 222 String substring; 223 if (complexLayout) { 224 // AttributedString a = new AttributedString(text); 225 // LineBreakMeasurer m = new LineBreakMeasurer(a.getIterator(), frc); 226 // substring = text.substring(0, m.nextOffset((double)availableWidth)); 227 } else { 228 // RT-23458: Use a faster algorithm for the most common case 229 // where truncation happens at the end, i.e. for ELLIPSIS and 230 // CLIP, but not for other cases such as WORD_ELLIPSIS, etc. 231 if (style == ELLIPSIS && !new Bidi(text, Bidi.DIRECTION_LEFT_TO_RIGHT).isMixed()) { 232 int hit = computeTruncationIndex(font, text, width - ellipsisWidth); 233 if (hit < 0 || hit >= text.length()) { 234 return text; 235 } else { 236 return text.substring(0, hit) + ellipsis; 237 } 238 } 239 240 // simply total up the widths of all chars to determine how many 241 // will fit in the available space. Remember the last whitespace 242 // encountered so that if we're breaking on words we can trim 243 // and omit it. 244 double total = 0.0F; 245 int whitespaceIndex = -1; 246 // at the termination of the loop, index will be one past the 247 // end of the substring 248 int index = 0; 249 int start = (style == LEADING_ELLIPSIS || style == LEADING_WORD_ELLIPSIS) ? (text.length() - 1) : (0); 250 int end = (start == 0) ? (text.length() - 1) : 0; 251 int stepValue = (start == 0) ? 1 : -1; 252 boolean done = (start == 0) ? start > end : start < end; 253 for (int i = start; !done ; i += stepValue) { 254 index = i; 255 char c = text.charAt(index); 256 total = computeTextWidth(font, 257 (start == 0) ? text.substring(0, i + 1) 258 : text.substring(i, start + 1), 259 0); 260 if (Character.isWhitespace(c)) { 261 whitespaceIndex = index; 262 } 263 if (total > availableWidth) { 264 break; 265 } 266 done = start == 0? i >= end : i <= end; 267 } 268 final boolean fullTrim = !wordTrim || whitespaceIndex == -1; 269 substring = (start == 0) ? 270 (text.substring(0, fullTrim ? index : whitespaceIndex)) : 271 (text.substring((fullTrim ? index : whitespaceIndex) + 1)); 272 assert(!text.equals(substring)); 273 } 274 if (style == ELLIPSIS || style == WORD_ELLIPSIS) { 275 return substring + ellipsis; 276 } else { 277 //style is LEADING_ELLIPSIS or LEADING_WORD_ELLIPSIS 278 return ellipsis + substring; 279 } 280 } else { 281 // these two indexes are INCLUSIVE not exclusive 282 int leadingIndex = 0; 283 int trailingIndex = 0; 284 int leadingWhitespace = -1; 285 int trailingWhitespace = -1; 286 // The complex case is going to be killer. What I have to do is 287 // read all the chars from the left up to the leadingIndex, 288 // and all the chars from the right up to the trailingIndex, 289 // and sum those together to get my total. That is, I cannot have 290 // a running total but must retotal the cummulative chars each time 291 if (complexLayout) { 292 } else /* double leadingTotal = 0; 293 double trailingTotal = 0; 294 for (int i=0; i<text.length(); i++) { 295 double total = computeStringWidth(metrics, text.substring(0, i)); 296 if (total + trailingTotal > availableWidth) break; 297 leadingIndex = i; 298 leadingTotal = total; 299 if (Character.isWhitespace(text.charAt(i))) leadingWhitespace = leadingIndex; 300 301 int index = text.length() - (i + 1); 302 total = computeStringWidth(metrics, text.substring(index - 1)); 303 if (total + leadingTotal > availableWidth) break; 304 trailingIndex = index; 305 trailingTotal = total; 306 if (Character.isWhitespace(text.charAt(index))) trailingWhitespace = trailingIndex; 307 }*/ 308 { 309 // either CENTER_ELLIPSIS or CENTER_WORD_ELLIPSIS 310 // for this case I read one char on the left, then one on the end 311 // then second on the left, then second from the end, etc until 312 // I have used up all the availableWidth. At that point, I trim 313 // the string twice: once from the start to firstIndex, and 314 // once from secondIndex to the end. I then insert the ellipsis 315 // between the two. 316 leadingIndex = -1; 317 trailingIndex = -1; 318 double total = 0.0F; 319 for (int i = 0; i <= text.length() - 1; i++) { 320 char c = text.charAt(i); 321 //total += metrics.charWidth(c); 322 total += computeTextWidth(font, "" + c, 0); 323 if (total > availableWidth) { 324 break; 325 } 326 leadingIndex = i; 327 if (Character.isWhitespace(c)) { 328 leadingWhitespace = leadingIndex; 329 } 330 int index = text.length() - 1 - i; 331 c = text.charAt(index); 332 //total += metrics.charWidth(c); 333 total += computeTextWidth(font, "" + c, 0); 334 if (total > availableWidth) { 335 break; 336 } 337 trailingIndex = index; 338 if (Character.isWhitespace(c)) { 339 trailingWhitespace = trailingIndex; 340 } 341 } 342 } 343 if (leadingIndex < 0) { 344 return ellipsis; 345 } 346 if (style == CENTER_ELLIPSIS) { 347 if (trailingIndex < 0) { 348 return text.substring(0, leadingIndex + 1) + ellipsis; 349 } 350 return text.substring(0, leadingIndex + 1) + ellipsis + text.substring(trailingIndex); 351 } else { 352 boolean leadingIndexIsLastLetterInWord = 353 Character.isWhitespace(text.charAt(leadingIndex + 1)); 354 int index = (leadingWhitespace == -1 || leadingIndexIsLastLetterInWord) ? (leadingIndex + 1) : (leadingWhitespace); 355 String leading = text.substring(0, index); 356 if (trailingIndex < 0) { 357 return leading + ellipsis; 358 } 359 boolean trailingIndexIsFirstLetterInWord = 360 Character.isWhitespace(text.charAt(trailingIndex - 1)); 361 index = (trailingWhitespace == -1 || trailingIndexIsFirstLetterInWord) ? (trailingIndex) : (trailingWhitespace + 1); 362 String trailing = text.substring(index); 363 return leading + ellipsis + trailing; 364 } 365 } 366 } 367 368 public static String computeClippedWrappedText(Font font, String text, double width, 369 double height, OverrunStyle truncationStyle, 370 String ellipsisString, TextBoundsType boundsType) { 371 if (font == null) { 372 throw new IllegalArgumentException("Must specify a font"); 373 } 374 375 String ellipsis = (truncationStyle == CLIP) ? "" : ellipsisString; 376 int eLen = ellipsis.length(); 377 // Do this before using helper, as it's not reentrant. 378 double eWidth = computeTextWidth(font, ellipsis, 0); 379 double eHeight = computeTextHeight(font, ellipsis, 0, boundsType); 380 381 if (width < eWidth || height < eHeight) { 382 // The ellipsis doesn't fit. 383 return text; // RT-30868 - return text, not empty string. 384 } 385 386 helper.setText(text); 387 helper.setFont(font); 388 helper.setWrappingWidth((int)Math.ceil(width)); 389 helper.setBoundsType(boundsType); 390 helper.setLineSpacing(0); 391 392 boolean leading = (truncationStyle == LEADING_ELLIPSIS || 393 truncationStyle == LEADING_WORD_ELLIPSIS); 394 boolean center = (truncationStyle == CENTER_ELLIPSIS || 395 truncationStyle == CENTER_WORD_ELLIPSIS); 396 boolean trailing = !(leading || center); 397 boolean wordTrim = (truncationStyle == WORD_ELLIPSIS || 398 truncationStyle == LEADING_WORD_ELLIPSIS || 399 truncationStyle == CENTER_WORD_ELLIPSIS); 400 401 String result = text; 402 int len = (result != null) ? result.length() : 0; 403 int centerLen = -1; 404 405 Point2D centerPoint = null; 406 if (center) { 407 // Find index of character in the middle of the visual text area 408 centerPoint = new Point2D((width - eWidth) / 2, height / 2 - helper.getBaselineOffset()); 409 } 410 411 // Find index of character at the bottom left of the text area. 412 // This should be the first character of a line that would be clipped. 413 Point2D endPoint = new Point2D(0, height - helper.getBaselineOffset()); 414 415 int hit = helper.hitTest(endPoint).getCharIndex(); 416 if (hit >= len) { 417 helper.setBoundsType(TextBoundsType.LOGICAL); // restore 418 return text; 419 } 420 if (center) { 421 hit = helper.hitTest(centerPoint).getCharIndex(); 422 } 423 424 if (hit > 0 && hit < len) { 425 // Step one, make a truncation estimate. 426 427 if (center || trailing) { 428 int ind = hit; 429 if (center) { 430 // This is for the first part, i.e. beginning of text up to ellipsis. 431 if (wordTrim) { 432 int brInd = lastBreakCharIndex(text, ind + 1); 433 if (brInd >= 0) { 434 ind = brInd + 1; 435 } else { 436 brInd = firstBreakCharIndex(text, ind); 437 if (brInd >= 0) { 438 ind = brInd + 1; 439 } 440 } 441 } 442 centerLen = ind + eLen; 443 } // else: text node wraps at words, so wordTrim is not needed here. 444 result = result.substring(0, ind) + ellipsis; 445 } 446 447 if (leading || center) { 448 // The hit is an index counted from the beginning, but we need 449 // the opposite, i.e. an index counted from the end. However, 450 // the Text node does not support wrapped line layout in the 451 // reverse direction, starting at the bottom right corner. 452 453 // We'll simulate by assuming the index will be a similar 454 // number, then back up 10 characters just to add some slop. 455 // For example, the ending lines might pack tighter than the 456 // beginning lines, and therefore fit a higher number of 457 // characters. 458 int ind = Math.max(0, len - hit - 10); 459 if (ind > 0 && wordTrim) { 460 int brInd = lastBreakCharIndex(text, ind + 1); 461 if (brInd >= 0) { 462 ind = brInd + 1; 463 } else { 464 brInd = firstBreakCharIndex(text, ind); 465 if (brInd >= 0) { 466 ind = brInd + 1; 467 } 468 } 469 } 470 if (center) { 471 // This is for the second part, i.e. from ellipsis to end of text. 472 result = result + text.substring(ind); 473 } else { 474 result = ellipsis + text.substring(ind); 475 } 476 } 477 478 // Step two, check if text still overflows after we added the ellipsis. 479 // If so, remove one char or word at a time. 480 while (true) { 481 helper.setText(result); 482 int hit2 = helper.hitTest(endPoint).getCharIndex(); 483 if (center && hit2 < centerLen) { 484 // No room for text after ellipsis. Maybe there is a newline 485 // here, and the next line falls outside the view. 486 if (hit2 > 0 && result.charAt(hit2-1) == '\n') { 487 hit2--; 488 } 489 result = text.substring(0, hit2) + ellipsis; 490 break; 491 } else if (hit2 > 0 && hit2 < result.length()) { 492 if (leading) { 493 int ind = eLen + 1; // Past ellipsis and first char. 494 if (wordTrim) { 495 int brInd = firstBreakCharIndex(result, ind); 496 if (brInd >= 0) { 497 ind = brInd + 1; 498 } 499 } 500 result = ellipsis + result.substring(ind); 501 } else if (center) { 502 int ind = centerLen + 1; // Past ellipsis and first char. 503 if (wordTrim) { 504 int brInd = firstBreakCharIndex(result, ind); 505 if (brInd >= 0) { 506 ind = brInd + 1; 507 } 508 } 509 result = result.substring(0, centerLen) + result.substring(ind); 510 } else { 511 int ind = result.length() - eLen - 1; // Before last char and ellipsis. 512 if (wordTrim) { 513 int brInd = lastBreakCharIndex(result, ind); 514 if (brInd >= 0) { 515 ind = brInd; 516 } 517 } 518 result = result.substring(0, ind) + ellipsis; 519 } 520 } else { 521 break; 522 } 523 } 524 } 525 // RESTORE STATE 526 helper.setWrappingWidth(DEFAULT_WRAPPING_WIDTH); 527 helper.setLineSpacing(DEFAULT_LINE_SPACING); 528 helper.setText(DEFAULT_TEXT); 529 helper.setBoundsType(DEFAULT_BOUNDS_TYPE); 530 return result; 531 } 532 533 534 private static int firstBreakCharIndex(String str, int start) { 535 char[] chars = str.toCharArray(); 536 for (int i = start; i < chars.length; i++) { 537 if (isPreferredBreakCharacter(chars[i])) { 538 return i; 539 } 540 } 541 return -1; 542 } 543 544 private static int lastBreakCharIndex(String str, int start) { 545 char[] chars = str.toCharArray(); 546 for (int i = start; i >= 0; i--) { 547 if (isPreferredBreakCharacter(chars[i])) { 548 return i; 549 } 550 } 551 return -1; 552 } 553 554 /* Recognizes white space and latin punctuation as preferred 555 * line break positions. Could do a bit better with using more 556 * of the properties from the Character class. 557 */ 558 private static boolean isPreferredBreakCharacter(char ch) { 559 if (Character.isWhitespace(ch)) { 560 return true; 561 } else { 562 switch (ch) { 563 case ';' : 564 case ':' : 565 case '.' : 566 return true; 567 default: return false; 568 } 569 } 570 } 571 572 private static boolean requiresComplexLayout(Font font, String string) { 573 /* Map attrs = font.getAttributes(); 574 if (contains(attrs, KERNING, KERNING_ON) || 575 contains(attrs, LIGATURES, LIGATURES_ON) || 576 (attrs.containsKey(TRACKING) && attrs.get(TRACKING) != null)) { 577 return true; 578 } 579 return isComplexLayout(string.toCharArray(), 0, string.length()); 580 */ 581 return false; 582 } 583 584 static int computeStartOfWord(Font font, String text, int index) { 585 if ("".equals(text) || index < 0) return 0; 586 if (text.length() <= index) return text.length(); 587 // if the given index is not in a word (but in whitespace), then 588 // simply return the index 589 if (Character.isWhitespace(text.charAt(index))) { 590 return index; 591 } 592 boolean complexLayout = requiresComplexLayout(font, text); 593 if (complexLayout) { 594 // TODO needs implementation 595 return 0; 596 } else { 597 // just start walking backwards from index until either i<0 or 598 // the first whitespace is found. 599 int i = index; 600 while (--i >= 0) { 601 if (Character.isWhitespace(text.charAt(i))) { 602 return i + 1; 603 } 604 } 605 return 0; 606 } 607 } 608 609 static int computeEndOfWord(Font font, String text, int index) { 610 if (text.equals("") || index < 0) { 611 return 0; 612 } 613 if (text.length() <= index) { 614 return text.length(); 615 } 616 // if the given index is not in a word (but in whitespace), then 617 // simply return the index 618 if (Character.isWhitespace(text.charAt(index))) { 619 return index; 620 } 621 boolean complexLayout = requiresComplexLayout(font, text); 622 if (complexLayout) { 623 // TODO needs implementation 624 return text.length(); 625 } else { 626 // just start walking forward from index until either i > length or 627 // the first whitespace is found. 628 int i = index; 629 while (++i < text.length()) { 630 if (Character.isWhitespace(text.charAt(i))) { 631 return i; 632 } 633 } 634 return text.length(); 635 } 636 } 637 638 // used for layout to adjust widths to honor the min/max policies consistently 639 public static double boundedSize(double value, double min, double max) { 640 // if max < value, return max 641 // if min > value, return min 642 // if min > max, return min 643 return Math.min(Math.max(value, min), Math.max(min,max)); 644 } 645 646 public static void addMnemonics(ContextMenu popup, Scene scene) { 647 addMnemonics(popup, scene, false); 648 } 649 650 public static void addMnemonics(ContextMenu popup, Scene scene, boolean initialState) { 651 652 if (!com.sun.javafx.PlatformUtil.isMac()) { 653 654 ContextMenuContent cmContent = (ContextMenuContent)popup.getSkin().getNode(); 655 MenuItem menuitem; 656 657 for (int i = 0 ; i < popup.getItems().size() ; i++) { 658 menuitem = popup.getItems().get(i); 659 /* 660 ** check is there are any mnemonics in this menu 661 */ 662 if (menuitem.isMnemonicParsing()) { 663 664 TextBinding bindings = new TextBinding(menuitem.getText()); 665 int mnemonicIndex = bindings.getMnemonicIndex() ; 666 if (mnemonicIndex >= 0) { 667 KeyCombination mnemonicKeyCombo = bindings.getMnemonicKeyCombination(); 668 Mnemonic myMnemonic = new Mnemonic(cmContent.getLabelAt(i), mnemonicKeyCombo); 669 scene.addMnemonic(myMnemonic); 670 NodeHelper.setShowMnemonics(cmContent.getLabelAt(i), initialState); 671 } 672 } 673 } 674 } 675 } 676 677 678 679 public static void removeMnemonics(ContextMenu popup, Scene scene) { 680 681 if (!com.sun.javafx.PlatformUtil.isMac()) { 682 683 ContextMenuContent cmContent = (ContextMenuContent)popup.getSkin().getNode(); 684 MenuItem menuitem; 685 686 for (int i = 0 ; i < popup.getItems().size() ; i++) { 687 menuitem = popup.getItems().get(i); 688 /* 689 ** check is there are any mnemonics in this menu 690 */ 691 if (menuitem.isMnemonicParsing()) { 692 693 TextBinding bindings = new TextBinding(menuitem.getText()); 694 int mnemonicIndex = bindings.getMnemonicIndex() ; 695 if (mnemonicIndex >= 0) { 696 KeyCombination mnemonicKeyCombo = bindings.getMnemonicKeyCombination(); 697 698 ObservableList<Mnemonic> mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); 699 if (mnemonicsList != null) { 700 for (int j = 0 ; j < mnemonicsList.size() ; j++) { 701 if (mnemonicsList.get(j).getNode() == cmContent.getLabelAt(i)) { 702 mnemonicsList.remove(j); 703 } 704 } 705 } 706 } 707 } 708 } 709 } 710 } 711 712 public static double computeXOffset(double width, double contentWidth, HPos hpos) { 713 if (hpos == null) { 714 return 0; 715 } 716 717 switch(hpos) { 718 case LEFT: 719 return 0; 720 case CENTER: 721 return (width - contentWidth) / 2; 722 case RIGHT: 723 return width - contentWidth; 724 default: 725 return 0; 726 } 727 } 728 729 public static double computeYOffset(double height, double contentHeight, VPos vpos) { 730 if (vpos == null) { 731 return 0; 732 } 733 734 switch(vpos) { 735 case TOP: 736 return 0; 737 case CENTER: 738 return (height - contentHeight) / 2; 739 case BOTTOM: 740 return height - contentHeight; 741 default: 742 return 0; 743 } 744 } 745 746 /* 747 ** Returns true if the platform is to use Two-Level-Focus. 748 ** This is in the Util class to ease any changes in 749 ** the criteria for enabling this feature. 750 ** 751 ** TwoLevelFocus is needed on platforms that 752 ** only support 5-button navigation (arrow keys and Select/OK). 753 ** 754 */ 755 public static boolean isTwoLevelFocus() { 756 return Platform.isSupported(ConditionalFeature.TWO_LEVEL_FOCUS); 757 } 758 759 760 // useful method for linking things together when before a property is 761 // necessarily set 762 public static <T> void executeOnceWhenPropertyIsNonNull(ObservableValue<T> p, Consumer<T> consumer) { 763 if (p == null) return; 764 765 T value = p.getValue(); 766 if (value != null) { 767 consumer.accept(value); 768 } else { 769 final InvalidationListener listener = new InvalidationListener() { 770 @Override public void invalidated(Observable observable) { 771 T value = p.getValue(); 772 773 if (value != null) { 774 p.removeListener(this); 775 consumer.accept(value); 776 } 777 } 778 }; 779 p.addListener(listener); 780 } 781 } 782 783 public static String formatHexString(Color c) { 784 if (c != null) { 785 return String.format((Locale) null, "#%02x%02x%02x", 786 Math.round(c.getRed() * 255), 787 Math.round(c.getGreen() * 255), 788 Math.round(c.getBlue() * 255)); 789 } else { 790 return null; 791 } 792 } 793 794 public static URL getResource(String str) { 795 return Utils.class.getResource(str); 796 } 797 798 }