/**
   * Updates the interal bitset from <code>iterator</code>. This will set <code>validMask</code> to
   * true if <code>iterator</code> is non-null.
   */
  private void updateMask(AttributedCharacterIterator iterator) {
    if (iterator != null) {
      validMask = true;
      this.iterator = iterator;

      // Update the literal mask
      if (literalMask == null) {
        literalMask = new BitSet();
      } else {
        for (int counter = literalMask.length() - 1; counter >= 0; counter--) {
          literalMask.clear(counter);
        }
      }

      iterator.first();
      while (iterator.current() != CharacterIterator.DONE) {
        Map attributes = iterator.getAttributes();
        boolean set = isLiteral(attributes);
        int start = iterator.getIndex();
        int end = iterator.getRunLimit();

        while (start < end) {
          if (set) {
            literalMask.set(start);
          } else {
            literalMask.clear(start);
          }
          start++;
        }
        iterator.setIndex(start);
      }
    }
  }
示例#2
0
  /**
   * InputMethod implementation For details read
   * http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html
   */
  @Override
  protected void processInputMethodEvent(InputMethodEvent e) {
    int commitCount = e.getCommittedCharacterCount();

    if (commitCount > 0) {
      myInputMethodUncommitedChars = null;
      AttributedCharacterIterator text = e.getText();
      if (text != null) {
        StringBuilder sb = new StringBuilder();

        //noinspection ForLoopThatDoesntUseLoopVariable
        for (char c = text.first(); commitCount > 0; c = text.next(), commitCount--) {
          if (c >= 0x20
              && c
                  != 0x7F) { // Hack just like in
                             // javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
            sb.append(c);
          }
        }

        myTerminalStarter.sendString(sb.toString());
      }
    } else {
      myInputMethodUncommitedChars = uncommitedChars(e.getText());
    }
  }
  /**
   * @tests java.text.AttributedString#AttributedString(AttributedCharacterIterator, int, int, Map<?
   *     extends AttributedCharacterIterator.Attribute,?>) Test of method
   *     java.text.AttributedString#AttributedString(AttributedCharacterIterator, int, int, Map<?
   *     extends AttributedCharacterIterator.Attribute,?>). Case 1: Try to construct
   *     AttributedString. Case 2: Try to construct AttributedString using 0-length text and not an
   *     empty Map attributes.
   */
  public void test_ConstructorLjava_lang_StringLjava_util_Map() {
    String test = "Test string";

    // case 1: Try to construct AttributedString
    try {
      AttributedString attrString =
          new AttributedString(
              test, new WeakHashMap<AttributedCharacterIterator.Attribute, String>());
      AttributedCharacterIterator it = attrString.getIterator();
      StringBuffer buf = new StringBuffer();
      buf.append(it.first());
      char ch;
      while ((ch = it.next()) != CharacterIterator.DONE) buf.append(ch);
      assertTrue("Wrong string: " + buf, buf.toString().equals(test));
    } catch (Exception e) {
      fail("Unexpected exception " + e.toString());
    }

    // case 2: Try to construct AttributedString using 0-length text and
    // not an empty Map attributes.
    try {
      Map<AttributedCharacterIterator.Attribute, String> whm =
          new WeakHashMap<AttributedCharacterIterator.Attribute, String>();
      whm.put(new TestAttributedCharacterIteratorAttribute("test"), "value");
      new AttributedString("", whm);
      fail("Expected IllegalArgumentException was not thrown");
    } catch (Exception e) {
      // expected
    }
  }
