@Override
  protected Transferable createTransferable(JComponent c) {
    JTextPane aTextPane = (JTextPane) c;

    HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit());
    StyledDocument sdoc = aTextPane.getStyledDocument();
    int sel_start = aTextPane.getSelectionStart();
    int sel_end = aTextPane.getSelectionEnd();

    int i = sel_start;
    StringBuilder output = new StringBuilder();
    while (i < sel_end) {
      Element e = sdoc.getCharacterElement(i);
      Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute);
      int start = e.getStartOffset(), end = e.getEndOffset();
      if (nameAttr == HTML.Tag.BR) {
        output.append("\n");
      } else if (nameAttr == HTML.Tag.CONTENT) {
        if (start < sel_start) {
          start = sel_start;
        }
        if (end > sel_end) {
          end = sel_end;
        }
        try {
          String str = sdoc.getText(start, end - start);
          output.append(str);
        } catch (BadLocationException ble) {
          Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage());
        }
      }
      i = end;
    }
    return new StringSelection(output.toString());
  }
  public void search() {
    hilit.removeAllHighlights();

    String s = entry.getText();
    if (s.length() <= 0) {
      message("Nothing to search");
      return;
    }

    String content = textArea.getText();
    int index = content.indexOf(s, 0);
    if (index >= 0) {
      try {
        int end = index + s.length();
        hilit.addHighlight(index, end, painter);
        textArea.setCaretPosition(end);
        entry.setBackground(entryBg);
        message("'" + s + "' found. Press ESC to end search");
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    } else {
      entry.setBackground(ERROR_COLOR);
      message("'" + s + "' found. Press ESC to start a new search");
    }
  }
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }

      try {
        int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
        lastClickPoint = null;
        Document document = getDocument();
        String selectedText = getSelectedText();
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          final int selectionEnd = getSelectionEnd();
          document.insertString(selectionEnd, selectedText, null);
          select(selectionEnd, selectionEnd + selectedText.length());
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1);
          if (!textToDuplicate.startsWith("\n")) {
            textToDuplicate = "\n" + textToDuplicate;
          }
          if (textToDuplicate.endsWith("\n")) {
            textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1);
          }
          document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null);
          setCaretPosition(position + textToDuplicate.length());
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
  public void toggleBreakpoint() {
    if (isEnabled()) {
      try {
        int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
        lastClickPoint = null;
        if (position >= 0) {
          String textToCaret = getDocument().getText(0, position);
          int lineCount = 0;
          for (int i = 0; i < textToCaret.length(); i++) {
            if (textToCaret.charAt(i) == '\n') {
              lineCount++;
            }
          }
          if (breakpoints.isThereBreakpoint(lineCount)) {
            breakpoints.removeBreakpoint(lineCount);
          } else {
            breakpoints.addBreakpoint(new BreakpointInfo(lineCount));
          }
        }
      } catch (BadLocationException e) {
        e.printStackTrace();
      }

      Component parent = GuiUtils.getParentOfType(this, XmlEditorScrollPane.class);
      if (parent != null) {
        ((XmlEditorScrollPane) parent).onDocChanged();
      }
      repaint();
    }
  }
  /**
   * This method causes a transfer to a component from a clipboard or a DND drop operation. The
   * Transferable represents the data to be imported into the component.
   *
   * @param comp The component to receive the transfer. This argument is provided to enable sharing
   *     of TransferHandlers by multiple components.
   * @param t The data to import
   * @return <code>true</code> iff the data was inserted into the component.
   */
  public boolean importData(JComponent comp, Transferable t) {

    JTextComponent c = (JTextComponent) comp;
    withinSameComponent = c == exportComp;

    // if we are importing to the same component that we exported from
    // then don't actually do anything if the drop location is inside
    // the drag location and set shouldRemove to false so that exportDone
    // knows not to remove any data
    if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) {
      shouldRemove = false;
      return true;
    }

    boolean imported = false;
    DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c);
    if (importFlavor != null) {
      try {
        InputContext ic = c.getInputContext();
        if (ic != null) ic.endComposition();
        Reader r = importFlavor.getReaderForText(t);
        handleReaderImport(r, c);
        imported = true;
      } catch (UnsupportedFlavorException ufe) {
        ufe.printStackTrace();
      } catch (BadLocationException ble) {
        ble.printStackTrace();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    }

    return imported;
  }
Exemple #6
0
    public void mousePressed(MouseEvent evt) {
      requestFocus();

      // Focus events not fired sometimes?
      setCaretVisible(true);
      focusedComponent = JEditTextArea.this;

      if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 && popup != null) {
        popup.show(painter, evt.getX(), evt.getY());
        return;
      }

      int line = yToLine(evt.getY());
      int offset = xToOffset(line, evt.getX());
      int dot = getLineStartOffset(line) + offset;

      switch (evt.getClickCount()) {
        case 1:
          doSingleClick(evt, line, offset, dot);
          break;
        case 2:
          // It uses the bracket matching stuff, so
          // it can throw a BLE
          try {
            doDoubleClick(evt, line, offset, dot);
          } catch (BadLocationException bl) {
            bl.printStackTrace();
          }
          break;
        case 3:
          doTripleClick(evt, line, offset, dot);
          break;
      }
    }
