コード例 #1
0
ファイル: G4PTool.java プロジェクト: hemalchevli/Sketchbook
  /** This is executed every time we launch the tool using the menu item in Processing IDE */
  public void run() {
    GCScheme.makeColorSchemes();

    //		Base base = editor.getBase();
    Sketch sketch = editor.getSketch();
    File sketchFolder = sketch.getFolder();
    File sketchbookFolder = Base.getSketchbookFolder();

    // Provide a warning (first time only) if G4P is not loaded
    if (!g4p_error_shown && !g4pJarExists(Base.getSketchbookLibrariesFolder())) {
      Base.showWarning(
          "GUI Builder error",
          "Although you can use this tool the sketch created will not \nwork because the G4P library needs to be installed.\nSee G4P at http://www.lagers.org.uk/g4p/",
          null);
      g4p_error_shown = true;
    }
    // The tool is not open so create the designer window
    if (dframe == null) {
      // If the gui.pde tab does not exist create it
      if (!guiTabExists(sketch)) {
        sketch.addFile(new File(sketchbookFolder, G4P_TOOL_DATA_FOLDER + SEP + PDE_TAB_NAME));
      }
      // Create data folder if necessary
      sketch.prepareDataFolder();

      // Create a sub-folder called 'GUI_BUILDER_DATA' inside the sketch folder if
      // it doesn't already exist
      File configFolder = new File(sketchFolder, CONFIG_FOLDER);
      if (!configFolder.exists()) {
        configFolder.mkdir();
      }
      dframe = new GuiDesigner(editor);
      System.out.println("===================================================");
      System.out.println("   G4PTool V2.2.1 created by Peter Lager");
      System.out.println("===================================================");

      //			try {
      //				BufferedImage img = ImageIO.read(new File(sketchbookFolder, G4P_TOOL_DATA_FOLDER + SEP +
      // "default_gui_palette.png"));
      //				System.out.println("Image " + img);
      //			} catch (IOException e) {
      //				System.out.println("Unable to load colour schemes");
      //				e.printStackTrace();
      //			}
    }
    // Design window exists so make visible, open to normal size
    // and bring to front.
    dframe.setVisible(true);
    dframe.setExtendedState(JFrame.NORMAL);
    dframe.toFront();
  }