示例#4
0
  /** @see Graphics2D#drawString(AttributedCharacterIterator, float, float) */
  public void drawString(AttributedCharacterIterator iter, float x, float y) {
    /*
            StringBuffer sb = new StringBuffer();
            for(char c = iter.first(); c != AttributedCharacterIterator.DONE; c = iter.next()) {
                sb.append(c);
            }
            drawString(sb.toString(),x,y);
    */
    StringBuffer stringbuffer = new StringBuffer(iter.getEndIndex());
    for (char c = iter.first(); c != '\uFFFF'; c = iter.next()) {
      if (iter.getIndex() == iter.getRunStart()) {
        if (stringbuffer.length() > 0) {
          drawString(stringbuffer.toString(), x, y);
          FontMetrics fontmetrics = getFontMetrics();
          x = (float) (x + fontmetrics.getStringBounds(stringbuffer.toString(), this).getWidth());
          stringbuffer.delete(0, stringbuffer.length());
        }
        doAttributes(iter);
      }
      stringbuffer.append(c);
    }

    drawString(stringbuffer.toString(), x, y);
    underline = false;
  }
  public List getTextRuns(TextNode node, AttributedCharacterIterator aci) {
    List textRuns = node.getTextRuns();
    if (textRuns != null) {
      return textRuns;
    }

    AttributedCharacterIterator[] chunkACIs = getTextChunkACIs(aci);
    textRuns = computeTextRuns(node, aci, chunkACIs);

    aci.first();
    List rgns = (List) aci.getAttribute(FLOW_REGIONS);

    if (rgns != null) {
      Iterator i = textRuns.iterator();
      List chunkLayouts = new ArrayList();
      TextRun tr = (TextRun) i.next();
      List layouts = new ArrayList();
      chunkLayouts.add(layouts);
      layouts.add(tr.getLayout());
      while (i.hasNext()) {
        tr = (TextRun) i.next();
        if (tr.isFirstRunInChunk()) {
          layouts = new ArrayList();
          chunkLayouts.add(layouts);
        }
        layouts.add(tr.getLayout());
      }

      FlowExtGlyphLayout.textWrapTextChunk(chunkACIs, chunkLayouts, rgns);
    }

    node.setTextRuns(textRuns);
    return textRuns;
  }
示例#6
0
 private List<Integer> getNewlineLocations(AttributedCharacterIterator styledTextIterator) {
   List<Integer> newlineLocations = new ArrayList<Integer>();
   for (char c = styledTextIterator.first();
       c != AttributedCharacterIterator.DONE;
       c = styledTextIterator.next()) {
     if (c == '\n') newlineLocations.add(styledTextIterator.getIndex());
   }
   return newlineLocations;
 }
 /**
  * @tests java.text.AttributedString#getIterator() Test of method
  *     java.text.AttributedString#getIterator().
  */
 public void test_getIterator() {
   String test = "Test string";
   try {
     AttributedString attrString = new AttributedString(test);
     AttributedCharacterIterator it = attrString.getIterator();
     assertEquals("Incorrect iteration on AttributedString", it.first(), test.charAt(0));
   } catch (Exception e) {
     fail("Unexpected exceptiption " + e.toString());
   }
 }
 /** @tests java.text.AttributedString#AttributedString(java.lang.String) */
 public void test_ConstructorLjava_lang_String() {
   String test = "Test string";
   AttributedString attrString = new AttributedString(test);
   AttributedCharacterIterator it = attrString.getIterator();
   StringBuffer buf = new StringBuffer();
   buf.append(it.first());
   char ch;
   while ((ch = it.next()) != CharacterIterator.DONE) buf.append(ch);
   assertTrue("Wrong string: " + buf, buf.toString().equals(test));
 }
示例#9
0
  /**
   * ************************************************************************ Return a Iterator with
   * only the relevant attributes. Fixes implementation in AttributedString, which returns
   * everything
   *
   * @param aString attributed string
   * @param relevantAttributes relevant attributes
   * @return iterator
   */
  public static AttributedCharacterIterator getIterator(
      AttributedString aString, AttributedCharacterIterator.Attribute[] relevantAttributes) {
    AttributedCharacterIterator iter = aString.getIterator();
    Set set = iter.getAllAttributeKeys();
    //	System.out.println("AllAttributeKeys=" + set);
    if (set.size() == 0) return iter;
    //	Check, if there are unwanted attributes
    Set<AttributedCharacterIterator.Attribute> unwanted =
        new HashSet<AttributedCharacterIterator.Attribute>(iter.getAllAttributeKeys());
    for (int i = 0; i < relevantAttributes.length; i++) unwanted.remove(relevantAttributes[i]);
    if (unwanted.size() == 0) return iter;

    //	Create new String
    StringBuffer sb = new StringBuffer();
    for (char c = iter.first(); c != AttributedCharacterIterator.DONE; c = iter.next())
      sb.append(c);
    aString = new AttributedString(sb.toString());

    //	copy relevant attributes
    Iterator it = iter.getAllAttributeKeys().iterator();
    while (it.hasNext()) {
      AttributedCharacterIterator.Attribute att = (AttributedCharacterIterator.Attribute) it.next();
      if (!unwanted.contains(att)) {
        for (char c = iter.first(); c != AttributedCharacterIterator.DONE; c = iter.next()) {
          Object value = iter.getAttribute(att);
          if (value != null) {
            int start = iter.getRunStart(att);
            int limit = iter.getRunLimit(att);
            //	System.out.println("Attribute=" + att + " Value=" + value + " Start=" + start + "
            // Limit=" + limit);
            aString.addAttribute(att, value, start, limit);
            iter.setIndex(limit);
          }
        }
      }
      //	else
      //		System.out.println("Unwanted: " + att);
    }
    return aString.getIterator();
  } //	getIterator