Exemple #7
0
    private static int getNSVisualPosition(EditorPane txt, int pos, int direction) {
      Element root = txt.getDocument().getDefaultRootElement();
      int numLines = root.getElementIndex(txt.getDocument().getLength() - 1) + 1;
      int line = root.getElementIndex(pos) + 1;
      int tarLine = direction == SwingConstants.NORTH ? line - 1 : line + 1;
      try {
        if (tarLine <= 0) {
          return 0;
        }
        if (tarLine > numLines) {
          return txt.getDocument().getLength();
        }

        Rectangle curRect = txt.modelToView(pos);
        Rectangle tarEndRect;
        if (tarLine < numLines) {
          tarEndRect = txt.modelToView(txt.getLineStartOffset(tarLine) - 1);
        } else {
          tarEndRect = txt.modelToView(txt.getDocument().getLength() - 1);
        }
        Debug.log(9, "curRect: " + curRect + ", tarEnd: " + tarEndRect);

        if (curRect.x > tarEndRect.x) {
          pos = txt.viewToModel(new Point(tarEndRect.x, tarEndRect.y));
        } else {
          pos = txt.viewToModel(new Point(curRect.x, tarEndRect.y));
        }
      } catch (BadLocationException e) {
        Debug.error(me + "Problem getting next visual position\n%s", e.getMessage());
      }

      return pos;
    }
 /** Clear the log panel. */
 public void clearLogPanel() {
   try {
     logPane.getDocument().remove(1, logPane.getDocument().getLength() - 1);
   } catch (BadLocationException e) {
     LoggerFactory.getLogger(ProcessUIPanel.class).error(e.getMessage());
   }
 }
    // ----------------------------------------------------
    // return last location found
    public int searchBackward(String lastFindStr) {
      try { // backward
        if (isFindAgain) { // otherwise you find same string
          int foo = lastFindIndex; // begining of word
          if (foo >= 0) {
            editor1.setCaretPosition(foo);
          }
          // System.out.println("Debug:TextViewer:searchBackward: lastFindIndex: "+foo);
        }

        int carPos = editor1.getCaretPosition();
        // search backward
        // todo: should we use the getText(pos,len,segment);
        String chunk1 = editor1.getDocument().getText(0, carPos);
        int lastFindIndexTemp = chunk1.lastIndexOf(lastFindStr);
        if (lastFindIndexTemp == -1) {
          boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try forward?");
          // handle forward
          if (okPressed) {
            forwardFindDirection = true;
            lastFindIndex = searchForward(lastFindStr);
          }
        } else {
          lastFindIndex = lastFindIndexTemp;
          editor1.setCaretPosition(lastFindIndex); // ready to type in body
          editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body
        }
      } catch (BadLocationException badexception) {
        String errstr = "TextViewer:searchBackward: " + badexception.getMessage();
        warningPopup.display(errstr);
        return (-1);
      }
      return (lastFindIndex);
    }
Exemple #10
0
  /**
   * Similar to <code>setSelectedText()</code>, but overstrikes the appropriate number of characters
   * if overwrite mode is enabled.
   *
   * @param str The string
   * @see #setSelectedText(String)
   * @see #isOverwriteEnabled()
   */
  public void overwriteSetSelectedText(String str) {
    // Don't overstrike if there is a selection
    if (!overwrite || selectionStart != selectionEnd) {
      setSelectedText(str);
      return;
    }

    // Don't overstrike if we're on the end of
    // the line
    int caret = getCaretPosition();
    int caretLineEnd = getLineEndOffset(getCaretLine());
    if (caretLineEnd - caret <= str.length()) {
      setSelectedText(str);
      return;
    }

    document.beginCompoundEdit();

    try {
      document.remove(caret, str.length());
      document.insertString(caret, str, null);
    } catch (BadLocationException bl) {
      bl.printStackTrace();
    } finally {
      document.endCompoundEdit();
    }
  }
 private void addStyledText(String text, Style style) {
   try {
     doc.insertString(doc.getLength(), text, style);
   } catch (BadLocationException ble) {
     ble.printStackTrace();
   }
 }