コード例 #2
0
ファイル: Compiler.java プロジェクト: wesen/mididuino
  public static List<String> getLibraries(String path, Target target) {
    List<String> result = new ArrayList<String>();
    try {
      Sketch sketch = new Sketch(null, path);
      sketch.preprocess(Base.getBuildFolder().getAbsolutePath(), target);

      Vector<Library> libraries = new Vector<Library>();
      LibraryManager libraryManager = new LibraryManager();
      for (File file : sketch.getImportedLibraries()) {
        String item = file.getName();
        libraryManager.addLibrary(libraries, libraryManager.get(item), true);
      }

      String prefLibs = Preferences.get("boards." + Preferences.get("board") + ".build.libraries");
      if (prefLibs != null) {
        String[] boardLibraries = prefLibs.trim().split("\\s+");
        for (String item : boardLibraries) {
          libraryManager.addLibrary(libraries, libraryManager.get(item), true);
        }
      }

      for (Library library : libraries) {
        result.add(library.getName());
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (RunnerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return result;
  }
コード例 #3
0
ファイル: JavaMode.java プロジェクト: gamehawk197/processing
  void initLogger() {
    final boolean VERBOSE_LOGGING = true;
    final int LOG_SIZE = 512 * 1024; // max log file size (in bytes)

    Logger globalLogger = Logger.getLogger("");
    // Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); // doesn't work on os x
    if (VERBOSE_LOGGING) {
      globalLogger.setLevel(Level.INFO);
    } else {
      globalLogger.setLevel(Level.WARNING);
    }

    // enable logging to file
    try {
      // settings is writable for built-in modes, mode folder is not writable
      File logFolder = Base.getSettingsFile("debug");
      if (!logFolder.exists()) {
        logFolder.mkdir();
      }
      File logFile = new File(logFolder, "DebugMode.%g.log");
      Handler handler = new FileHandler(logFile.getAbsolutePath(), LOG_SIZE, 10, false);
      globalLogger.addHandler(handler);

    } catch (IOException ex) {
      Logger.getLogger(JavaMode.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
      Logger.getLogger(JavaMode.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #4
0
  /** Add import statements to the current tab for all of packages inside the specified jar file. */
  public void handleImportLibrary(String jarPath) {
    // make sure the user didn't hide the sketch folder
    sketch.ensureExistence();

    // import statements into the main sketch file (code[0])
    // if the current code is a .java file, insert into current
    // if (current.flavor == PDE) {
    if (mode.isDefaultExtension(sketch.getCurrentCode())) {
      sketch.setCurrentCode(0);
    }

    // could also scan the text in the file to see if each import
    // statement is already in there, but if the user has the import
    // commented out, then this will be a problem.
    String[] list = Base.packageListFromClassPath(jarPath);
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < list.length; i++) {
      buffer.append("import ");
      buffer.append(list[i]);
      buffer.append(".*;\n");
    }
    buffer.append('\n');
    buffer.append(getText());
    setText(buffer.toString());
    setSelection(0, 0); // scroll to start
    sketch.setModified(true);
  }
コード例 #5
0
ファイル: Runner.java プロジェクト: hsiaotaiyeh/processing
  protected Connector findConnector(String connectorName) {
    //    List connectors =
    //      com.sun.jdi.Bootstrap.virtualMachineManager().allConnectors();
    List connectors = org.eclipse.jdi.Bootstrap.virtualMachineManager().allConnectors();

    //    // debug: code to list available connectors
    //    Iterator iter2 = connectors.iterator();
    //    while (iter2.hasNext()) {
    //      Connector connector = (Connector)iter2.next();
    //      System.out.println("connector name is " + connector.name());
    //    }

    for (Object c : connectors) {
      Connector connector = (Connector) c;
      //      System.out.println(connector.name());
      //    }
      //    Iterator iter = connectors.iterator();
      //    while (iter.hasNext()) {
      //      Connector connector = (Connector)iter.next();
      if (connector.name().equals(connectorName)) {
        return connector;
      }
    }
    Base.showError(
        "Compiler Error",
        "findConnector() failed to find " + connectorName + " inside Runner",
        null);
    return null; // Not reachable
  }
コード例 #6
0
  /**
   * Removes import statements from tabSource, replaces each with white spaces and adds the import
   * to the list of program imports
   *
   * @param tabProgram - Code in a tab
   * @param tabNumber - index of the tab
   * @return String - Tab code with imports replaced with white spaces
   */
  private String scrapImportStatements(String tabProgram, int tabNumber) {

    String tabSource = new String(tabProgram);
    do {
      // System.out.println("-->\n" + sourceAlt + "\n<--");
      String[] pieces = PApplet.match(tabSource, importRegexp);

      // Stop the loop if we've removed all the import lines
      if (pieces == null) break;

      String piece = pieces[1] + pieces[2] + pieces[3];
      int len = piece.length(); // how much to trim out

      // programImports.add(piece); // the package name

      // find index of this import in the program
      int idx = tabSource.indexOf(piece);
      // System.out.print("Import -> " + piece);
      // System.out.println(" - "
      // + Base.countLines(tabSource.substring(0, idx)) + " tab "
      // + tabNumber);
      programImports.add(
          new ImportStatement(piece, tabNumber, Base.countLines(tabSource.substring(0, idx))));
      // Remove the import from the main program
      // Substitue with white spaces
      String whiteSpace = "";
      for (int j = 0; j < piece.length(); j++) {
        whiteSpace += " ";
      }
      tabSource = tabSource.substring(0, idx) + whiteSpace + tabSource.substring(idx + len);

    } while (true);
    // System.out.println(tabSource);
    return tabSource;
  }
コード例 #7
0
ファイル: AVD.java プロジェクト: Misas/processing-android
  protected boolean create(final AndroidSDK sdk) throws IOException {
    final String[] params = {
      sdk.getAndroidToolPath(),
      "create",
      "avd",
      "-n",
      name,
      "-t",
      target,
      "-c",
      DEFAULT_SDCARD_SIZE,
      "-s",
      DEFAULT_SKIN,
      "--abi",
      "armeabi"
    };

    // Set the list to null so that exists() will check again
    avdList = null;

    final ProcessHelper p = new ProcessHelper(params);
    try {
      // Passes 'no' to "Do you wish to create a custom hardware profile [no]"
      //      System.out.println("CREATE AVD STARTING");
      final ProcessResult createAvdResult = p.execute("no");
      //      System.out.println("CREATE AVD HAS COMPLETED");
      if (createAvdResult.succeeded()) {
        return true;
      }
      if (createAvdResult.toString().contains("Target id is not valid")) {
        // They didn't install the Google APIs
        Base.showWarningTiered("Android Error", AVD_TARGET_PRIMARY, AVD_TARGET_SECONDARY, null);
        //        throw new IOException("Missing required SDK components");
      } else {
        // Just generally not working
        //        Base.showWarning("Android Error", AVD_CREATE_ERROR, null);
        Base.showWarningTiered("Android Error", AVD_CREATE_PRIMARY, AVD_CREATE_SECONDARY, null);
        System.out.println(createAvdResult);
        //        throw new IOException("Error creating the AVD");
      }
      // System.err.println(createAvdResult);
    } catch (final InterruptedException ie) {
    }

    return false;
  }
コード例 #8
0
  @Override
  public void run() {
    updateContributionIndex();
    updateLibrariesIndex();

    long updatablePlatforms =
        BaseNoGui.indexer
            .getPackages()
            .stream()
            .flatMap(pack -> pack.getPlatforms().stream())
            .filter(new UpdatablePlatformPredicate())
            .count();

    long updatableLibraries =
        BaseNoGui.librariesIndexer
            .getInstalledLibraries()
            .stream()
            .filter(new UpdatableLibraryPredicate())
            .count();

    if (updatableLibraries <= 0 && updatablePlatforms <= 0) {
      return;
    }

    String text;
    if (updatableLibraries > 0 && updatablePlatforms <= 0) {
      text =
          I18n.format(
              tr("Updates available for some of your {0}libraries{1}"),
              "<a href=\"http://librarymanager\">",
              "</a>");
    } else if (updatableLibraries <= 0 && updatablePlatforms > 0) {
      text =
          I18n.format(
              tr("Updates available for some of your {0}boards{1}"),
              "<a href=\"http://boardsmanager\">",
              "</a>");
    } else {
      text =
          I18n.format(
              tr("Updates available for some of your {0}boards{1} and {2}libraries{3}"),
              "<a href=\"http://boardsmanager\">",
              "</a>",
              "<a href=\"http://librarymanager\">",
              "</a>");
    }

    if (cancelled) {
      return;
    }

    SwingUtilities.invokeLater(
        () -> {
          notificationPopup =
              new NotificationPopup(base.getActiveEditor(), hyperlinkListener, text);
          notificationPopup.setVisible(true);
        });
  }
コード例 #9
0
  protected void updateContributionListing() {
    if (editor != null) {
      List<Contribution> contributions = new ArrayList<Contribution>();

      List<Library> libraries = new ArrayList<Library>(editor.getMode().contribLibraries);

      // Only add core libraries that are installed in the sketchbook
      // https://github.com/processing/processing/issues/3688
      // libraries.addAll(editor.getMode().coreLibraries);
      final String sketchbookPath = Base.getSketchbookLibrariesFolder().getAbsolutePath();
      for (Library lib : editor.getMode().coreLibraries) {
        if (lib.getLibraryPath().startsWith(sketchbookPath)) {
          libraries.add(lib);
        }
      }

      contributions.addAll(libraries);

      Base base = editor.getBase();

      List<ToolContribution> tools = base.getToolContribs();
      contributions.addAll(tools);

      List<ModeContribution> modes = base.getModeContribs();
      contributions.addAll(modes);

      List<ExamplesContribution> examples = base.getExampleContribs();
      contributions.addAll(examples);

      //    ArrayList<LibraryCompilation> compilations = LibraryCompilation.list(libraries);
      //
      //    // Remove libraries from the list that are part of a compilations
      //    for (LibraryCompilation compilation : compilations) {
      //      Iterator<Library> it = libraries.iterator();
      //      while (it.hasNext()) {
      //        Library current = it.next();
      //        if (compilation.getFolder().equals(current.getFolder().getParentFile())) {
      //          it.remove();
      //        }
      //      }
      //    }

      contribListing.updateInstalledList(contributions);
    }
  }
コード例 #10
0
ファイル: Runner.java プロジェクト: nconfrey/processing
  public Runner(JavaBuild build, RunnerListener listener) throws SketchException {
    this.listener = listener;
    //    this.sketch = sketch;
    this.build = build;

    if (listener instanceof Editor) {
      this.editor = (Editor) listener;
      sketchErr = editor.getConsole().getErr();
      sketchOut = editor.getConsole().getOut();
    } else {
      sketchErr = System.err;
      sketchOut = System.out;
    }

    // Make sure all the imported libraries will actually run with this setup.
    int bits = Base.getNativeBits();
    for (Library library : build.getImportedLibraries()) {
      if (!library.supportsArch(PApplet.platform, bits)) {
        sketchErr.println(library.getName() + " does not run in " + bits + "-bit mode.");
        int opposite = (bits == 32) ? 64 : 32;
        if (Base.isMacOS()) {
          // if (library.supportsArch(PConstants.MACOSX, opposite)) {  // should always be true
          throw new SketchException(
              "To use "
                  + library.getName()
                  + ", "
                  + "switch to "
                  + opposite
                  + "-bit mode in Preferences.");
          // }
        } else {
          throw new SketchException(
              library.getName()
                  + " is only compatible "
                  + "with the  "
                  + opposite
                  + "-bit download of Processing.");
          // throw new SketchException(library.getName() + " does not run in " + bits + "-bit
          // mode.");
          // "To use this library, switch to 32-bit mode in Preferences." (OS X)
          //  "To use this library, you must use the 32-bit version of Processing."
        }
      }
    }
  }
コード例 #11
0
 /** Prints out classpath elements per line. Used for debugging only. */
 public static void showClassPath() {
   System.out.println("------Classpath------");
   String cps[] =
       PApplet.split(System.getProperty("java.class.path"), Base.isWindows() ? ';' : ':');
   for (int i = 0; i < cps.length; i++) {
     System.out.println(cps[i]);
   }
   System.out.println("---------------------");
 }
コード例 #12
0
  public void init(Editor _editor) {
    this.m_editor = _editor;

    File toolRoot = null;
    try {
      toolRoot =
          new File(
                  SequantoAutomationTool.class
                      .getProtectionDomain()
                      .getCodeSource()
                      .getLocation()
                      .toURI())
              .getParentFile()
              .getParentFile();
    } catch (java.net.URISyntaxException ex) {
      toolRoot =
          new File(
                  SequantoAutomationTool.class
                      .getProtectionDomain()
                      .getCodeSource()
                      .getLocation()
                      .getPath())
              .getParentFile()
              .getParentFile();
    }

    m_generatorPy =
        new File(new File(toolRoot, "generator"), "generate_automation_defines.py")
            .getAbsolutePath();
    m_isWindows = System.getProperty("os.name").toLowerCase().contains("win");
    if (m_isWindows) {
      for (File root : File.listRoots()) {
        File[] files =
            root.listFiles(
                new FileFilter() {
                  public boolean accept(File f) {
                    return f.getName().toLowerCase().startsWith("python");
                  }
                });
        if (files != null) {
          for (File directory : files) {
            m_pythonPath = new File(directory, "python.exe");
            break;
          }
        }
      }
      if (m_pythonPath == null) {
        Base.showMessage(
            "ERROR",
            String.format(
                "Could not python interpreter - Generate Automation tool will not work."));
      }
    }
  }
コード例 #13
0
ファイル: JavaMode.java プロジェクト: Revlin/processing
 public Library getCoreLibrary() {
   if (coreLibrary == null) {
     File coreFolder = Base.getContentFile("core");
     coreLibrary = new Library(coreFolder);
     //      try {
     //        coreLibrary = getLibrary("processing.core");
     //        System.out.println("core found at " + coreLibrary.getLibraryPath());
     //      } catch (SketchException e) {
     //        Base.log("Serious problem while locating processing.core", e);
     //      }
   }
   return coreLibrary;
 }
コード例 #14
0
ファイル: AVD.java プロジェクト: Misas/processing-android
 public static boolean ensureProperAVD(final AndroidSDK sdk) {
   try {
     if (defaultAVD.exists(sdk)) {
       //        System.out.println("the avd exists");
       return true;
     }
     //      if (badList.contains(defaultAVD)) {
     if (defaultAVD.badness()) {
       //        Base.showWarning("Android Error", AVD_CANNOT_LOAD, null);
       Base.showWarningTiered("Android Error", AVD_LOAD_PRIMARY, AVD_LOAD_SECONDARY, null);
       return false;
     }
     if (defaultAVD.create(sdk)) {
       //        System.out.println("the avd was created");
       return true;
     }
   } catch (final Exception e) {
     //      Base.showWarning("Android Error", AVD_CREATE_ERROR, e);
     Base.showWarningTiered("Android Error", AVD_CREATE_PRIMARY, AVD_CREATE_SECONDARY, null);
   }
   System.out.println("at bottom of ensure proper");
   return false;
 }
コード例 #15
0
  public void show() {
    if (editor.getSketch().isModified()) {
      Base.showWarning(
          "Directives Editor",
          "Please save your sketch before changing " + "the directives.",
          null);
      return;
    }

    resetInterface();
    findRemoveDirectives(false);

    frame.setVisible(true);
  }
コード例 #16
0
  /** Handler for Sketch &rarr; Export Application */
  public void handleExportApplication() {
    toolbar.activate(JavaToolbar.EXPORT);

    if (handleExportCheckModified()) {
      statusNotice("Exporting application...");
      try {
        if (exportApplicationPrompt()) {
          Base.openFolder(sketch.getFolder());
          statusNotice("Done exporting.");
        } else {
          // error message will already be visible
          // or there was no error, in which case it was canceled.
        }
      } catch (Exception e) {
        statusNotice("Error during export.");
        e.printStackTrace();
      }
    }
    toolbar.deactivate(JavaToolbar.EXPORT);
  }
コード例 #17
0
  /** Execute a JRuby Script If the script name is not null, this executes it. */
  void executeJRubyScript(String scriptName) {

    if (scriptName != null) {

      ScriptRunner myScript = new ScriptRunner(jrubyPath + "jruby.bat", jrubyPath + "jruby");

      try {
        myScript.run(scriptPath + scriptName);
        System.out.println(myScript.getScriptOutput());
        ((WingFooter) wingFooter).setText(" Script finished.");
      } catch (Exception e) {
        Base.showWarning("JRuby Error", "Could not find the JRuby Compiler\n", null);
        e.printStackTrace();
      }

    } else {
      /* Display the issue */
      wingFooter.setText("Select a script to run.");
    }
  }
コード例 #18
0
ファイル: kCodeWindow.java プロジェクト: agness/Kaleido
  /**
   * Constructor: The one we're working on right now.
   *
   * @param id
   * @param label
   * @param desktop
   */
  public kCodeWindow(String id, String label, JDesktopPane desktop) {

    this.id = id;
    this.desktop = desktop;

    // make the editor portions

    TextAreaDefaults editareaSettings = new PdeTextAreaDefaults();
    editareaSettings.rows = TEXTAREA_DEFAULT_ROWS;
    editareaSettings.cols = TEXTAREA_DEFAULT_COLS;
    textarea = new JEditTextArea(editareaSettings);
    textarea.getDocument().setTokenMarker(Editor.pdeTokenMarker);
    textarea.setEventsEnabled(
        false); // suppress JEditTextArea events (not that anyone is listening to it)
    textarea.setEditable(true);
    textarea.setHorizontalOffset(TEXTAREA_HORIZ_OFFSET);
    textarea.getPainter().setLineHighlightEnabled(false); // else looks funny
    textarea.getPainter().setBackground(kConstants.CODE_WINDOW_COLOR);
    setShortcutKeystrokes();
    JScrollPane scrollPane = new JScrollPane(textarea);
    scrollPane.setBorder(null);
    //    scrollPane.setOpaque(true);

    editFrame = new JInternalFrame(label, true, false, false, false);
    editFrame.setContentPane(textarea);
    editFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    editFrame.setSize(editFrame_DEFAULT_WIDTH, editFrame_DEFAULT_HEIGHT);
    editFrame.setBorder(null);
    editFrame.setOpaque(true);

    // make the triangle
    triangleFrame = new JInternalFrame("", false, false, false, false);
    triangleFrame.setOpaque(false);
    triangleFrame
        .getRootPane()
        .setBackground(new Color(0, 0, 0, 0)); // needs this to actually do the trick
    triangleFrame.setContentPane(
        new Triangle("SE", 0, TRIANGLE_BASE, TRIANGLE_DEFAULT_HEIGHT, TRIANGLE_BASE));
    triangleFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    triangleFrame.setSize(TRIANGLE_BASE, TRIANGLE_DEFAULT_HEIGHT);
    triangleFrame.setBorder(null);

    // remove the ability to move the triangle iframe
    MouseMotionListener[] actions =
        (MouseMotionListener[]) triangleFrame.getListeners(MouseMotionListener.class);
    for (int i = 0; i < actions.length; i++) triangleFrame.removeMouseMotionListener(actions[i]);

    // make the buttons
    moveButton = new JButton(Base.getImageIcon("codewindow-activ-move.gif", desktop));
    moveButton.setDisabledIcon(Base.getImageIcon("codewindow-inact-move.gif", desktop));
    moveButton.setVisible(true);
    moveButton.setBorder(null);
    moveButton.setOpaque(false);
    moveButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
    closeButton = new JButton(Base.getImageIcon("codewindow-activ-close.gif", desktop));
    closeButton.setDisabledIcon(Base.getImageIcon("codewindow-inact-close.gif", desktop));
    closeButton.setVisible(true);
    closeButton.setBorder(null);
    closeButton.setOpaque(false);
    closeButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 0));
    buttonPanel.setBorder(null);
    buttonPanel.setOpaque(false);
    buttonPanel.add(moveButton);
    buttonPanel.add(closeButton);

    buttonFrame = new JInternalFrame("", false, false, false, false);
    buttonFrame.setContentPane(buttonPanel);
    buttonFrame.setOpaque(false);
    buttonFrame.getRootPane().setBackground(new Color(0, 0, 0, 0));
    buttonFrame.setSize(BUTTON_ICON_WIDTH * 2 + BUTTON_GAP, BUTTON_ICON_HEIGHT);
    buttonFrame.setBorder(null);

    // myriad event handling

    installFocusHandlers(buttonPanel);

    // hide code window when escape key is hit
    textarea.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) setVisible(false);
          }
        });
    // add dragging function of the move button,
    // reset the triangle after mouse release, and shift the editFrame
    // along with the mouse when the user is moving the window
    mxMouseControl moveListener = createMoveListener();
    moveButton.addMouseListener(moveListener);
    moveButton.addMouseMotionListener(moveListener);
    closeButton.addMouseListener(createCloseListener());
    // listens to resizing of editFrame and adjusts the position of the
    // buttons and the shape of the triangle accordingly
    editFrame.addComponentListener(createResizeListener());
    // when code windows are on top of each other, layers them correctly
    // such that when the user clicks on any part of a code window
    // all three component internal frames are brought to the top
    // so they appear "focused" also
    InternalFrameListener iframeListener =
        new InternalFrameAdapter() {
          public void internalFrameActivated(InternalFrameEvent e) {
            moveToFrontLayer();
          }

          public void internalFrameDeactivated(InternalFrameEvent e) {
            moveToBackLayer();
          }
        };
    editFrame.addInternalFrameListener(iframeListener);
    buttonFrame.addInternalFrameListener(iframeListener);
    triangleFrame.addInternalFrameListener(iframeListener);

    // add everything to desktop

    desktop.add(editFrame);
    desktop.add(buttonFrame);
    desktop.add(triangleFrame);
    moveToBackLayer();
  }