示例#10
0
 /**
  * Draws a string at the specified position.
  *
  * @param iterator the string.
  * @param x the x-coordinate.
  * @param y the y-coordinate.
  */
 @Override
 public void drawString(AttributedCharacterIterator iterator, int x, int y) {
   // for now we simply want to extract the chars from the iterator
   // and call an unstyled text renderer
   StringBuffer sb = new StringBuffer();
   int numChars = iterator.getEndIndex() - iterator.getBeginIndex();
   char c = iterator.first();
   for (int i = 0; i < numChars; i++) {
     sb.append(c);
     c = iterator.next();
   }
   drawString(new String(sb), x, y);
 }
示例#11
0
  /**
   * Handlers INPUT_METHOD_TEXT_CHANGED event. This handler also checks if a invalid key is pressed.
   * This handler is not necessary for JDK1.1, but in JDK1.2, 'keyTyped' event is never generated
   * instead this event is generated so it has to be handled.
   *
   * <p>Note: In JDK1.1 this method should be commented.
   *
   * @param imeEvt event object
   */
  public void inputMethodTextChanged(InputMethodEvent imeEvt) {
    AttributedCharacterIterator aciIterator = imeEvt.getText();

    for (char cChar = aciIterator.first();
        cChar != CharacterIterator.DONE;
        cChar = aciIterator.next()) {
      // If any one of the characters is not allowed,
      // consume the event ...
      if (Character.isDigit(cChar) || cChar == TIME_SEP || cChar == KeyEvent.VK_PERIOD) continue;
      imeEvt.consume();
      return;
    }
    return;
  }
示例#12
0
  private static String uncommitedChars(AttributedCharacterIterator text) {
    StringBuilder sb = new StringBuilder();

    for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) {
      if (c >= 0x20
          && c
              != 0x7F) { // Hack just like in
                         // javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
        sb.append(c);
      }
    }

    return sb.toString();
  }
  /**
   * Returns the start of the first run that contains the attribute <code>id</code>. This will
   * return <code>-1</code> if the attribute can not be found.
   */
  int getAttributeStart(AttributedCharacterIterator.Attribute id) {
    if (isValidMask()) {
      AttributedCharacterIterator iterator = getIterator();

      iterator.first();
      while (iterator.current() != CharacterIterator.DONE) {
        if (iterator.getAttribute(id) != null) {
          return iterator.getIndex();
        }
        iterator.next();
      }
    }
    return -1;
  }
  /**
   * Create a new StyledParagraph over the given styled text.
   *
   * @param aci an iterator over the text
   * @param chars the characters extracted from aci
   */
  public StyledParagraph(AttributedCharacterIterator aci, char[] chars) {

    int start = aci.getBeginIndex();
    int end = aci.getEndIndex();
    length = end - start;

    int index = start;
    aci.first();

    do {
      final int nextRunStart = aci.getRunLimit();
      final int localIndex = index - start;

      Map attributes = aci.getAttributes();
      attributes = addInputMethodAttrs(attributes);
      Decoration d = Decoration.getDecoration(attributes);
      addDecoration(d, localIndex);

      Object f = getGraphicOrFont(attributes);
      if (f == null) {
        addFonts(chars, attributes, localIndex, nextRunStart - start);
      } else {
        addFont(f, localIndex);
      }

      aci.setIndex(nextRunStart);
      index = nextRunStart;

    } while (index < end);

    // Add extra entries to starts arrays with the length
    // of the paragraph.  'this' is used as a dummy value
    // in the Vector.
    if (decorations != null) {
      decorationStarts = addToVector(this, length, decorations, decorationStarts);
    }
    if (fonts != null) {
      fontStarts = addToVector(this, length, fonts, fontStarts);
    }
  }
 private TextLayout createAndCacheTextLayout(
     int fragmentIndex, Font basefont, FontRenderContext fontRenderContext) {
   String text = myFragments.get(fragmentIndex);
   AttributedString string = new AttributedString(text);
   int start = 0;
   int end = text.length();
   AttributedCharacterIterator it =
       string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end);
   Font currentFont = basefont;
   int currentIndex = start;
   for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
     Font font = basefont;
     if (!font.canDisplay(c)) {
       for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) {
         font =
             provider.getFontAbleToDisplay(
                 c, basefont.getSize(), basefont.getStyle(), basefont.getFamily());
         if (font != null) break;
       }
     }
     int i = it.getIndex();
     if (!Comparing.equal(currentFont, font)) {
       if (i > currentIndex) {
         string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i);
       }
       currentFont = font;
       currentIndex = i;
     }
   }
   if (currentIndex < end) {
     string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end);
   }
   TextLayout layout = new TextLayout(string.getIterator(), fontRenderContext);
   if (fragmentIndex >= myLayouts.size()) {
     myLayouts.addAll(Collections.nCopies(fragmentIndex - myLayouts.size() + 1, null));
   }
   myLayouts.set(fragmentIndex, layout);
   myLayoutFont = getBaseFont();
   return layout;
 }
  /**
   * Returns the number of occurences of <code>f</code> before the location <code>start</code> in
   * the current <code>AttributedCharacterIterator</code>.
   */
  private int getFieldTypeCountTo(Object f, int start) {
    AttributedCharacterIterator iterator = getIterator();
    int count = 0;

    if (iterator != null && (f instanceof AttributedCharacterIterator.Attribute)) {
      AttributedCharacterIterator.Attribute field = (AttributedCharacterIterator.Attribute) f;
      int index = 0;

      iterator.first();
      while (iterator.getIndex() < start) {
        while (iterator.getAttribute(field) == null && iterator.next() != CharacterIterator.DONE) ;
        if (iterator.current() != CharacterIterator.DONE) {
          iterator.setIndex(iterator.getRunLimit(field));
          iterator.next();
          count++;
        } else {
          break;
        }
      }
    }
    return count;
  }
  /** Selects the fields identified by <code>attributes</code>. */
  void selectField(Object f, int count) {
    AttributedCharacterIterator iterator = getIterator();

    if (iterator != null && (f instanceof AttributedCharacterIterator.Attribute)) {
      AttributedCharacterIterator.Attribute field = (AttributedCharacterIterator.Attribute) f;

      iterator.first();
      while (iterator.current() != CharacterIterator.DONE) {
        while (iterator.getAttribute(field) == null && iterator.next() != CharacterIterator.DONE) ;
        if (iterator.current() != CharacterIterator.DONE) {
          int limit = iterator.getRunLimit(field);

          if (--count <= 0) {
            getFormattedTextField().select(iterator.getIndex(), limit);
            break;
          }
          iterator.setIndex(limit);
          iterator.next();
        }
      }
    }
  }