Exemple #12
0
 /**
  * Appends a string into the panel window.
  *
  * @param stringMessage The string to be appended.
  */
 public void append(String stringMessage) {
   StyledDocument doc = textPane.getStyledDocument();
   try {
     doc.insertString(doc.getLength(), "[Server: " + stringMessage + "]\n", chatFont);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
 }
Exemple #13
0
 /**
  * Copies the specified substring of the document into a segment. If the offsets are invalid, the
  * segment will contain a null string.
  *
  * @param start The start offset
  * @param len The length of the substring
  * @param segment The segment
  */
 public final void getText(int start, int len, Segment segment) {
   try {
     document.getText(start, len, segment);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     segment.offset = segment.count = 0;
   }
 }
Exemple #14
0
 /** Returns the entire text of this text area. */
 public String getText() {
   try {
     return document.getText(0, document.getLength());
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     return null;
   }
 }
 public String getDocumentText() {
   try {
     return getDocument().getText(0, getDocument().getLength());
   } catch (BadLocationException e) {
     e.printStackTrace();
     return null;
   }
 }
Exemple #16
0
 /**
  * Returns the specified substring of the document.
  *
  * @param start The start offset
  * @param len The length of the substring
  * @return The substring, or null if the offsets are invalid
  */
 public final String getText(int start, int len) {
   try {
     return document.getText(start, len);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     return null;
   }
 }
 private void setText(String text) {
   try {
     // remove all text and insert the completed string
     super.remove(0, getLength());
     super.insertString(0, text, null);
   } catch (BadLocationException e) {
     throw new RuntimeException(e.toString());
   }
 }
 private void moveCursorToTest(Test test) {
   if (test instanceof TestCase) {
     String func = ((TestCase) test).getName();
     try {
       SikuliIDE.getInstance().jumpTo(func);
     } catch (BadLocationException e) {
       e.printStackTrace();
     }
   }
 }
Exemple #19
0
 /** Sets the entire text of this text area. */
 public void setText(String text) {
   try {
     document.beginCompoundEdit();
     document.remove(0, document.getLength());
     document.insertString(0, text, null);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
   } finally {
     document.endCompoundEdit();
   }
 }
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }
      int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
      lastClickPoint = null;
      Document document = getDocument();
      String selectedText = getSelectedText();

      try {
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          String trimmed = selectedText.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            StringBuffer buffer = new StringBuffer(selectedText);
            int pos = buffer.indexOf("<!--");
            buffer.delete(pos, pos + 4);
            pos = buffer.lastIndexOf("-->");
            buffer.delete(pos, pos + 3);
            replaceSelection(buffer.toString());
          } else {
            String newSelection = "<!--" + selectedText + "-->";
            replaceSelection(newSelection);
          }
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToComment = getText(fromIndex, toIndex - fromIndex + 1);

          if (textToComment.startsWith("\n")) {
            textToComment = textToComment.substring(1);
            fromIndex++;
          }
          if (textToComment.endsWith("\n")) {
            textToComment = textToComment.substring(0, textToComment.length() - 1);
            toIndex--;
          }
          String trimmed = textToComment.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            int pos = textToComment.lastIndexOf("-->");
            document.remove(fromIndex + pos, 3);
            pos = textToComment.indexOf("<!--");
            document.remove(fromIndex + pos, 4);
          } else {
            document.insertString(Math.min(toIndex + 1, docLen), "-->", null);
            document.insertString(fromIndex, "<!--", null);
          }
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
    public void actionPerformed(ActionEvent e) {
      JTextComponent textComponent = getTextComponent(e);
      if (!textComponent.isEditable() || !textComponent.isEnabled()) {
        return;
      }

      try {
        outdentText(textComponent);
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
Exemple #22
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
Exemple #23
0
    @Override
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum((int) f.length());
        status.add(progress);
        status.revalidate();

        // try to start reading
        Reader in = new FileReader(f);
        char[] buff = new char[4096];
        int nch;
        while ((nch = in.read(buff, 0, buff.length)) != -1) {
          doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
          progress.setValue(progress.getValue() + nch);
        }
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not open file: " + msg,
                    "Error opening file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      doc.addUndoableEditListener(undoHandler);
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();

      resetUndoManager();

      if (elementTreePanel != null) {
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                elementTreePanel.setEditor(getEditor());
              }
            });
      }
    }
  private static void insertQuestion(final JTextPane textPane, String str) {
    Document doc = textPane.getDocument();
    try {
      doc.insertString(doc.getLength(), str, null);

      final int pos = doc.getLength();
      System.out.println(pos);
      final JTextField field =
          new JTextField(4) {
            @Override
            public Dimension getMaximumSize() {
              return getPreferredSize();
            }
          };
      field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
      field.addFocusListener(
          new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
              try {
                Rectangle rect = textPane.modelToView(pos);
                rect.grow(0, 4);
                rect.setSize(field.getSize());
                // System.out.println(rect);
                // System.out.println(field.getLocation());
                textPane.scrollRectToVisible(rect);
              } catch (BadLocationException ex) {
                ex.printStackTrace();
              }
            }

            @Override
            public void focusLost(FocusEvent e) {
              /* not needed */
            }
          });
      Dimension d = field.getPreferredSize();
      int baseline = field.getBaseline(d.width, d.height);
      field.setAlignmentY(baseline / (float) d.height);

      SimpleAttributeSet a = new SimpleAttributeSet();
      StyleConstants.setLineSpacing(a, 1.5f);
      textPane.setParagraphAttributes(a, true);

      textPane.insertComponent(field);
      doc.insertString(doc.getLength(), "\n", null);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
  }