コード例 #19
0
  public void run() {
    if (!new File(m_generatorPy).exists()) {
      Base.showMessage(
          "ERROR", String.format("Could not find generator python script at %s", m_generatorPy));
    }
    Sketch sketch = m_editor.getSketch();
    if (sketch.isModified()) {
      try {
        sketch.save();
      } catch (java.io.IOException ex) {
        // Base.showMessage("ERROR", "Could not save sketch before trying to generate." );
      }
    }

    // String sketchName = sketch.getName();
    // SketchCode codeObject = sketch.getCurrentCode();
    // String code = codeObject.getProgram();
    try {
      String code = m_editor.getCurrentTab().getText();
      // String code = m_editor.getText();
      int start = code.indexOf("BEGIN AUTOMATION");
      if (start != -1) {
        int end = code.indexOf("END AUTOMATION", start);
        if (end != -1) {
          String automationCode = code.substring(start + "BEGIN AUTOMATION".length(), end);
          automationCode = automationCode.replaceAll("\\*\\s+", "");
          // SketchData sketchData = new MySketchData(sketch.getMainFilePath());
          // File buildFolder = BaseNoGui.getBuildFolder(sketchData);
          File buildFolder = getBuildFolder(sketch);
          // File codeFolder = sketchData.getCodeFolder();
          File codeFolder = new File(sketch.getFolder(), "code");
          Files.createDirectories(codeFolder.toPath());
          File automationFileName = new File(buildFolder, "automation.automation");
          FileWriter writer = new FileWriter(automationFileName);
          writer.write("name automation\n");
          writer.write("import " + sketch.getMainFilePath().toString() + "\n");
          writer.write(automationCode);
          writer.close();

          try {
            ProcessBuilder processBuilder = null;
            if (m_isWindows) {
              processBuilder =
                  new ProcessBuilder(
                      m_pythonPath.getAbsolutePath(),
                      m_generatorPy,
                      "-s",
                      "--arduino",
                      automationFileName.getAbsolutePath());
            } else {
              processBuilder =
                  new ProcessBuilder(
                      m_generatorPy, "-s", "--arduino", automationFileName.getAbsolutePath());
            }
            processBuilder.directory(codeFolder);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            inheritIO(process.getInputStream(), System.out);
            int result = process.waitFor();

            String includeLibLine = "#include \"SequantoAutomation.h\"\n";
            if (!code.contains(includeLibLine)) {
              code = includeLibLine + code;
            }

            /*
              File generatedFileName = new File(codeFolder, "automation_automation.c" );
              String includeLine = String.format("#include \"%s\"\n", generatedFileName.getAbsolutePath());
              if ( !code.contains(includeLine) )
              {
              int i = code.indexOf(includeLibLine);
              code = code.substring(0, i + includeLibLine.length()) +
              includeLine +
              code.substring ( i + includeLibLine.length(), code.length() );
              }
            */

            String includeLine = String.format("#include \"code/automation_automation.h\"\n");
            if (!code.contains(includeLine)) {
              int i = code.indexOf(includeLibLine);
              code =
                  code.substring(0, i + includeLibLine.length())
                      + includeLine
                      + code.substring(i + includeLibLine.length(), code.length());
            }

            String includeCodeLine = String.format("\n#include \"code/automation_automation.c\"\n");
            if (!code.contains(includeCodeLine)) {
              code = code + includeCodeLine;
            }

            if (m_editor.getCurrentTab().getText() != code) {
              // System.out.println ( "Setting code to" );
              // System.out.println ( code );
              // System.out.println ( "Current text was" );
              // System.out.println ( m_editor.getText() );
              m_editor.getCurrentTab().setText(code);
            }

            if (result == 0) {
              System.out.println("Sequanto automation code generated successfully!");
            } else {
              System.out.println("ERROR!!!");
            }
          } catch (Exception ex) {
            Base.showMessage("ERROR", String.format("Could not start generator script: %s", ex));
          }
        } else {
          Base.showMessage("ERROR", "Can not find END AUTOMATION.");
        }
      } else {
        Base.showMessage("ERROR", "Can not find BEGIN AUTOMATION.");
      }
    } catch (java.io.IOException ex) {
      Base.showMessage("ERROR", String.format("IO Error: %s.", ex));
    }
  }