示例#18
0
  /** Shows the current selected <tt>TextNode</tt>. */
  protected void showSelectedGraphicsNode() {
    GraphicsNode gn = walker.getCurrentGraphicsNode();
    if (!(gn instanceof TextNode)) {
      return;
    }
    TextNode textNode = (TextNode) gn;
    // mark the selection of the substring found
    String text = textNode.getText();
    String pattern = search.getText();
    if (!caseSensitive.isSelected()) {
      text = text.toLowerCase();
      pattern = pattern.toLowerCase();
    }
    int end = text.indexOf(pattern, currentIndex);

    AttributedCharacterIterator aci = textNode.getAttributedCharacterIterator();
    aci.first();
    for (int i = 0; i < end; ++i) {
      aci.next();
    }
    Mark startMark = textNode.getMarkerForChar(aci.getIndex(), true);

    for (int i = 0; i < pattern.length() - 1; ++i) {
      aci.next();
    }
    Mark endMark = textNode.getMarkerForChar(aci.getIndex(), false);
    svgCanvas.select(startMark, endMark);

    // zoom on the TextNode if needed
    if (highlightButton.isSelected()) {
      return;
    }

    // get the highlight shape in GVT root (global) coordinate sytem
    Shape s = textNode.getHighlightShape();
    AffineTransform at;
    if (highlightCenterZoomButton.isSelected()) {
      at = svgCanvas.getInitialTransform();
    } else {
      at = svgCanvas.getRenderingTransform();
    }
    // get the bounds of the highlight shape in the canvas coordinate system
    Rectangle2D gnb = at.createTransformedShape(s).getBounds();

    Dimension canvasSize = svgCanvas.getSize();
    // translate the highlight region to (0, 0) in the canvas coordinate
    // system
    AffineTransform Tx =
        AffineTransform.getTranslateInstance(
            -gnb.getX() - gnb.getWidth() / 2, -gnb.getY() - gnb.getHeight() / 2);

    if (highlightCenterZoomButton.isSelected()) {
      // zoom on the highlight shape such as the shape takes x% of the
      // canvas size
      double sx = canvasSize.width / gnb.getWidth();
      double sy = canvasSize.height / gnb.getHeight();
      double scale = Math.min(sx, sy) / 8;
      if (scale > 1) {
        Tx.preConcatenate(AffineTransform.getScaleInstance(scale, scale));
      }
    }
    Tx.preConcatenate(
        AffineTransform.getTranslateInstance(canvasSize.width / 2, canvasSize.height / 2));
    // take into account the initial transform
    AffineTransform newRT = new AffineTransform(at);
    newRT.preConcatenate(Tx);
    // change the rendering transform
    svgCanvas.setRenderingTransform(newRT);
  }
  public void drawString(AttributedCharacterIterator iterator, float x, float y) {

    // TextLayout draws the iterator as glyph vector
    // thats why we use it only in the case of TEXT_AS_SHAPES,
    // otherwise tagged strings are always written as glyphs
    if (isProperty(TEXT_AS_SHAPES)) {
      // draws all attributes
      TextLayout tl = new TextLayout(iterator, getFontRenderContext());
      tl.draw(this, x, y);
    } else {
      // reset to that font at the end
      Font font = getFont();

      // initial attributes, we us TextAttribute.equals() rather
      // than Font.equals() because using Font.equals() we do
      // not get a 'false' if underline etc. is changed
      Map<? extends Attribute, Object> attributes = FontUtilities.getAttributes(font);

      // stores all characters which are written with the same font
      // if font is changed the buffer will be written and cleared
      // after it
      StringBuffer sb = new StringBuffer();

      for (char c = iterator.first(); c != AttributedCharacterIterator.DONE; c = iterator.next()) {

        // append c if font is not changed
        if (attributes.equals(iterator.getAttributes())) {
          sb.append(c);

        } else {
          // TextLayout does not like 0 length strings
          if (sb.length() > 0) {
            // draw sb if font is changed
            drawString(sb.toString(), x, y);

            // change the x offset for the next drawing
            // FIXME: change y offset for vertical text
            TextLayout tl = new TextLayout(sb.toString(), attributes, getFontRenderContext());

            // calculate real width
            x = x + Math.max(tl.getAdvance(), (float) tl.getBounds().getWidth());
          }

          // empty sb
          sb = new StringBuffer();
          sb.append(c);

          // change the font
          attributes = iterator.getAttributes();
          setFont(new Font(attributes));
        }
      }

      // draw the rest
      if (sb.length() > 0) {
        drawString(sb.toString(), x, y);
      }

      // use the old font for the next string drawing
      setFont(font);
    }
  }
