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);
  }
  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);
    }
  }
Beispiel #3
0
 private void updateDisplay() {
   // first, set block colours
   textView.setBackground(getColour(backgroundColour("text-background-colour")));
   textView.setForeground(getColour(foregroundColour("text-foreground-colour")));
   textView.setCaretColor(getColour(foregroundColour("text-caret-colour")));
   problemsView.setBackground(getColour(backgroundColour("problems-background-colour")));
   problemsView.setForeground(getColour(foregroundColour("problems-foreground-colour")));
   consoleView.setBackground(getColour(backgroundColour("console-background-colour")));
   consoleView.setForeground(getColour(foregroundColour("console-foreground-colour")));
   // second, set colours on the code!
   java.util.List<Lexer.Token> tokens = Lexer.tokenise(textView.getText(), true);
   int pos = 0;
   for (Lexer.Token t : tokens) {
     int len = t.toString().length();
     if (t instanceof Lexer.RightBrace || t instanceof Lexer.LeftBrace) {
       highlightArea(pos, len, foregroundColour("text-brace-colour"));
     } else if (t instanceof Lexer.Strung) {
       highlightArea(pos, len, foregroundColour("text-string-colour"));
     } else if (t instanceof Lexer.Comment) {
       highlightArea(pos, len, foregroundColour("text-comment-colour"));
     } else if (t instanceof Lexer.Quote) {
       highlightArea(pos, len, foregroundColour("text-quote-colour"));
     } else if (t instanceof Lexer.Comma) {
       highlightArea(pos, len, foregroundColour("text-comma-colour"));
     } else if (t instanceof Lexer.Identifier) {
       highlightArea(pos, len, foregroundColour("text-identifier-colour"));
     } else if (t instanceof Lexer.Integer) {
       highlightArea(pos, len, foregroundColour("text-integer-colour"));
     }
     pos += len;
   }
 }
Beispiel #4
0
  // Remove a test case from testBox and tests array.
  private void removeTest() {

    // Make sure they want to remove the checked tests.
    String message = "Are you sure you would like to remove the selected tests?";
    int decision =
        JOptionPane.showConfirmDialog(null, message, "Remove", JOptionPane.OK_CANCEL_OPTION);

    // If they definitely do want to remove.
    if (decision == JOptionPane.OK_OPTION) {

      // Make array list copy, so as to avoid index errors.
      ArrayList<JCheckBox> newTests = (ArrayList<JCheckBox>) tests.clone();
      int removed = 0;

      for (int i = 0; i < tests.size(); i++) {
        if (tests.get(i).isSelected()) {
          // Remove from the tests copy.
          newTests.remove(i - removed);
          // Remove from the GUI box.
          testBox.setEditable(true);
          testBox.remove(tests.get(i));
          testBox.repaint();
          testBox.setEditable(false);
        }
      }

      // Update the tests with the newly made list.
      tests = newTests;
    }
  }
    public void actionPerformed(ActionEvent a) {
      String command = a.getActionCommand();
      if (command.equals("e")) {
        // Log toggle.
        if (consoleDisplayed = !consoleDisplayed) {
          splitter.add(outputScroll);
          splitter.setDividerLocation(.8);
        } else {
          splitter.remove(outputScroll);
        }
      } else if (command.equals("k")) {
        if (text.getText().contains("class")) {
          // This means we should try to compile this as normal.

          // Pulls out class name
          String code = text.getText();
          int firstPos = code.indexOf("class");
          int secondPos = code.indexOf("{");
          String name = code.substring(firstPos + "class".length() + 1, secondPos).trim();

          compileAndRun(name, text.getText());
        } else {
          // This means we should compile this as a playground.
          String code = text.getText();

          // Common import statements built-in
          String importDump = new String();
          importDump +=
              ("import java.util.*;\n"
                  + "import javax.swing.*;\n"
                  + "import javax.swing.event.*;\n"
                  + "import java.awt.*;\n"
                  + "import java.awt.event.*;\n"
                  + "import java.io.*;\n");

          // Pulls out any "import" statements and appends them to the import dump.
          int i = code.indexOf("import");
          while (i >= 0) {
            String s = code.substring(i, code.indexOf(";", i) + 1);
            code = code.replaceFirst(s, "");
            importDump += s + "\n";
            i = code.indexOf("import", i + 1);
          }

          // Inject the class header and main method
          code =
              "//User and auto-imports pre-defined\n"
                  + importDump
                  + "//Autogenerated class\npublic class Main {\npublic static void main(String[] args) {\n"
                  + code
                  + "\n}\n}";

          compileAndRun("Main", code);
        }
      }
    }
 // 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) {
         }
       });
 }