コード例 #20
0
ファイル: Runner.java プロジェクト: hsiaotaiyeh/processing
  /**
   * Provide more useful explanations of common error messages, perhaps with a short message in the
   * status area, and (if necessary) a longer message in the console.
   *
   * @param exceptionClass Class name causing the error (with full package name)
   * @param message The message from the exception
   * @param listener The Editor or command line interface that's listening for errors
   * @return true if the error was purtified, false otherwise
   */
  public static boolean handleCommonErrors(
      final String exceptionClass, final String message, final RunnerListener listener) {
    if (exceptionClass.equals("java.lang.OutOfMemoryError")) {
      if (message.contains("exceeds VM budget")) {
        // TODO this is a kludge for Android, since there's no memory preference
        listener.statusError(
            "OutOfMemoryError: This code attempts to use more memory than available.");
        System.err.println(
            "An OutOfMemoryError means that your code is either using up too much memory");
        System.err.println(
            "because of a bug (e.g. creating an array that's too large, or unintentionally");
        System.err.println(
            "loading thousands of images), or simply that it's trying to use more memory");
        System.err.println("than what is supported by the current device.");
      } else {
        listener.statusError(
            "OutOfMemoryError: You may need to increase the memory setting in Preferences.");
        System.err.println(
            "An OutOfMemoryError means that your code is either using up too much memory");
        System.err.println(
            "because of a bug (e.g. creating an array that's too large, or unintentionally");
        System.err.println(
            "loading thousands of images), or that your sketch may need more memory to run.");
        System.err.println(
            "If your sketch uses a lot of memory (for instance if it loads a lot of data files)");
        System.err.println(
            "you can increase the memory available to your sketch using the Preferences window.");
      }
    } else if (exceptionClass.equals("java.lang.UnsatisfiedLinkError")) {
      listener.statusError("A library used by this sketch is not installed properly.");
      System.err.println("A library relies on native code that's not available.");
      System.err.println(
          "Or only works properly when the sketch is run as a "
              + ((Base.getNativeBits() == 32) ? "64-bit " : "32-bit ")
              + " application.");

    } else if (exceptionClass.equals("java.lang.StackOverflowError")) {
      listener.statusError("StackOverflowError: This sketch is attempting too much recursion.");
      System.err.println(
          "A StackOverflowError means that you have a bug that's causing a function");
      System.err.println("to be called recursively (it's calling itself and going in circles),");
      System.err.println("or you're intentionally calling a recursive function too much,");
      System.err.println("and your code should be rewritten in a more efficient manner.");

    } else if (exceptionClass.equals("java.lang.UnsupportedClassVersionError")) {
      listener.statusError(
          "UnsupportedClassVersionError: A library is using code compiled with an unsupported version of Java.");
      System.err.println(
          "This version of Processing only supports libraries and JAR files compiled for Java 1.6 or earlier.");
      System.err.println("A library used by this sketch was compiled for Java 1.7 or later, ");
      System.err.println("and needs to be recompiled to be compatible with Java 1.6.");

    } else if (exceptionClass.equals("java.lang.NoSuchMethodError")
        || exceptionClass.equals("java.lang.NoSuchFieldError")) {
      listener.statusError(
          exceptionClass.substring(10)
              + ": "
              + "You may be using a library that's incompatible "
              + "with this version of Processing.");
    } else {
      return false;
    }
    return true;
  }
