private void updateTemplateFromEditor(PrintfTemplate template) {
    ArrayList params = new ArrayList();
    String format = null;
    int text_length = editorPane.getDocument().getLength();
    try {
      format = editorPane.getDocument().getText(0, text_length);
    } catch (BadLocationException ex1) {
    }
    Element section_el = editorPane.getDocument().getDefaultRootElement();
    // Get number of paragraphs.
    int num_para = section_el.getElementCount();
    for (int p_count = 0; p_count < num_para; p_count++) {
      Element para_el = section_el.getElement(p_count);
      // Enumerate the content elements
      int num_cont = para_el.getElementCount();
      for (int c_count = 0; c_count < num_cont; c_count++) {
        Element content_el = para_el.getElement(c_count);
        AttributeSet attr = content_el.getAttributes();
        // Get the name of the style applied to this content element; may be null
        String sn = (String) attr.getAttribute(StyleConstants.NameAttribute);
        // Check if style name match
        if (sn != null && sn.startsWith("Parameter")) {
          // we extract the label.
          JLabel l = (JLabel) StyleConstants.getComponent(attr);
          if (l != null) {
            params.add(l.getName());
          }
        }
      }
    }

    template.setFormat(format);
    template.setTokens(params);
  }
Exemple #2
1
 protected void insertText(String textString, AttributeSet set) {
   try {
     content.getDocument().insertString(content.getDocument().getLength(), textString, set);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
 }
 /** 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());
   }
 }
  @Override
  public synchronized void run() {
    try {
      for (int i = 0; i < NUM_PIPES; i++) {
        while (Thread.currentThread() == reader[i]) {
          try {
            this.wait(100);
          } catch (InterruptedException ie) {
          }
          if (pin[i].available() != 0) {
            String input = this.readLine(pin[i]);
            appendMsg(htmlize(input));
            if (textArea.getDocument().getLength() > 0) {
              textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            }
          }
          if (quit) {
            return;
          }
        }
      }

    } catch (Exception e) {
      Debug.error(me + "Console reports an internal error:\n%s", e.getMessage());
    }
  }
Exemple #5
0
 /**
  * Insert (append) styled text in JTextPane
  *
  * @param textPane The JTextPane under consideration
  * @param text The text to be appended
  * @param set The Style attribute (font, size, color etc.)
  */
 protected static void insertText(JTextPane textPane, String text, AttributeSet set) {
   if (textPane == null) return;
   textPane.setEditable(true);
   try {
     textPane.getDocument().insertString(textPane.getDocument().getLength(), text + "\n", set);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
   textPane.setEditable(false);
 }
 // For compatibility with writers when talking to the JVM.
 public void write(char[] buffer, int offset, int length) {
   String text = new String(buffer, offset, length);
   SwingUtilities.invokeLater(
       () -> {
         try {
           pane.getDocument().insertString(pane.getDocument().getLength(), text, properties);
         } catch (Exception e) {
         }
       });
 }
 /**
  * Add the provided text with the provided color to the GUI document
  *
  * @param text The text that will be added
  * @param color The color used to show the text
  */
 public void print(String text, Color color) {
   StyleContext sc = StyleContext.getDefaultStyleContext();
   AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
   int len = logPane.getDocument().getLength();
   try {
     logPane.setCaretPosition(len);
     logPane.getDocument().insertString(len, text + "\n", aset);
   } catch (BadLocationException e) {
     LoggerFactory.getLogger(ProcessUIPanel.class).error("Cannot show the log message", e);
   }
   logPane.setCaretPosition(logPane.getDocument().getLength());
 }
  private void displayMessage(String text, AttributeSet as) {
    try {
      if (!text.endsWith("\n")) {
        text += "\n";
      }
      jTextPaneDisplayMessages
          .getDocument()
          .insertString(jTextPaneDisplayMessages.getDocument().getLength(), text, as);

      jTextPaneDisplayMessages.setCaretPosition(jTextPaneDisplayMessages.getDocument().getLength());
    } catch (BadLocationException ex) {
    }
  }
  /**
   * Parse the passed text string for style names and add the styled text to the text pane's
   * document.
   *
   * @param text Text to parse
   * @param pane Pane to modify. The pane also provides the style names
   */
  public static final void parse(String text, JTextPane pane) {
    try {
      Matcher match = TEXT_PATTERN.matcher(text);
      Document doc = pane.getDocument();
      int textStart = 0; // Start of current text area
      Style style = null; // Style for next set of text
      while (match.find()) {

        // Save the current text first
        String styledText = text.substring(textStart, match.start());
        textStart = match.end() + 1;
        if (style != null && styledText != null) {
          doc.insertString(doc.getLength(), styledText, style);
        } // endif

        // Get the next style
        style = pane.getStyle(match.group(1));
        if (style == null) throw new IllegalArgumentException("Unknown style: '" + match.group(1));
      } // endwhile

      // Add the last of the text
      doc.insertString(doc.getLength(), text.substring(textStart), null);
    } catch (BadLocationException e) {
      e.printStackTrace();
      throw new IllegalStateException(
          "This should not happen since I always use the document to "
              + "determine the location to write. It might be due to synchronization problems though");
    }
  }
  /** @param singleFormatter */
  protected void fillWithObjFormatter(final DataObjDataFieldFormatIFace singleFormatter) {
    ignoreFmtChange = true;
    try {
      formatEditor.setText("");

      if (singleFormatter == null) {
        return;
      }

      Document doc = formatEditor.getDocument();
      DataObjDataField[] fields = singleFormatter.getFields();
      if (fields == null) {
        return;
      }

      for (DataObjDataField field : fields) {
        try {
          doc.insertString(doc.getLength(), field.getSep(), null);

          // System.err.println("["+field.getName()+"]["+field.getSep()+"]["+field.getFormat()+"]["+field.toString()+"]");
          insertFieldIntoTextEditor(new DataObjDataFieldWrapper(field));
        } catch (BadLocationException ble) {
        }
      }
    } finally {
      ignoreFmtChange = false;
    }
  }
  public void toScreen(String s, Class module, String TYPE) {
    Color c = Color.BLACK;
    if (TYPE != null) {
      if (TYPE.contains("ERROR")) c = Color.RED;
      if (TYPE.contains("WARNING")) c = new Color(255, 106, 0);
      if (TYPE.contains("DEBUG")) c = Color.BLUE;
      if (module.toString().equalsIgnoreCase("Exception")) c = Color.RED;
    }
    StyleContext sc = StyleContext.getDefaultStyleContext();
    javax.swing.text.AttributeSet aset =
        sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
    int len = SCREEN.getDocument().getLength(); // same value as
    SCREEN.setCaretPosition(len); // place caret at the end (with no selection)
    SCREEN.setCharacterAttributes(aset, false);
    SCREEN.replaceSelection(
        "["
            + getData()
            + " - "
            + module.getSimpleName()
            + " - "
            + TYPE
            + "] "
            + s
            + "\n"); // there is no selection, so inserts at caret
    SCREEN.setFont(new Font("Monospaced", Font.PLAIN, 14));

    aggiungiRiga(s, module, TYPE);
  }
  public void toChatScreen(String toScreen, boolean selfSeen)
      throws IOException, BadLocationException {
    // Timestamp ts = new Timestamp();
    String toScreenFinal = "";
    Date now = Calendar.getInstance().getTime();
    SimpleDateFormat format = new SimpleDateFormat("hh:mm");
    String ts = format.format(now);

    // chatScreen.append(ts + " " + toScreen + "\n");
    toScreenFinal = "<font color=gray>" + ts + "</font> ";
    if (selfSeen) toScreenFinal = toScreenFinal + "<font color=red>" + toScreen + "</font>";
    else toScreenFinal = toScreenFinal + toScreen;

    // chatter.addTo(toScreen);

    // if(standardWindow) {
    //    chatScreen.setCaretPosition(chatScreen.getDocument().getLength());
    // }
    // else {
    JScrollBar vBar = scrollChat.getVerticalScrollBar();
    int vSize = vBar.getVisibleAmount();
    int maxVBar = vBar.getMaximum();
    int currVBar = vBar.getValue() + vSize;
    kit.insertHTML(doc, doc.getLength(), toScreenFinal, 0, 0, null);
    if (maxVBar == currVBar) {
      chatScreen.setCaretPosition(chatScreen.getDocument().getLength());
    }

    // }

    // kit.insertHTML(doc, doc.getLength(), toScreenFinal, 0, 0, null);

  }
Exemple #13
0
  private final void find(Pattern pattern) {
    final WriteOnce<Integer> once = new WriteOnce<Integer>();
    final Highlighter highlighter = textPane.getHighlighter();
    highlighter.removeAllHighlights();

    int matches = 0;

    final HTMLDocument doc = (HTMLDocument) textPane.getDocument();
    for (final HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.CONTENT);
        it.isValid();
        it.next())
      try {
        final String fragment =
            doc.getText(it.getStartOffset(), it.getEndOffset() - it.getStartOffset());
        final Matcher matcher = pattern.matcher(fragment);
        while (matcher.find()) {
          highlighter.addHighlight(
              it.getStartOffset() + matcher.start(),
              it.getStartOffset() + matcher.end(),
              HIGHLIGHTER);
          once.set(it.getStartOffset());
          ++matches;
        }
      } catch (final BadLocationException ex) {
      }
    if (!once.isEmpty()) textPane.setCaretPosition(once.get());
    this.matches.setText(String.format("%d matches", matches));
  }
  private void updateEditorView() {
    editorPane.setText("");
    numParameters = 0;
    try {
      java.util.List elements = editableTemplate.getPrintfElements();
      for (Iterator it = elements.iterator(); it.hasNext(); ) {
        PrintfUtil.PrintfElement el = (PrintfUtil.PrintfElement) it.next();
        if (el.getFormat().equals(PrintfUtil.PrintfElement.FORMAT_NONE)) {
          appendText(el.getElement(), PLAIN_ATTR);
        } else {
          insertParameter(
              (ConfigParamDescr) paramKeys.get(el.getElement()),
              el.getFormat(),
              editorPane.getDocument().getLength());
        }
      }
    } catch (Exception ex) {
      JOptionPane.showMessageDialog(
          this,
          "Invalid Format: " + ex.getMessage(),
          "Invalid Printf Format",
          JOptionPane.ERROR_MESSAGE);

      selectedPane = 1;
      printfTabPane.setSelectedIndex(selectedPane);
      updatePane(selectedPane);
    }
  }
 public void clearText() {
   try {
     Document doc = textPane.getDocument();
     doc.remove(0, doc.getLength());
   } catch (Exception ex) {
     log.warn("failed to clear text", ex);
   }
 }
 private void addText(String str, String styleName, JTextPane pane) {
   Document doc = pane.getDocument();
   int len = doc.getLength();
   try {
     doc.insertString(len, str, pane.getStyle(styleName));
   } catch (javax.swing.text.BadLocationException e) {
   }
 }
 protected void append(JTextPane field, final String change) {
   Document document = field.getDocument();
   try {
     document.insertString(document.getLength(), change, null);
   } catch (BadLocationException e) {
     throw new NotImplementedYet(e); // Fix Handle this exception.
   }
 }
 private void appendMsg(String msg) {
   HTMLDocument doc = (HTMLDocument) textArea.getDocument();
   HTMLEditorKit kit = (HTMLEditorKit) textArea.getEditorKit();
   try {
     kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
   } catch (Exception e) {
     Debug.error(me + "Problem appending text to message area!\n%s", e.getMessage());
   }
 }
Exemple #19
0
  public void appendToPane(String msg, Color c) {
    if (inputText.isEnabled()) {
      StyleContext sc = StyleContext.getDefaultStyleContext();
      AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

      textArea.setCharacterAttributes(aset, false);
      textArea.replaceSelection(msg);
      textArea.setCaretPosition(textArea.getDocument().getLength());
    }
  }
Exemple #20
0
  final void setPage(HtmlPage page) throws IOException {

    this.page = page;
    final Document doc = textPane.getDocument();
    doc.putProperty(Document.TitleProperty, page.getTitle());
    // Clearing stream forces refresh.
    doc.putProperty(Document.StreamDescriptionProperty, null);
    textPane.setPage(page.getPath().toURI().toURL());
    find(find.getText());
  }
 /*
  * append(String s, Color color){...}
  * This method is the same as append(String s) except
  * that this method also changes the color of the
  * indicated text instead of defaulting to white.
  */
 public static void append(String s, Color color) {
   style = tPane.addStyle("Styles", null);
   StyleConstants.setForeground(style, color);
   try {
     doc.insertString(doc.getLength(), s, style);
   } catch (BadLocationException ex) {
     System.out.println("BadLocationException ex caught.");
   }
   tPane.setCaretPosition(tPane.getDocument().getLength());
 }
 // Appends text to the end of the log, using the provided settings. Doesn't add a new line.
 private static void print(String message, SimpleAttributeSet settings) {
   try {
     outputText
         .getDocument()
         .insertString(outputText.getDocument().getLength(), message, settings);
   } catch (BadLocationException e) {
     try {
       outputText
           .getDocument()
           .insertString(
               outputText.getDocument().getLength(),
               "Couldn't insert message \"" + message + "\".",
               progErr);
     } catch (BadLocationException b) {
       // If you ever reach this error, something is seriously wrong, so just please swallow it and
       // ignore it.
     }
   }
 }
Exemple #23
0
  public static void appendToPane(JTextPane tp, String msg, Color c) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);
  }
 @Override
 public void actionPerformed(ActionEvent e) {
   int pos = textPane.getCaretPosition();
   Document doc = textPane.getDocument();
   if (pos < 0) {
     pos = doc.getLength();
   }
   try {
     doc.insertString(pos, textToInsert, null);
   } catch (BadLocationException ex) {
     log.error("Failed to insert text " + ex.getMessage() + " ... ignore, no rethrow!");
   }
 }
  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 #26
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());
     }
   }
 }