Beispiel #7
0
  private boolean checkForSave() {
    // build warning message
    String message;
    if (file == null) {
      message = "File has been modified.  Save changes?";
    } else {
      message = "File \"" + file.getName() + "\" has been modified.  Save changes?";
    }

    // show confirm dialog
    int r =
        JOptionPane.showConfirmDialog(
            this,
            new JLabel(message),
            "Warning!",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE);

    if (r == JOptionPane.YES_OPTION) {
      // Save File
      if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        // write the file
        physWriteTextFile(fileChooser.getSelectedFile(), textView.getText());
      } else {
        // user cancelled save after all
        return false;
      }
    }
    return r != JOptionPane.CANCEL_OPTION;
  }
Beispiel #8
0
 public void prettyPrint() {
   try {
     // clear old problem messages
     problemsView.setText("");
     // update status view
     statusView.setText(" Parsing ...");
     LispExpr root = Parser.parse(textView.getText());
     statusView.setText(" Pretty Printing ...");
     String newText = PrettyPrinter.prettyPrint(root);
     textView.setText(newText);
     statusView.setText(" Done.");
   } catch (Error e) {
     System.err.println(e.getMessage());
     statusView.setText(" Errors.");
   }
 }
Beispiel #9
0
 public void unbindKey(String keySequence) {
   KeyStroke ks = KeyStroke.getKeyStroke(keySequence);
   if (ks == null) {
     throw new Error("Invalid key sequence \"" + keySequence + "\"");
   }
   textView.getKeymap().removeKeyStrokeBinding(ks);
 }
Beispiel #10
0
 public void evaluate() {
   try {
     // clear problems and console messages
     problemsView.setText("");
     consoleView.setText("");
     // update status view
     statusView.setText(" Parsing ...");
     tabbedPane.setSelectedIndex(0);
     LispExpr root = Parser.parse(textView.getText());
     statusView.setText(" Running ...");
     tabbedPane.setSelectedIndex(1);
     // update run button
     runButton.setIcon(stopImage);
     runButton.setActionCommand("Stop");
     // start run thread
     runThread = new RunThread(root);
     runThread.start();
   } catch (SyntaxError e) {
     tabbedPane.setSelectedIndex(0);
     System.err.println(
         "Syntax Error at " + e.getLine() + ", " + e.getColumn() + " : " + e.getMessage());
   } catch (Error e) {
     // parsing error
     System.err.println(e.getMessage());
     statusView.setText(" Errors.");
   }
 }
    /**
     * Gets the displayed value, and uses the converter to convert the shared value to units this
     * instance is supposed to represent. If the displayed value and shared value are different,
     * then we turn off our document filter and update our value to match the shared value. We
     * re-enable the document filter afterwards.
     */
    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      try {
        StyledDocument doc = getStyledDocument();
        double actualValue = (multiplier.getDisplayValue(value.getValue()));
        String actualValueAsString = df.format(actualValue);

        String displayedValue;
        try {
          displayedValue = doc.getText(0, doc.getLength());
        } catch (BadLocationException e) {
          displayedValue = "";
        }
        if (displayedValue.isEmpty()) {
          displayedValue = "0";
        }
        double displayedValueAsDouble = Double.parseDouble(displayedValue);
        if (!actualValueAsString.equals(displayedValue)
            && displayedValueAsDouble != actualValue) // Allow user to enter trailing zeroes.
        {
          bypassFilterAndSetText(doc, actualValueAsString);
        }
      } catch (NumberFormatException e) {
        // Swallow it as it's OK for the user to try and enter non-numbers.
      }
    }