コード例 #21
0
ファイル: Compiler.java プロジェクト: wesen/mididuino
  public static void main(String args[]) {
    String midictrlDir = null;
    String board = "minicommand2";

    if (args.length <= 1) {
      return;
    }
    java.util.List printList = new ArrayList();

    int i;
    for (i = 0; i < args.length; i++) {
      if (args[i].equals("--board")) {
        board = args[i + 1];
        i++;
      } else if (args[i].equals("--dir")) {
        midictrlDir = args[i + 1];
        i++;
      } else {
        break;
      }
    }

    if (midictrlDir == null) {
      midictrlDir = System.getProperty("user.dir");
    }

    String hardwarePath =
        (midictrlDir != null ? midictrlDir : System.getProperty("user.dir"))
            + File.separator
            + "hardware";
    Base.init(midictrlDir);
    Target target = null;
    Preferences.initBoards(midictrlDir);
    Preferences.set("board", board);
    try {
      target =
          new Target(
              hardwarePath + File.separator + "cores",
              Preferences.get("boards." + Preferences.get("board") + ".build.core"));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    for (i = 0; i < args.length; i++) {
      if (args[i].equals("--print-c-flags")) {
        PrintList(Compiler.getCompilerFlags());
      } else if (args[i].equals("--print-cxx-flags")) {
        PrintList(Compiler.getCompilerFlags());
      } else if (args[i].equals("--print-ld-flags")) {
        PrintList(Compiler.getLinkerFlags());
      } else if (args[i].equals("--libraries")) {
        PrintList(Compiler.getLibraries(args[i + 1], target));
      } else if (args[i].equals("--make")) {
        System.out.print("MIDICTRL_LIBS += ");
        PrintList(Compiler.getLibraries(args[i + 1], target));
        System.out.print("CFLAGS += ");
        PrintList(Compiler.getCompilerFlags());
        System.out.print("CXXFLAGS += ");
        PrintList(Compiler.getCompilerFlags());
        System.out.print("CLDFLAGS += ");
        PrintList(Compiler.getLinkerFlags());
      }
    }
  }
コード例 #22
0
ファイル: Runner.java プロジェクト: hsiaotaiyeh/processing
  protected String[] getMachineParams() {
    ArrayList<String> params = new ArrayList<String>();

    // params.add("-Xint"); // interpreted mode
    // params.add("-Xprof");  // profiler
    // params.add("-Xaprof");  // allocation profiler
    // params.add("-Xrunhprof:cpu=samples");  // old-style profiler

    // TODO change this to use run.args = true, run.args.0, run.args.1, etc.
    // so that spaces can be included in the arg names
    String options = Preferences.get("run.options");
    if (options.length() > 0) {
      String pieces[] = PApplet.split(options, ' ');
      for (int i = 0; i < pieces.length; i++) {
        String p = pieces[i].trim();
        if (p.length() > 0) {
          params.add(p);
        }
      }
    }

    //    params.add("-Djava.ext.dirs=nuffing");

    if (Preferences.getBoolean("run.options.memory")) {
      params.add("-Xms" + Preferences.get("run.options.memory.initial") + "m");
      params.add("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
    }

    if (Base.isMacOS()) {
      params.add("-Xdock:name=" + build.getSketchClassName());
      //      params.add("-Dcom.apple.mrj.application.apple.menu.about.name=" +
      //                 sketch.getMainClassName());
    }
    // sketch.libraryPath might be ""
    // librariesClassPath will always have sep char prepended
    params.add(
        "-Djava.library.path="
            + build.getJavaLibraryPath()
            + File.pathSeparator
            + System.getProperty("java.library.path"));

    params.add("-cp");
    params.add(build.getClassPath());
    //    params.add(sketch.getClassPath() +
    //        File.pathSeparator +
    //        Base.librariesClassPath);

    // enable assertions
    // http://dev.processing.org/bugs/show_bug.cgi?id=1188
    params.add("-ea");
    // PApplet.println(PApplet.split(sketch.classPath, ':'));

    String outgoing[] = new String[params.size()];
    params.toArray(outgoing);

    //    PApplet.println(outgoing);
    //    PApplet.println(PApplet.split(outgoing[0], ":"));
    //    PApplet.println();
    //    PApplet.println("class path");
    //    PApplet.println(PApplet.split(outgoing[2], ":"));

    return outgoing;
    // return (String[]) params.toArray();

    //  System.out.println("sketch class path");
    //  PApplet.println(PApplet.split(sketch.classPath, ';'));
    //  System.out.println();
    //  System.out.println("libraries class path");
    //  PApplet.println(PApplet.split(Base.librariesClassPath, ';'));
    //  System.out.println();
  }
コード例 #23
0
ファイル: JavaMode.java プロジェクト: gamehawk197/processing
 public static void main(String[] args) {
   processing.app.Base.main(args);
 }
コード例 #24
0
ファイル: Compiler.java プロジェクト: CM-9xx/cm9xx
  /**
   * Compile with avr-gcc.
   *
   * @param sketch Sketch object to be compiled.
   * @param buildPath Where the temporary files live and will be built from.
   * @param primaryClassName the name of the combined sketch file w/ extension
   * @return true if successful.
   * @throws RunnerException Only if there's a problem. Only then.
   * 
  * [ROBOTIS]Changed prototype to support ARM Cortex-M3 based CM-900 Pandora project
  * 2012-09-26 [email protected]
  * */
  public boolean compile(Sketch sketch, //change return type[ROBOTIS]
                         String buildPath,
                         String primaryClassName,
                         boolean verbose,
                         List<String> ignored) throws RunnerException {
    this.sketch = sketch;
    this.buildPath = buildPath;
    this.primaryClassName = primaryClassName; //예를 들면 cpp파일로 변환된 AnalogReadSerial.cpp
    this.verbose = verbose;
    this.sketchIsCompiled = false;
    System.out.println("Compiler.compile() sketch ="+sketch.getName()+"buildpath ="+buildPath+"primaryClassName ="+primaryClassName);
    // the pms object isn't used for anything but storage
    MessageStream pms = new MessageStream(this);

    String avrBasePath = Base.getAvrBasePath();
    System.out.println("[ROBOTIS]avrBasePath ="+avrBasePath);
    Map<String, String> boardPreferences = Base.getBoardPreferences();
    String core = boardPreferences.get("build.core");
    System.out.println("[ROBOTIS]build.core ="+core);
    if (core == null) {
    	RunnerException re = new RunnerException(_("No board selected; please choose a board from the Tools > Board menu."));
      re.hideStackTrace();
      throw re;
    }
    String corePath;
    
    if (core.indexOf(':') == -1) {
      Target t = Base.getTarget();
      File coreFolder = new File(new File(t.getFolder(), "cores"), core);
      corePath = coreFolder.getAbsolutePath();
      
    } else {
      Target t = Base.targetsTable.get(core.substring(0, core.indexOf(':')));
      File coreFolder = new File(t.getFolder(), "cores");
      coreFolder = new File(coreFolder, core.substring(core.indexOf(':') + 1));
      corePath = coreFolder.getAbsolutePath();
    }

    System.out.println("[ROBOTIS]corePath ="+corePath);
    
    String variant = boardPreferences.get("build.variant");
    String variantPath = null;
    
    if (variant != null) {
      if (variant.indexOf(':') == -1) {
	Target t = Base.getTarget();
	File variantFolder = new File(new File(t.getFolder(), "variants"), variant);
	variantPath = variantFolder.getAbsolutePath();
      } else {
	Target t = Base.targetsTable.get(variant.substring(0, variant.indexOf(':')));
	File variantFolder = new File(t.getFolder(), "variants");
	variantFolder = new File(variantFolder, variant.substring(variant.indexOf(':') + 1));
	variantPath = variantFolder.getAbsolutePath();
      }
    }

    List<File> objectFiles = new ArrayList<File>();

   // 0. include paths for core + all libraries

   sketch.setCompilingProgress(20);
   List includePaths = new ArrayList();
   includePaths.add(corePath);
   if (variantPath != null) includePaths.add(variantPath);
   for (File file : sketch.getImportedLibraries()) {
     includePaths.add(file.getPath());
   }

   // 1. compile the sketch (already in the buildPath)

   sketch.setCompilingProgress(30);
   objectFiles.addAll(
     compileFiles(avrBasePath, buildPath, includePaths,
               findFilesInPath(buildPath, "S", false),
               findFilesInPath(buildPath, "c", false),
               findFilesInPath(buildPath, "cpp", false),
               boardPreferences));
   sketchIsCompiled = true;

   // 2. compile the libraries, outputting .o files to: <buildPath>/<library>/

   sketch.setCompilingProgress(40);
   for (File libraryFolder : sketch.getImportedLibraries()) {
     File outputFolder = new File(buildPath, libraryFolder.getName());
     File utilityFolder = new File(libraryFolder, "utility");
     createFolder(outputFolder);
     // this library can use includes in its utility/ folder
     includePaths.add(utilityFolder.getAbsolutePath());
     objectFiles.addAll(
       compileFiles(avrBasePath, outputFolder.getAbsolutePath(), includePaths,
               findFilesInFolder(libraryFolder, "S", false),
               findFilesInFolder(libraryFolder, "c", false),
               findFilesInFolder(libraryFolder, "cpp", false),
               boardPreferences));
     outputFolder = new File(outputFolder, "utility");
     createFolder(outputFolder);
     objectFiles.addAll(
       compileFiles(avrBasePath, outputFolder.getAbsolutePath(), includePaths,
               findFilesInFolder(utilityFolder, "S", false),
               findFilesInFolder(utilityFolder, "c", false),
               findFilesInFolder(utilityFolder, "cpp", false),
               boardPreferences));
     // other libraries should not see this library's utility/ folder
     includePaths.remove(includePaths.size() - 1);
   }

   // 3. compile the core, outputting .o files to <buildPath> and then
   // collecting them into the core.a library file.

   sketch.setCompilingProgress(50);
  includePaths.clear();
  includePaths.add(corePath);  // include path for core only
  if (variantPath != null) includePaths.add(variantPath);
  List<File> coreObjectFiles =
    compileFiles(avrBasePath, buildPath, includePaths,
              findFilesInPath(corePath, "S", true),
              findFilesInPath(corePath, "c", true),
              findFilesInPath(corePath, "cpp", true),
              boardPreferences);

   String runtimeLibraryName = buildPath + File.separator + "core.a";
   List baseCommandAR = new ArrayList(Arrays.asList(new String[] {
     avrBasePath + "avr-ar",
     "rcs",
     runtimeLibraryName
   }));
   for(File file : coreObjectFiles) {
     List commandAR = new ArrayList(baseCommandAR);
     commandAR.add(file.getAbsolutePath());
     execAsynchronously(commandAR);
   }

    // 4. link it all together into the .elf file
    // For atmega2560, need --relax linker option to link larger
    // programs correctly.
    String optRelax = "";
    String atmega2560 = new String ("atmega2560");
    if ( atmega2560.equals(boardPreferences.get("build.mcu")) ) {
        optRelax = new String(",--relax");
    }
   sketch.setCompilingProgress(60);
    List baseCommandLinker = new ArrayList(Arrays.asList(new String[] {
      avrBasePath + "avr-gcc",
      "-Os",
      "-Wl,--gc-sections"+optRelax,
      "-mmcu=" + boardPreferences.get("build.mcu"),
      "-o",
      buildPath + File.separator + primaryClassName + ".elf"
    }));

    for (File file : objectFiles) {
      baseCommandLinker.add(file.getAbsolutePath());
    }

    baseCommandLinker.add(runtimeLibraryName);
    baseCommandLinker.add("-L" + buildPath);
    baseCommandLinker.add("-lm");

    execAsynchronously(baseCommandLinker);

    List baseCommandObjcopy = new ArrayList(Arrays.asList(new String[] {
      avrBasePath + "avr-objcopy",
      "-O",
      "-R",
    }));
    
    List commandObjcopy;

    // 5. extract EEPROM data (from EEMEM directive) to .eep file.
    sketch.setCompilingProgress(70);
    commandObjcopy = new ArrayList(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.set(3, "-j");
    commandObjcopy.add(".eeprom");
    commandObjcopy.add("--set-section-flags=.eeprom=alloc,load");
    commandObjcopy.add("--no-change-warnings");
    commandObjcopy.add("--change-section-lma");
    commandObjcopy.add(".eeprom=0");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".eep");
    execAsynchronously(commandObjcopy);
    
    // 6. build the .hex file
    sketch.setCompilingProgress(80);
    commandObjcopy = new ArrayList(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.add(".eeprom"); // remove eeprom data
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".hex");
    execAsynchronously(commandObjcopy);
    
    sketch.setCompilingProgress(90);
   
    return true;
  }
コード例 #25
0
ファイル: Runner.java プロジェクト: hsiaotaiyeh/processing
  public boolean launchVirtualMachine(boolean presenting) {
    String[] vmParams = getMachineParams();
    String[] sketchParams = getSketchParams(presenting);
    int port = 8000 + (int) (Math.random() * 1000);
    String portStr = String.valueOf(port);

    // Older (Java 1.5 and earlier) version, go figure
    //    String jdwpArg = "-Xrunjdwp:transport=dt_socket,address=" + portStr +
    // ",server=y,suspend=y";
    //    String debugArg = "-Xdebug";
    // Newer (Java 1.5+) version that uses JVMTI
    String jdwpArg =
        "-agentlib:jdwp=transport=dt_socket,address=" + portStr + ",server=y,suspend=y";

    // Everyone works the same under Java 7 (also on OS X)
    String[] commandArgs = new String[] {Base.getJavaPath(), jdwpArg};

    /*
        String[] commandArgs = null;
        if (!Base.isMacOS()) {
          commandArgs = new String[] {
            Base.getJavaPath(),
            jdwpArg
          };
        } else {
          // Decided to just set this to 1.6 only, because otherwise it's gonna
          // be a shitshow if folks are getting Apple's 1.6 with 32-bit and
          // Oracle's 1.7 when run in 64-bit mode. ("Why does my sketch suck in
          // 64-bit? Why is retina broken?)
          // The --request flag will prompt to install Apple's 1.6 JVM if none is
          // available. We're specifying 1.6 so that we can get support for both
          // 32- and 64-bit, because Oracle won't be releasing Java 1.7 in 32-bit.
          // Helpfully, the --request flag is not present on Mac OS X 10.6
          // (luckily it is also not needed, because 1.6 is installed by default)
          // but it requires an additional workaround to not use that flag,
          // otherwise will see an error about an unsupported option. The flag is
          // available with 10.7 and 10.8, the only other supported versions of
          // OS X at this point, because we require 10.6.8 and higher. That also
          // means we don't need to check for any other OS versions, the user is
          // a douchebag and modifies Info.plist to get around the restriction.
          if (false) {
            if (System.getProperty("os.version").startsWith("10.6")) {
              commandArgs = new String[] {
                "/usr/libexec/java_home",
                "--version", "1.6",
                "--exec", "java",
                "-d" + Base.getNativeBits(),
                jdwpArg
              };
            } else {  // for 10.7, 10.8, etc
              commandArgs = new String[] {
                "/usr/libexec/java_home",
                "--request",  // install on-demand
                "--version", "1.6",
                "--exec", "java",
                "-d" + Base.getNativeBits(),
    //          debugArg,
                jdwpArg
              };
            }
          } else {
            // testing jdk-7u40
            commandArgs = new String[] {
              //"/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/bin/java",
              Base.getJavaPath(),
              jdwpArg
            };
          }
        }
        */

    commandArgs = PApplet.concat(commandArgs, vmParams);
    commandArgs = PApplet.concat(commandArgs, sketchParams);
    //  PApplet.println(commandArgs);
    //  commandArg.setValue(commandArgs);
    launchJava(commandArgs);

    AttachingConnector connector = (AttachingConnector) findConnector("com.sun.jdi.SocketAttach");
    // PApplet.println(connector);  // gets the defaults

    Map arguments = connector.defaultArguments();

    //  Connector.Argument addressArg =
    //    (Connector.Argument)arguments.get("address");
    //  addressArg.setValue(addr);
    Connector.Argument portArg = (Connector.Argument) arguments.get("port");
    portArg.setValue(portStr);

    //    Connector.Argument timeoutArg =
    //      (Connector.Argument)arguments.get("timeout");
    //    timeoutArg.setValue("10000");

    // PApplet.println(connector);  // prints the current
    // com.sun.tools.jdi.AbstractLauncher al;
    // com.sun.tools.jdi.RawCommandLineLauncher rcll;

    // System.out.println(PApplet.javaVersion);
    // http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#sunlaunch

    try {
      //      boolean available = false;
      //      while (!available) {
      while (true) {
        try {
          vm = connector.attach(arguments);
          //          vm = connector.attach(arguments);
          if (vm != null) {
            //            generateTrace();
            //            available = true;
            return true;
          }
        } catch (IOException e) {
          //          System.out.println("waiting");
          //          e.printStackTrace();
          try {
            Thread.sleep(100);
          } catch (InterruptedException e1) {
            e1.printStackTrace();
          }
        }
      }
      //    } catch (IOException exc) {
      //      throw new Error("Unable to launch target VM: " + exc);
    } catch (IllegalConnectorArgumentsException exc) {
      throw new Error("Internal error: " + exc);
    }
  }
コード例 #26
0
  public JMenu buildHelpMenu() {
    // To deal with a Mac OS X 10.5 bug, add an extra space after the name
    // so that the OS doesn't try to insert its slow help menu.
    JMenu menu = new JMenu("Help ");
    JMenuItem item;

    // macosx already has its own about menu
    if (!Base.isMacOS()) {
      item = new JMenuItem("About Processing");
      item.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              new About(JavaEditor.this);
            }
          });
      menu.add(item);
    }

    item = new JMenuItem("Environment");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            showReference("environment" + File.separator + "index.html");
          }
        });
    menu.add(item);

    item = new JMenuItem("Reference");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            showReference("index.html");
          }
        });
    menu.add(item);

    item = Toolkit.newJMenuItemShift("Find in Reference", 'F');
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (textarea.isSelectionActive()) {
              handleFindReference();
            }
          }
        });
    menu.add(item);

    menu.addSeparator();
    item = new JMenuItem("Online");
    item.setEnabled(false);
    menu.add(item);

    item = new JMenuItem("Getting Started");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Base.openURL("http://processing.org/learning/gettingstarted/");
          }
        });
    menu.add(item);

    item = new JMenuItem("Troubleshooting");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Base.openURL("http://wiki.processing.org/w/Troubleshooting");
          }
        });
    menu.add(item);

    item = new JMenuItem("Frequently Asked Questions");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Base.openURL("http://wiki.processing.org/w/FAQ");
          }
        });
    menu.add(item);

    item = new JMenuItem("Visit Processing.org");
    item.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Base.openURL("http://processing.org/");
          }
        });
    menu.add(item);

    return menu;
  }