Exemple #25
0
 @Override
 protected void exportDone(JComponent source, Transferable data, int action) {
   if (action == TransferHandler.MOVE) {
     JTextPane aTextPane = (JTextPane) source;
     int sel_start = aTextPane.getSelectionStart();
     int sel_end = aTextPane.getSelectionEnd();
     Document doc = aTextPane.getDocument();
     try {
       doc.remove(sel_start, sel_end - sel_start);
     } catch (BadLocationException e) {
       Debug.error(me + "exportDone: Problem while trying to remove text\n%s", e.getMessage());
     }
   }
 }
 public void actionPerformed(ActionEvent e) {
   ETextArea target = (ETextArea) getFocusedComponent();
   try {
     Document document = target.getDocument();
     int position = target.getCaretPosition();
     String whitespace = target.getIndentationOfLineAtOffset(position);
     String prefix = "{\n" + whitespace + Parameters.getParameter("indent.string");
     String suffix = "\n" + whitespace + "}";
     document.insertString(position, prefix + suffix, null);
     target.setCaretPosition(position + prefix.length());
   } catch (BadLocationException ex) {
     ex.printStackTrace();
   }
 }
Exemple #27
0
 private int parseRange(int start, int end) {
   if (!showThumbs) {
     // do not show any thumbnails
     return end;
   }
   try {
     end = parseLine(start, end, patCaptureBtn);
     end = parseLine(start, end, patPatternStr);
     end = parseLine(start, end, patRegionStr);
     end = parseLine(start, end, patPngStr);
   } catch (BadLocationException e) {
     Debug.error(me + "parseRange: Problem while trying to parse line\n%s", e.getMessage());
   }
   return end;
 }
Exemple #28
0
 // <editor-fold defaultstate="collapsed" desc="content insert append">
 public void insertString(String str) {
   int sel_start = getSelectionStart();
   int sel_end = getSelectionEnd();
   if (sel_end != sel_start) {
     try {
       getDocument().remove(sel_start, sel_end - sel_start);
     } catch (BadLocationException e) {
       Debug.error(me + "insertString: Problem while trying to insert\n%s", e.getMessage());
     }
   }
   int pos = getCaretPosition();
   insertString(pos, str);
   int new_pos = getCaretPosition();
   int end = parseRange(pos, new_pos);
   setCaretPosition(end);
 }
Exemple #29
0
  protected void updateBracketHighlight(int newCaretPosition) {
    if (newCaretPosition == 0) {
      bracketPosition = bracketLine = -1;
      return;
    }

    try {
      int offset = TextUtilities.findMatchingBracket(document, newCaretPosition - 1);
      if (offset != -1) {
        bracketLine = getLineOfOffset(offset);
        bracketPosition = offset - getLineStartOffset(bracketLine);
        return;
      }
    } catch (BadLocationException bl) {
      bl.printStackTrace();
    }

    bracketLine = bracketPosition = -1;
  }
Exemple #30
0
 /*
  * public int search(String str){
  * return search(str, true);
  * }
  */
 public int search(String str, int pos, boolean forward) {
   boolean isCaseSensitive = true;
   String toSearch = str;
   if (str.startsWith("!")) {
     str = str.substring(1).toUpperCase();
     isCaseSensitive = false;
   }
   int ret = -1;
   Document doc = getDocument();
   Debug.log(9, "search caret: " + pos + ", " + doc.getLength());
   try {
     String body;
     int begin;
     if (forward) {
       int len = doc.getLength() - pos;
       body = doc.getText(pos, len > 0 ? len : 0);
       begin = pos;
     } else {
       body = doc.getText(0, pos);
       begin = 0;
     }
     if (!isCaseSensitive) {
       body = body.toUpperCase();
     }
     Pattern pattern = Pattern.compile(Pattern.quote(str));
     Matcher matcher = pattern.matcher(body);
     ret = continueSearch(matcher, begin, forward);
     if (ret < 0) {
       if (forward && pos != 0) {
         return search(toSearch, 0, forward);
       }
       if (!forward && pos != doc.getLength()) {
         return search(toSearch, doc.getLength(), forward);
       }
     }
   } catch (BadLocationException e) {
     Debug.log(7, "search caret: " + pos + ", " + doc.getLength() + e.getStackTrace());
   }
   return ret;
 }