Beispiel #12
0
 public void bindKeyToCommand(String keySequence, LispExpr cmd) {
   // 	see Java API for info on keySequence format
   KeyStroke ks = KeyStroke.getKeyStroke(keySequence);
   if (ks == null) {
     throw new Error("Invalid key sequence \"" + keySequence + "\"");
   }
   textView.getKeymap().addActionForKeyStroke(ks, new KeyAction(cmd));
 }
 void editorPane_keyPressed(KeyEvent e) {
   StyledDocument doc = editorPane.getStyledDocument();
   int pos = editorPane.getCaretPosition();
   int code = e.getKeyCode();
   Element el;
   switch (code) {
     case KeyEvent.VK_BACK_SPACE:
     case KeyEvent.VK_DELETE:
     case KeyEvent.VK_LEFT:
     case KeyEvent.VK_KP_LEFT:
       if (pos == 0) return;
       // we want to get the element to the left of position.
       el = doc.getCharacterElement(pos - 1);
       break;
     case KeyEvent.VK_RIGHT:
     case KeyEvent.VK_KP_RIGHT:
       // we want to get the element to the right of position.
       el = doc.getCharacterElement(pos + 1);
       break;
     default:
       return; // bail we don't handle it.
   }
   AttributeSet attr = el.getAttributes();
   String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute);
   int el_range = el.getEndOffset() - el.getStartOffset() - 1;
   if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) {
     try {
       switch (code) {
         case KeyEvent.VK_BACK_SPACE:
         case KeyEvent.VK_DELETE:
           doc.remove(el.getStartOffset(), el_range);
           break;
         case KeyEvent.VK_LEFT:
         case KeyEvent.VK_KP_LEFT:
           editorPane.setCaretPosition(pos - el_range);
           break;
         case KeyEvent.VK_RIGHT:
         case KeyEvent.VK_KP_RIGHT:
           editorPane.setCaretPosition(pos + (el_range));
           break;
       }
     } catch (BadLocationException ex) {
     }
   }
 }
Beispiel #14
0
 public int getYValueFromOffset(int offset) {
   try {
     return textPane.modelToView(offset).y;
   } catch (Exception e) {
     System.out.println("EditorServer: DocumentPanel: getYValueFromOffset. error");
     e.printStackTrace();
     return 0;
   }
 }
Beispiel #15
0
  // Update the box that shows current actions.
  public void updateGUI(String message) {
    StyledDocument text = updateBox.getStyledDocument();
    SimpleAttributeSet currentWords = new SimpleAttributeSet();
    StyleConstants.setBold(currentWords, true);
    SimpleAttributeSet pastWords = new SimpleAttributeSet();
    StyleConstants.setBold(pastWords, false);

    try {
      text.setCharacterAttributes(0, text.getLength(), pastWords, true);
      text.insertString(0, message + "\n", currentWords);
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      System.err.println("Bad location exception while styling updateBox.");
      e.printStackTrace();
    }

    updateBox.setCaretPosition(0);
  }
 // 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.
     }
   }
 }
Beispiel #17
0
 public void newFile() {
   if (!dirty || checkForSave()) {
     textView.setText("");
     consoleView.setText("");
     problemsView.setText("");
     statusView.setText(" Created new file.");
     file = null;
     // reset dirty bit
     dirty = false;
   }
 }
Beispiel #18
0
 public void saveFile() {
   if (file == null) {
     // first save file, so prompt for name.
     saveFileAs();
   } else {
     // file already named so just write it.
     physWriteTextFile(file, textView.getText());
     // update status
     statusView.setText(" Saved file \"" + file.getName() + "\".");
     // reset dirty bit
     dirty = false;
   }
 }
Beispiel #19
0
 public void saveFileAs() {
   // Force user to enter new file name
   if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
     file = fileChooser.getSelectedFile();
   } else {
     // user cancelled save after all
     return;
   }
   // file selected, so write it.
   physWriteTextFile(file, textView.getText());
   // update status
   statusView.setText(" Saved file \"" + file.getName() + "\".");
   // reset dirty bit
   dirty = false;
 }
Beispiel #20
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);
 }