Exemple #27
0
  private void executeCommand(String command) {
    // Get shell service.
    ServiceReference ref = hostBundle.getServiceReference(SHELL_SERVICE_REFERENCE);
    if (ref == null) {
      LOGGER.error(I18N.tr("No shell service is available."));
      return;
    }
    ShellService shell = (ShellService) hostBundle.getService(ref);
    try {
      // Print the command line in the output window.
      try {
        outputField
            .getDocument()
            .insertString(outputField.getDocument().getLength(), "osgi> " + command + "\n", null);
      } catch (BadLocationException ex) {
        LOGGER.debug(ex.getLocalizedMessage(), ex);
        // ignore
      }

      try {
        shell.executeCommand(command, new PrintStream(info), new PrintStream(error));
      } catch (Exception ex) {
        LOGGER.error(ex.getLocalizedMessage(), ex);
      } finally {
        try {
          // Send messages to the window
          info.flush();
          error.flush();
          outputField.setCaretPosition(outputField.getDocument().getLength());
        } catch (IOException ex) {
          LOGGER.error(ex.getLocalizedMessage(), ex);
        }
      }
    } finally {
      hostBundle.ungetService(ref);
    }
  }
Exemple #28
0
 public void caretUpdate(CaretEvent e) {
   // when the cursor moves on _textView
   // this method will be called. Then, we
   // must determine what the line number is
   // and update the line number view
   Element root = textView.getDocument().getDefaultRootElement();
   int line = root.getElementIndex(e.getDot());
   root = root.getElement(line);
   int col = root.getElementIndex(e.getDot());
   lineNumberView.setText(line + ":" + col);
   // if text is selected then enable copy and cut
   boolean isSelection = e.getDot() != e.getMark();
   copyAction.setEnabled(isSelection);
   cutAction.setEnabled(isSelection);
 }
  public void displayClass(String classString) {
    displayDataState = DisplayDataState.INSIDE_CLASS;
    try {
      String currentText = jTextPane.getDocument().getText(0, jTextPane.getDocument().getLength());
      if (currentText.equals(getOneColorFormattedOutput(classString))) {
        return;
      }
    } catch (BadLocationException e) {
      e.printStackTrace();
    }

    clearText();
    StyleConstants.setFontSize(style, 18);

    Document doc = new DefaultStyledDocument();

    try {
      doc.insertString(doc.getLength(), getOneColorFormattedOutput(classString), style);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }

    jTextPane.setDocument(doc);
  }
Exemple #30
0
 @Override
 public void mouseMoved(MouseEvent event) {
   JTextPane textPane = (JTextPane) event.getSource();
   Point point = new Point(event.getX(), event.getY());
   int position = textPane.viewToModel(point);
   DefaultStyledDocument document = (DefaultStyledDocument) textPane.getDocument();
   Element element = document.getCharacterElement(position);
   AttributeSet attributeSet = element.getAttributes();
   String sLink = (String) attributeSet.getAttribute("link");
   if (sLink != null) {
     textPane.setCursor(handCursor);
   } else {
     textPane.setCursor(textCursor);
   }
 }