示例#20
0
  /** Initialize state, including fChars array, direction, and fBidi. */
  private void initAll(AttributedCharacterIterator text) {

    fStart = text.getBeginIndex();

    // extract chars
    fChars = new char[text.getEndIndex() - fStart];

    int n = 0;
    for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) {
      fChars[n++] = c;
    }

    text.first();

    fBidi = new Bidi(text);
    if (fBidi.isLeftToRight()) {
      fBidi = null;
    }

    text.first();
    Map<? extends Attribute, ?> paragraphAttrs = text.getAttributes();
    NumericShaper shaper = AttributeValues.getNumericShaping(paragraphAttrs);
    if (shaper != null) {
      shaper.shape(fChars, 0, fChars.length);
    }

    fParagraph = new StyledParagraph(text, fChars);

    // set paragraph attributes
    {
      // If there's an embedded graphic at the start of the
      // paragraph, look for the first non-graphic character
      // and use it and its font to initialize the paragraph.
      // If not, use the first graphic to initialize.
      fJustifyRatio = AttributeValues.getJustification(paragraphAttrs);

      boolean haveFont = TextLine.advanceToFirstFont(text);

      if (haveFont) {
        Font defaultFont = TextLine.getFontAtCurrentPos(text);
        int charsStart = text.getIndex() - text.getBeginIndex();
        LineMetrics lm = defaultFont.getLineMetrics(fChars, charsStart, charsStart + 1, fFrc);
        fBaseline = (byte) lm.getBaselineIndex();
        fBaselineOffsets = lm.getBaselineOffsets();
      } else {
        // hmmm what to do here?  Just try to supply reasonable
        // values I guess.

        GraphicAttribute graphic =
            (GraphicAttribute) paragraphAttrs.get(TextAttribute.CHAR_REPLACEMENT);
        fBaseline = TextLayout.getBaselineFromGraphic(graphic);
        Hashtable<Attribute, ?> fmap = new Hashtable<>(5, (float) 0.9);
        Font dummyFont = new Font(fmap);
        LineMetrics lm = dummyFont.getLineMetrics(" ", 0, 1, fFrc);
        fBaselineOffsets = lm.getBaselineOffsets();
      }
      fBaselineOffsets = TextLine.getNormalizedOffsets(fBaselineOffsets, fBaseline);
    }

    invalidateComponents();
  }