Beispiel #21
0
 public void openFile() {
   if (!dirty || checkForSave()) {
     if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
       file = fileChooser.getSelectedFile();
     } else {
       // user cancelled open after all
       return;
     }
     // load file into text view
     textView.setText(physReadTextFile(file));
     // update status
     statusView.setText(" Loaded file \"" + file.getName() + "\".");
     // reset dirty bit
     dirty = false;
   }
 }
 // This is used for when the user's code has something wrong.
 // This has checks in place to make some more sense of the error messages.
 // Internal errors should be logged using println and the progErr font.
 private static void logError(String message) {
   if (message.contains("Playground$FrameAction")) {
     // This is a reflection error, so that means that we have a malformed class or method.
     String code = text.getText();
     if (!code.startsWith("public class")) {
       println(
           "Error: You defined a private class. Please use \"public class <classname>\".",
           progErr);
     } else {
       println(
           "Error: Malformed method. Make sure your main method is defined as \"public static void main(<any args>)\".",
           progErr);
     }
   } else {
     println(message, progErr);
   }
 }
  private void insertParameter(ConfigParamDescr descr, String format, int pos) {
    try {
      StyledDocument doc = (StyledDocument) editorPane.getDocument();

      // The component must first be wrapped in a style
      Style style = doc.addStyle("Parameter-" + numParameters, null);
      JLabel label = new JLabel(descr.getDisplayName());
      label.setAlignmentY(0.8f); // make sure we line up
      label.setFont(new Font("Helvetica", Font.PLAIN, 14));
      label.setForeground(Color.BLUE);
      label.setName(descr.getKey());
      label.setToolTipText("key: " + descr.getKey() + "    format: " + format);
      StyleConstants.setComponent(style, label);
      doc.insertString(pos, format, style);
      numParameters++;
    } catch (BadLocationException e) {
    }
  }
 void insertMatchButton_actionPerformed(ActionEvent e) {
   String key = (String) matchComboBox.getSelectedItem();
   String format = (String) matchesKeys.get(key);
   if (key.equals(STRING_LITERAL)) {
     format =
         escapeReservedChars(
             (String)
                 JOptionPane.showInputDialog(
                     this,
                     "Enter the string you wish to match",
                     "String Literal Input",
                     JOptionPane.OK_CANCEL_OPTION));
     if (StringUtil.isNullString(format)) {
       return;
     }
   }
   if (selectedPane == 0) {
     insertText(format, PLAIN_ATTR, editorPane.getSelectionStart());
   } else {
     // add the combobox data value to the edit box
     int pos = formatTextArea.getCaretPosition();
     formatTextArea.insert(format, pos);
   }
 }
Beispiel #25
0
  protected void buildErrorPanel() {
    errorPanel = new JPanel();
    GroupLayout layout = new GroupLayout(errorPanel);
    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);
    errorPanel.setLayout(layout);
    //    errorPanel.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
    errorMessage = new JTextPane();
    errorMessage.setEditable(false);
    errorMessage.setContentType("text/html");
    errorMessage.setText(
        "<html><body>Could not connect to the Processing server.<br>"
            + "Contributions cannot be installed or updated without an Internet connection.<br>"
            + "Please verify your network connection again, then try connecting again.</body></html>");
    errorMessage.setFont(Toolkit.getSansFont(14, Font.PLAIN));
    errorMessage.setMaximumSize(new Dimension(550, 50));
    errorMessage.setOpaque(false);

    StyledDocument doc = errorMessage.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, doc.getLength(), center, false);

    closeButton = new JButton("X");
    closeButton.setContentAreaFilled(false);
    closeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            contribDialog.makeAndShowTab(false, false);
          }
        });
    tryAgainButton = new JButton("Try Again");
    tryAgainButton.setFont(Toolkit.getSansFont(14, Font.PLAIN));
    tryAgainButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            contribDialog.makeAndShowTab(false, true);
            contribDialog.downloadAndUpdateContributionListing(editor.getBase());
          }
        });
    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(errorMessage)
                    .addComponent(
                        tryAgainButton,
                        StatusPanel.BUTTON_WIDTH,
                        StatusPanel.BUTTON_WIDTH,
                        StatusPanel.BUTTON_WIDTH))
            .addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
            .addComponent(closeButton));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout.createParallelGroup().addComponent(errorMessage).addComponent(closeButton))
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(tryAgainButton));
    errorPanel.setBackground(Color.PINK);
    errorPanel.validate();
  }
Beispiel #26
0
 public void actionPerformed(ActionEvent e) {
   textView.paste();
 }
Beispiel #27
0
 private JTextPane makeTextPane(boolean editable) {
   document = new DefaultStyledDocument();
   JTextPane ta = new JTextPane(document);
   ta.setEditable(editable);
   return ta;
 }
Beispiel #28
0
 public void actionPerformed(ActionEvent e) {
   textView.copy();
 }
Beispiel #29
0
 private JTextPane buildEditor() {
   // build the editor pane
   JTextPane ta = makeTextPane(true);
   ta.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
   return ta;
 }
Beispiel #30
0
 public void setCaretPosition(int position) {
   Caret c = textView.getCaret();
   // move the caret
   c.setDot(position);
 }