コード例 #27
0
ファイル: Uploader.java プロジェクト: yellowpark/Arduino
  protected boolean executeUploadCommand(Collection commandDownloader) throws RunnerException {
    firstErrorFound = false; // haven't found any errors yet
    secondErrorFound = false;
    notFoundError = false;
    int result = 0; // pre-initialized to quiet a bogus warning from jikes

    String userdir = System.getProperty("user.dir") + File.separator;

    try {
      String[] commandArray = new String[commandDownloader.size()];
      commandDownloader.toArray(commandArray);

      String avrBasePath;

      if (Base.isLinux()) {
        avrBasePath = new String(Base.getHardwarePath() + "/tools/");
      } else {
        avrBasePath = new String(Base.getHardwarePath() + "/tools/avr/bin/");
      }

      commandArray[0] = avrBasePath + commandArray[0];

      if (verbose || Preferences.getBoolean("upload.verbose")) {
        for (int i = 0; i < commandArray.length; i++) {
          System.out.print(commandArray[i] + " ");
        }
        System.out.println();
      }
      Process process = Runtime.getRuntime().exec(commandArray);
      new MessageSiphon(process.getInputStream(), this);
      new MessageSiphon(process.getErrorStream(), this);

      // wait for the process to finish.  if interrupted
      // before waitFor returns, continue waiting
      //
      boolean compiling = true;
      while (compiling) {
        try {
          result = process.waitFor();
          compiling = false;
        } catch (InterruptedException intExc) {
        }
      }
      if (exception != null) {
        exception.hideStackTrace();
        throw exception;
      }
      if (result != 0) return false;
    } catch (Exception e) {
      String msg = e.getMessage();
      if ((msg != null)
          && (msg.indexOf("uisp: not found") != -1)
          && (msg.indexOf("avrdude: not found") != -1)) {
        // System.err.println("uisp is missing");
        // JOptionPane.showMessageDialog(editor.base,
        //                              "Could not find the compiler.\n" +
        //                              "uisp is missing from your PATH,\n" +
        //                              "see readme.txt for help.",
        //                              "Compiler error",
        //                              JOptionPane.ERROR_MESSAGE);
        return false;
      } else {
        e.printStackTrace();
        result = -1;
      }
    }
    // System.out.println("result2 is "+result);
    // if the result isn't a known, expected value it means that something
    // is fairly wrong, one possibility is that jikes has crashed.
    //
    if (exception != null) throw exception;

    if ((result != 0) && (result != 1)) {
      exception = new RunnerException(SUPER_BADNESS);
      // editor.error(exception);
      // PdeBase.openURL(BUGS_URL);
      // throw new PdeException(SUPER_BADNESS);
    }

    return (result == 0); // ? true : false;
  }
コード例 #28
0
ファイル: Compiler.java プロジェクト: wesen/mididuino
  /**
   * Compile with avr-gcc.
   *
   * @param sketch Sketch object to be compiled.
   * @param buildPath Where the temporary files live and will be built from.
   * @param primaryClassName the name of the combined sketch file w/ extension
   * @param target the target (core) to build against
   * @return true if successful.
   * @throws RunnerException Only if there's a problem. Only then.
   */
  public boolean compile(Sketch sketch, String buildPath, String primaryClassName, Target target)
      throws RunnerException {
    this.sketch = sketch;
    this.buildPath = buildPath;
    this.primaryClassName = primaryClassName;

    // the pms object isn't used for anything but storage
    MessageStream pms = new MessageStream(this);

    String avrBasePath = Base.getAvrBasePath();

    List<File> objectFiles = new ArrayList<File>();
    List<String> includePaths = new ArrayList<String>();

    try {
      Vector<Library> libraries = new Vector<Library>();

      LibraryManager libraryManager;
      libraryManager = new LibraryManager();
      libraryManager.buildAllUnbuilt();

      String prefLibs = Preferences.get("boards." + Preferences.get("board") + ".build.libraries");
      if (prefLibs != null) {
        String[] boardLibraries = prefLibs.trim().split("\\s+");
        for (String item : boardLibraries) {
          libraryManager.addLibrary(libraries, libraryManager.get(item));
        }
      }

      // 1. compile the target (core), outputting .o files to <buildPath> and
      // then collecting them into the core.a library file.
      includePaths.add(target.getPath());

      for (Library library : libraries) {
        includePaths.add(library.getFolder().getAbsolutePath());
      }

      List<File> targetObjectFiles =
          compileFiles(
              avrBasePath,
              buildPath,
              includePaths,
              findFilesInPath(target.getPath(), "c", true),
              findFilesInPath(target.getPath(), "cpp", true));

      // 2. compile the libraries, outputting .o files to: <buildPath>/<library>/

      for (File file : sketch.getImportedLibraries()) {
        String item = file.getName();
        libraryManager.addLibrary(libraries, libraryManager.get(item));
      }

      includePaths = new ArrayList<String>();
      includePaths.add(target.getPath());

      for (Library library : libraries) {
        String path = library.getFolder().getAbsolutePath();
        includePaths.add(library.getFolder().getAbsolutePath());
        for (File f : library.getObjectFiles()) {
          objectFiles.add(f);
        }
      }

      for (File f : targetObjectFiles) {
        objectFiles.add(f);
      }

      // 3. compile the sketch (already in the buildPath)

      objectFiles.addAll(
          compileFiles(
              avrBasePath,
              buildPath,
              includePaths,
              findFilesInPath(buildPath, "c", false),
              findFilesInPath(buildPath, "cpp", false)));

      // 4. link it all together into the .elf file

      List<String> baseCommandLinker =
          getCommandLinker(
              avrBasePath, objectFiles, buildPath + File.separator + primaryClassName + ".elf");

      baseCommandLinker.add("-L" + buildPath);
      baseCommandLinker.add("-lm");

      execAsynchronously(baseCommandLinker);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    List<String> baseCommandObjcopy = Arrays.asList(avrBasePath + "avr-objcopy", "-O", "-R");
    List<String> commandObjcopy;

    // 5. extract EEPROM data (from EEMEM directive) to .eep file.
    commandObjcopy = new ArrayList<String>(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.set(3, "-j");
    commandObjcopy.add(".eeprom");
    commandObjcopy.add("--set-section-flags=.eeprom=alloc,load");
    commandObjcopy.add("--no-change-warnings");
    commandObjcopy.add("--change-section-lma");
    commandObjcopy.add(".eeprom=0");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".eep");
    execAsynchronously(commandObjcopy);

    // 6. build the .hex file
    commandObjcopy = new ArrayList<String>(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.add(".eeprom"); // remove eeprom data
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".hex");
    execAsynchronously(commandObjcopy);

    return true;
  }
コード例 #29
0
  /**
   * Parse a chunk of code and extract the size() command and its contents. Also goes after
   * fullScreen(), smooth(), and noSmooth().
   *
   * @param code The code from the main tab in the sketch
   * @param fussy true if it should show an error message if bad size()
   * @return null if there was an error, otherwise an array (might contain some/all nulls)
   */
  public static SurfaceInfo parseSketchSize(String code, boolean fussy) throws SketchException {
    // This matches against any uses of the size() function, whether numbers
    // or variables or whatever. This way, no warning is shown if size() isn't
    // actually used in the applet, which is the case especially for anyone
    // who is cutting/pasting from the reference.

    //    String scrubbed = scrubComments(sketch.getCode(0).getProgram());
    //    String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
    //    String[] matches = PApplet.match(scrubComments(code), SIZE_REGEX);

    /*
    1. no size() or fullScreen() method at all
       will use the non-overridden settings() method in PApplet
    2. size() or fullScreen() found inside setup() (static mode sketch or otherwise)
       make sure that it uses numbers (or displayWidth/Height), copy into settings
    3. size() or fullScreen() already in settings()
       don't mess with the sketch, don't insert any defaults

    really only need to deal with situation #2.. nothing to be done for 1 and 3
    */
    // if static mode sketch, all we need is regex
    // easy proxy for static in this case is whether [^\s]void\s is present

    String searchArea = scrubComments(code);
    String[] setupMatch = PApplet.match(searchArea, VOID_SETUP_REGEX);
    if (setupMatch != null) {
      String found = setupMatch[0];
      int start = searchArea.indexOf(found) + found.length();
      int openBrace = searchArea.indexOf("{", start);
      char[] c = searchArea.toCharArray();
      int depth = 0;
      int closeBrace = -1;
      StringBuilder sb = new StringBuilder();
      for (int i = openBrace; i < c.length; i++) {
        if (c[i] == '{') {
          depth++;
        } else if (c[i] == '}') {
          depth--;
          if (depth == 0) {
            closeBrace = ++i;
            break;
          }
        } else {
          sb.append(c[i]);
        }
      }
      if (closeBrace == -1) {
        throw new SketchException("Found a { that's missing a matching }", false);
        //        return null;
      }
      searchArea = sb.toString();
    }

    StringList extraStatements = new StringList();

    // First look for noSmooth() or smooth(N) so we can hoist it into settings.
    String[] smoothContents = matchMethod("smooth", searchArea);
    if (smoothContents != null) {
      extraStatements.append(smoothContents[0]);
    }
    String[] noContents = matchMethod("noSmooth", searchArea);
    if (noContents != null) {
      if (extraStatements.size() != 0) {
        throw new SketchException("smooth() and noSmooth() cannot be used in the same sketch");
      } else {
        extraStatements.append(noContents[0]);
      }
    }
    String[] pixelDensityContents = matchMethod("pixelDensity", searchArea);
    if (pixelDensityContents != null) {
      extraStatements.append(pixelDensityContents[0]);
    }

    String[] sizeContents = matchMethod("size", searchArea);
    String[] fullContents = matchMethod("fullScreen", searchArea);
    // First check and make sure they aren't both being used, otherwise it'll
    // throw a confusing state exception error that one "can't be used here".
    if (sizeContents != null && fullContents != null) {
      throw new SketchException("size() and fullScreen() cannot be used in the same sketch", false);
    }

    // Get everything inside the parens for the size() method
    // String[] contents = PApplet.match(searchArea, SIZE_CONTENTS_REGEX);
    if (sizeContents != null) {
      StringList args = breakCommas(sizeContents[1]);
      SurfaceInfo info = new SurfaceInfo();
      info.statement = sizeContents[0];
      info.width = args.get(0).trim();
      info.height = args.get(1).trim();
      info.renderer = (args.size() >= 3) ? args.get(2).trim() : null;
      info.path = (args.size() >= 4) ? args.get(3).trim() : null;

      // Trying to remember why we wanted to allow people to use displayWidth
      // as the height or displayHeight as the width, but maybe it's for
      // making a square sketch window? Not going to

      if (info.hasOldSyntax()) {
        //        return null;
        throw new SketchException("Please update your code to continue.", false);
      }

      if (info.hasBadSize() && fussy) {
        // found a reference to size, but it didn't seem to contain numbers
        final String message =
            "The size of this sketch could not be determined from your code.\n"
                + "Use only numbers (not variables) for the size() command.\n"
                + "Read the size() reference for more details.";
        Base.showWarning("Could not find sketch size", message, null);
        //        new Exception().printStackTrace(System.out);
        //        return null;
        throw new SketchException("Please fix the size() line to continue.", false);
      }

      if (extraStatements.size() != 0) {
        info.statement += extraStatements.join(" ");
      }
      info.checkEmpty();
      return info;
      // return new String[] { contents[0], width, height, renderer, path };
    }
    // if no size() found, check for fullScreen()
    // contents = PApplet.match(searchArea, FULL_SCREEN_CONTENTS_REGEX);
    if (fullContents != null) {
      SurfaceInfo info = new SurfaceInfo();
      info.statement = fullContents[0];
      StringList args = breakCommas(fullContents[1]);
      if (args.size() > 0) { // might have no args
        String args0 = args.get(0).trim();
        if (args.size() == 1) {
          // could be either fullScreen(1) or fullScreen(P2D), figure out which
          if (args0.equals("SPAN") || PApplet.parseInt(args0, -1) != -1) {
            // it's the display parameter, not the renderer
            info.display = args0;
          } else {
            info.renderer = args0;
          }
        } else if (args.size() == 2) {
          info.renderer = args0;
          info.display = args.get(1).trim();
        } else {
          throw new SketchException("That's too many parameters for fullScreen()");
        }
      }
      info.width = "displayWidth";
      info.height = "displayHeight";
      if (extraStatements.size() != 0) {
        info.statement += extraStatements.join(" ");
      }
      info.checkEmpty();
      return info;
    }

    // Made it this far, but no size() or fullScreen(), and still
    // need to pull out the noSmooth() and smooth(N) methods.
    if (extraStatements.size() != 0) {
      SurfaceInfo info = new SurfaceInfo();
      info.statement = extraStatements.join(" ");
      return info;
    }

    // not an error, just no size() specified
    // return new String[] { null, null, null, null, null };
    return new SurfaceInfo();
  }
コード例 #30
0
ファイル: Runner.java プロジェクト: nconfrey/processing
  public boolean launchVirtualMachine(boolean presenting) {
    String[] vmParams = getMachineParams();
    String[] sketchParams = getSketchParams(presenting);
    //    PApplet.printArray(sketchParams);
    int port = 8000 + (int) (Math.random() * 1000);
    String portStr = String.valueOf(port);

    // Older (Java 1.5 and earlier) version, go figure
    //    String jdwpArg = "-Xrunjdwp:transport=dt_socket,address=" + portStr +
    // ",server=y,suspend=y";
    //    String debugArg = "-Xdebug";
    // Newer (Java 1.5+) version that uses JVMTI
    String jdwpArg =
        "-agentlib:jdwp=transport=dt_socket,address=" + portStr + ",server=y,suspend=y";

    // Everyone works the same under Java 7 (also on OS X)
    String[] commandArgs = new String[] {Base.getJavaPath(), jdwpArg};

    commandArgs = PApplet.concat(commandArgs, vmParams);
    commandArgs = PApplet.concat(commandArgs, sketchParams);
    //  PApplet.println(commandArgs);
    //  commandArg.setValue(commandArgs);
    launchJava(commandArgs);

    AttachingConnector connector = (AttachingConnector) findConnector("com.sun.jdi.SocketAttach");
    // PApplet.println(connector);  // gets the defaults

    Map<String, Argument> arguments = connector.defaultArguments();

    //  Connector.Argument addressArg =
    //    (Connector.Argument)arguments.get("address");
    //  addressArg.setValue(addr);
    Connector.Argument portArg = arguments.get("port");
    portArg.setValue(portStr);

    //    Connector.Argument timeoutArg =
    //      (Connector.Argument)arguments.get("timeout");
    //    timeoutArg.setValue("10000");

    // PApplet.println(connector);  // prints the current
    // com.sun.tools.jdi.AbstractLauncher al;
    // com.sun.tools.jdi.RawCommandLineLauncher rcll;

    // System.out.println(PApplet.javaVersion);
    // http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#sunlaunch

    try {
      //      boolean available = false;
      //      while (!available) {
      while (true) {
        try {
          vm = connector.attach(arguments);
          //          vm = connector.attach(arguments);
          if (vm != null) {
            //            generateTrace();
            //            available = true;
            return true;
          }
        } catch (IOException e) {
          //          System.out.println("waiting");
          //          e.printStackTrace();
          try {
            Thread.sleep(100);
          } catch (InterruptedException e1) {
            e1.printStackTrace(sketchErr);
          }
        }
      }
      //    } catch (IOException exc) {
      //      throw new Error("Unable to launch target VM: " + exc);
    } catch (IllegalConnectorArgumentsException exc) {
      throw new Error("Internal error: " + exc);
    }
  }