Exemple #1
0
 /**
  * Used to return all of the Preferences used across the application. Preferences can then be
  * edited locally within the calling class.
  *
  * @return A new instance of Preferences to be used locally
  */
 public static Preferences getOdinPrefs() {
   // Obtain a logger to write progress to
   Logger log = LoggerFactory.getLogger("odin.odin.object.OdinPreferences");
   log.log(Level.FINEST, "Examining preferences to see if it's null or not.", prefsOdin);
   if (prefsOdin == null) {
     log.finest(
         "Preferences object was null, creating a new one from the default file (odin.prefs.xml).");
     try {
       // Obtain the FileInputStream for the central Preferences file
       BufferedInputStream bisXMLPrefs = new BufferedInputStream(new FileInputStream(sPrefsPath));
       // Providing the file isn't null then import the preferences
       if (bisXMLPrefs != null) {
         prefsOdin.importPreferences(bisXMLPrefs);
       }
     } catch (Exception x) {
       // If any errors are thrown then record them in the logger
       log.throwing("OdinPreferences", "getOdinPrefs()", x);
     }
   }
   // Obtain the Preferences for this class, this allows for everything to be centralised within
   // the file
   prefsOdin = Preferences.userNodeForPackage(OdinPreferences.class);
   // Return the Preferences to the receiver.
   return prefsOdin;
 }
 public void testNode5() throws BackingStoreException {
   Preferences child = pref.node("a");
   child.put("key", "value");
   child.flush();
   assertNotNull(storage.toFolder());
   assertNull(storage.toPropertiesFile());
 }
  public void testPreferencesEvents() throws Exception {
    storage.toFolder(true);
    FileUtil.getConfigRoot().addRecursiveListener(new FileListener());
    pref.addNodeChangeListener(new NodeListener());

    String newPath = "a/b/c";
    String[] paths = newPath.split("/");
    FileObject fo = null;
    FileObject fo0 = null;
    for (int i = 0; i < paths.length; i++) {
      String path = paths[i];
      fo = FileUtil.createFolder((fo == null) ? FileUtil.getConfigRoot() : fo, path);
      if (i == 0) {
        fo0 = fo;
      }
      nodeAddedEvent.await();
      assertEquals("Missing node added event", 0, nodeAddedEvent.getCount());
      nodeAddedEvent = new CountDownLatch(1);

      Preferences pref2 = pref.node(fo.getPath());
      pref2.addNodeChangeListener(new NodeListener());
    }

    FileObject fo1 = FileUtil.createData(fo, "a.properties");
    nodeAddedEvent.await();
    assertEquals("Missing node added event", 0, nodeAddedEvent.getCount());

    nodeRemovedEvent = new CountDownLatch(paths.length + 1);
    fo0.delete();
    nodeRemovedEvent.await();
    assertEquals("Missing node removed event", 0, nodeRemovedEvent.getCount());
  }
  /**
   * Tries to load/restore the window state of the given window.
   *
   * @param aNamespace the namespace to use for the window state;
   * @param aProperties the properties to read from;
   * @param aWindow the window to load the state for.
   */
  public static void loadWindowState(final Preferences aProperties, final Window aWindow) {
    // Special case: for FileDialog/JFileChooser we also should restore the
    // properties...
    loadFileDialogState(aProperties, aWindow);

    try {
      final int xPos = aProperties.getInt("winXpos", -1);
      final int yPos = aProperties.getInt("winYpos", -1);
      if ((xPos >= 0) && (yPos >= 0)) {
        aWindow.setLocation(xPos, yPos);
      }
    } catch (NumberFormatException exception) {
      // Ignore...
    }

    if (isNonResizableWindow(aWindow)) {
      // In case the window cannot be resized, don't restore its width &
      // height...
      return;
    }

    try {
      final int width = aProperties.getInt("winWidth", -1);
      final int height = aProperties.getInt("winHeight", -1);
      if ((width >= 0) && (height >= 0)) {
        aWindow.setSize(width, height);
      }
    } catch (NumberFormatException exception) {
      // Ignore...
    }
  }
  public boolean avrdude(Collection params) throws RunnerException {
    List commandDownloader = new ArrayList();
    commandDownloader.add("avrdude");

    // Point avrdude at its config file since it's in a non-standard location.
    if (Base.isMacOS()) {
      commandDownloader.add("-C" + "hardware/tools/avr/etc/avrdude.conf");
    } else if (Base.isWindows()) {
      String userdir = System.getProperty("user.dir") + File.separator;
      commandDownloader.add("-C" + userdir + "hardware/tools/avr/etc/avrdude.conf");
    } else {
      // ???: is it better to have Linux users install avrdude themselves, in
      // a way that it can find its own configuration file?
      commandDownloader.add("-C" + "hardware/tools/avrdude.conf");
    }

    if (Preferences.getBoolean("upload.verbose")) {
      commandDownloader.add("-v");
      commandDownloader.add("-v");
      commandDownloader.add("-v");
      commandDownloader.add("-v");
    } else {
      commandDownloader.add("-q");
      commandDownloader.add("-q");
    }
    // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168",
    // then shove an "m" at the beginning.  won't work for attiny's, etc.
    commandDownloader.add(
        "-pm" + Preferences.get("boards." + Preferences.get("board") + ".build.mcu").substring(6));
    commandDownloader.addAll(params);

    return executeUploadCommand(commandDownloader);
  }
Exemple #6
0
 static synchronized void setprefb(String prefname, byte[] val) {
   try {
     if (prefs == null) prefs = Preferences.userNodeForPackage(Utils.class);
     prefs.putByteArray(prefname, val);
   } catch (SecurityException e) {
   }
 }
  /**
   * Tests reading a 3.0.2 install with a mix of classic and OSGi plug-ins.
   *
   * @throws Exception
   */
  public void testClassicPlugins() throws Exception {
    // extract the 3.0.2 skeleton
    IPath location = extractClassicPlugins();

    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(location.toOSString());
    definition.setTargetLocations(new ITargetLocation[] {container});
    Set urls = getAllBundleURLs(definition);
    assertTrue("Must be bundles", urls.size() > 0);

    Preferences store = PDECore.getDefault().getPluginPreferences();
    boolean restore = store.getBoolean(ICoreConstants.TARGET_PLATFORM_REALIZATION);
    try {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, false);
      // the old way
      URL[] pluginPaths = PluginPathFinder.getPluginPaths(location.toOSString());
      for (int i = 0; i < pluginPaths.length; i++) {
        URL url = pluginPaths[i];
        if (!urls.contains(url)) {
          System.err.println(url.toString());
        }
      }
      assertEquals("Wrong number of bundles", pluginPaths.length, urls.size());
    } finally {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, restore);
    }
  }
Exemple #8
0
 static synchronized byte[] getprefb(String prefname, byte[] def) {
   try {
     if (prefs == null) prefs = Preferences.userNodeForPackage(Utils.class);
     return (prefs.getByteArray(prefname, def));
   } catch (SecurityException e) {
     return (def);
   }
 }
Exemple #9
0
 static synchronized String getpref(String prefname, String def) {
   try {
     if (prefs == null) prefs = Preferences.userNodeForPackage(Utils.class);
     return (prefs.get(prefname, def));
   } catch (SecurityException e) {
     return (def);
   }
 }
 // XXX: add support for uploading sketches using a programmer
 public boolean uploadUsingPreferences(String buildPath, String className) throws RunnerException {
   String uploadUsing = Preferences.get("boards." + Preferences.get("board") + ".upload.using");
   if (uploadUsing == null) {
     // fall back on global preference
     uploadUsing = Preferences.get("upload.using");
   }
   if (uploadUsing.equals("bootloader")) {
     return uploadViaBootloader(buildPath, className);
   } else {
     Collection params = getProgrammerCommands(uploadUsing);
     params.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i");
     return avrdude(params);
   }
 }
  public void testRemoveParentNode() throws BackingStoreException {
    assertNull(storage.toFolder());
    assertNull(storage.toPropertiesFile());

    Preferences subnode = pref.node("subnode");
    assertNull(storage.toFolder());
    assertNull(storage.toPropertiesFile());
    subnode.put("key", "value");
    subnode.flush();
    assertNotNull(storage.toFolder());
    assertNull(storage.toPropertiesFile());
    subnode.removeNode();
    pref.flush();
    assertNull(storage.toPropertiesFile());
    assertNull(storage.toFolder());
    assertFalse(storage.existsNode());
  }
  public void testPreferencesEvents2() throws Exception {
    pref.addNodeChangeListener(new NodeListener());
    pref.addPreferenceChangeListener(new PrefListener());

    Preferences child = pref.node("a");
    nodeAddedEvent.await();
    assertEquals("Missing node added event", 0, nodeAddedEvent.getCount());
    pref.put("key", "value");
    prefChangedEvent.await();
    assertEquals("Missing preference change event", 0, prefChangedEvent.getCount());
    pref.remove("key");
    prefRemovedEvent.await();
    assertEquals("Missing preference removed event", 0, prefRemovedEvent.getCount());
    child.removeNode();
    nodeRemovedEvent.await();
    assertEquals("Missing node removed event", 0, nodeRemovedEvent.getCount());
  }
Exemple #13
0
  public void testPreferenceChange() {
    try {
      Preferences userRoot = Preferences.userRoot();
      Preferences node = userRoot.node("testAdd");

      node.addPreferenceChangeListener(
          new PreferenceChangeListener() {
            public void preferenceChange(PreferenceChangeEvent evt) {
              System.out.println(
                  " node "
                      + evt.getNode().name()
                      + " key = <"
                      + evt.getKey()
                      + "> val= <"
                      + evt.getNewValue()
                      + ">");
              if (evt.getKey().equals("love"))
                assert evt.getNewValue().equals("ok") : evt.getNewValue();
              else if (evt.getKey().equals("love2"))
                assert evt.getNewValue().equals("not ok") : evt.getNewValue();
            }
          });

      node.put("love", "ok");
      node.put("love2", "not ok");

    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
Exemple #14
0
  /**
   * Saves the window state to the given properties map.
   *
   * @param aNamespace the namespace to use for the window state;
   * @param aProperties the properties to fill;
   * @param aWindow the window to save the state for.
   */
  public static void saveWindowState(final Preferences aProperties, final Window aWindow) {
    // Special case: for FileDialog/JFileChooser we also store the properties...
    saveFileDialogState(aProperties, aWindow);

    final Point location = aWindow.getLocation();
    aProperties.put("winXpos", Integer.toString(location.x));
    aProperties.put("winYpos", Integer.toString(location.y));

    if (isNonResizableWindow(aWindow)) {
      // In case the window cannot be resized, don't restore its width &
      // height...
      return;
    }

    final Dimension dims = aWindow.getSize();
    aProperties.put("winWidth", Integer.toString(dims.width));
    aProperties.put("winHeight", Integer.toString(dims.height));
  }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   assertSame(new NbPreferencesFactory().userRoot(), Preferences.userRoot());
   pref = getPreferencesNode();
   assertNotNull(pref);
   storage = (PropertiesStorage) pref.fileStorage;
   assertNotNull(storage);
 }
Exemple #16
0
 /**
  * This class provides exactly the same functions are the getOdinPrefs method but doesn't record
  * anything in the Log
  *
  * <p>It should <b>only</b> be used by the LoggerFactory class to prevent a loop. All other
  * classes should use the getOdinPrefs method to utilise the logger.
  *
  * <p>It also retrieves much of the information from the Server's Root XML document and reads it
  * into the preferences for later reads.
  *
  * @return A new instance of Preferences to be used locally
  */
 public static Preferences getInitialPreferences() {
   /* As mentioned in the JavaDoc comments, this is the same code but omitting the use of the log. It doesn't harm if
    * a class other than LoggerFactory uses it, we just lose the logs if something goes wrong.
    */
   if (prefsOdin == null) {
     try {
       String prefsFilePath = getPrefsPath() + prefsFileName;
       File f = new File(prefsFilePath);
       if (f.exists()) {
         sPrefsPath = prefsFilePath;
         BufferedInputStream bisXMLPrefs =
             new BufferedInputStream(new FileInputStream(prefsFilePath));
         if (bisXMLPrefs != null) {
           prefsOdin.importPreferences(bisXMLPrefs);
         }
       } else {
         File fBackup = new File(prefsFileName);
         if (fBackup.exists()) {
           // Using the backup preferences in the application directory.
           sPrefsPath = prefsFileName;
         }
         BufferedInputStream bisXMLPrefs =
             new BufferedInputStream(new FileInputStream(prefsFileName));
         prefsOdin.importPreferences(bisXMLPrefs);
       }
     } catch (FileNotFoundException fnfX) {
       System.err.println("Couldn't retrieve either preferences.");
     } catch (Exception x) {
       // If any errors are thrown then put them in System.err rather than the Logger
       System.err.println(
           "An error was caught while trying to obtain preferences for the logger.");
       x.printStackTrace();
     }
   }
   prefsOdin = Preferences.userNodeForPackage(OdinPreferences.class);
   // Get hold of the JAXB data contained within the Server Root document to find out where we
   // should store everything.
   getRootDocument();
   prefsOdin.put("odin.jaxb.dir.Archive", rDocument.getLocations().getArchive());
   prefsOdin.put("odin.jaxb.dir.Convert", rDocument.getLocations().getConversion());
   prefsOdin.put("odin.jaxb.dir.Mime", rDocument.getLocations().getFormat());
   prefsOdin.put("odin.jaxb.dir.Log", rDocument.getLocations().getLogging());
   prefsOdin.put("odin.jaxb.dir.Prefs", rDocument.getLocations().getPreference());
   prefsOdin.put("odin.jaxb.dir.Hazard", rDocument.getLocations().getQuarantine());
   prefsOdin.put("odin.jaxb.dir.Store", rDocument.getLocations().getRepository());
   silentUpdate();
   return prefsOdin;
 }
Exemple #17
0
  /**
   * Checks whether the given window is either a FileDialog, or contains a JFileChooser component.
   * If so, its current directory is restored from the given properties.
   *
   * @param aNamespace the name space to use;
   * @param aProperties the properties to get the directory from;
   * @param aWindow the window to check for.
   */
  private static void saveFileDialogState(final Preferences aProperties, final Window aWindow) {
    final String propKey = "lastDirectory";

    if (aWindow instanceof FileDialog) {
      final String dir = ((FileDialog) aWindow).getDirectory();
      if (dir != null) {
        aProperties.put(propKey, dir);
      }
    } else if (aWindow instanceof JDialog) {
      final Container contentPane = ((JDialog) aWindow).getContentPane();
      final JFileChooser fileChooser =
          (JFileChooser) findComponent(contentPane, JFileChooser.class);
      if (fileChooser != null) {
        final File dir = fileChooser.getCurrentDirectory();
        if (dir != null) {
          aProperties.put(propKey, dir.getAbsolutePath());
        }
      }
    }
  }
Exemple #18
0
  /**
   * Checks whether the given window is either a FileDialog, or contains a JFileChooser component.
   * If so, its current directory is stored in the given properties.
   *
   * @param aNamespace the name space to use;
   * @param aProperties the properties to store the found directory in;
   * @param aWindow the window to check for.
   */
  private static void loadFileDialogState(final Preferences aProperties, final Window aWindow) {
    final String propKey = "lastDirectory";

    if (aWindow instanceof FileDialog) {
      final String dir = aProperties.get(propKey, null);
      if (dir != null) {
        ((FileDialog) aWindow).setDirectory(dir);
      }
    } else if (aWindow instanceof JDialog) {
      final Container contentPane = ((JDialog) aWindow).getContentPane();
      final JFileChooser fileChooser =
          (JFileChooser) findComponent(contentPane, JFileChooser.class);
      if (fileChooser != null) {
        final String dir = aProperties.get(propKey, null);
        if (dir != null) {
          fileChooser.setCurrentDirectory(new File(dir));
        }
      }
    }
  }
Exemple #19
0
 /** Used to update any changes within the preferences to the main XML file. */
 public static void updateOdinPrefs() {
   // Obtain a logger to write progress to
   Logger log = LoggerFactory.getLogger("odin.odin.object.OdinPreferences");
   try {
     log.finest("Exporting preferences to file: " + sPrefsPath);
     // Record all of the preferences in the odin.prefs.xml file
     prefsOdin.exportNode(new FileOutputStream(sPrefsPath));
   } catch (Exception x) {
     // If an error was encountered during the update then write the details to the log
     log.throwing("OdinPreferences", "updateOdinPrefs()", x);
   }
 }
Exemple #20
0
 /**
  * Used to update the preferences with possibly new values from the root document. This method is
  * only used within this class to prevent recursion from creating a <code>Logger</code> instance.
  *
  * @see java.util.logging.Logger
  */
 private static void silentUpdate() {
   try {
     // Record all of the preferences in the odin.prefs.xml file
     prefsOdin.exportNode(new FileOutputStream(sPrefsPath));
   } catch (Exception x) {
     // If an error was encountered during the update then write the details
     // to the System.err as there isn't a log to use.
     System.err.println(
         "Couldn't update the preferences with values from the server's root document.");
     x.printStackTrace();
   }
 }
Exemple #21
0
  public void testNodeChange() {
    System.out.println("***TestEvent");
    try {
      Preferences userRoot = Preferences.userRoot();

      userRoot.addNodeChangeListener(
          new NodeChangeListener() {
            public void childAdded(NodeChangeEvent evt) {
              System.out.println(
                  "childAdded = " + evt.getParent().name() + " " + evt.getChild().name());
            }

            public void childRemoved(NodeChangeEvent evt) {
              System.out.println(
                  "childRemoved = " + evt.getParent().name() + " " + evt.getChild().name());
            }
          });

      Preferences node = userRoot.node("testAdd");
      node.removeNode();

    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
  /**
   * Tests that a bundle directory container is equivalent to scanning locations when it uses a
   * variable to specify its location.
   *
   * @throws Exception
   */
  public void testVariableDirectoryBundleContainer() throws Exception {
    // the new way
    ITargetDefinition definition = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation("${eclipse_home}/plugins");
    definition.setTargetLocations(new ITargetLocation[] {container});
    Set urls = getAllBundleURLs(definition);

    Preferences store = PDECore.getDefault().getPluginPreferences();
    boolean restore = store.getBoolean(ICoreConstants.TARGET_PLATFORM_REALIZATION);
    try {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, false);
      // the old way
      URL[] pluginPaths = PluginPathFinder.getPluginPaths(TargetPlatform.getDefaultLocation());
      assertEquals("Should have same number of bundles", pluginPaths.length, urls.size());
      for (int i = 0; i < pluginPaths.length; i++) {
        URL url = pluginPaths[i];
        assertTrue("Missing plug-in " + url.toString(), urls.contains(url));
      }
    } finally {
      store.setValue(ICoreConstants.TARGET_PLATFORM_REALIZATION, restore);
    }
  }
 public static void main(String[] args) throws Exception {
   String osName = System.getProperty("os.name");
   if (osName.startsWith("Windows")) return;
   Preferences root = Preferences.userRoot();
   Preferences node1 = root.node("node1");
   Preferences node1A = node1.node("node1A");
   Preferences node1B = node1.node("node1B");
   node1B.put("mykey", "myvalue");
   node1.flush();
   String node1BDirName = System.getProperty("user.home") + "/.java/.userPrefs" + "/node1/node1B";
   File node1BDir = new File(node1BDirName);
   node1BDir.setReadOnly();
   try {
     node1.removeNode();
   } catch (BackingStoreException ex) {
     // expected exception
   } finally {
     Runtime.getRuntime().exec("chmod 755 " + node1BDirName).waitFor();
     try {
       node1.removeNode();
     } catch (Exception e) {
     }
   }
 }
  private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException {
    List commandDownloader = new ArrayList();
    String protocol = Preferences.get("boards." + Preferences.get("board") + ".upload.protocol");

    // avrdude wants "stk500v1" to distinguish it from stk500v2
    if (protocol.equals("stk500")) protocol = "stk500v1";
    commandDownloader.add("-c" + protocol);
    commandDownloader.add(
        "-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
    commandDownloader.add(
        "-b" + Preferences.getInteger("boards." + Preferences.get("board") + ".upload.speed"));
    commandDownloader.add("-D"); // don't erase
    commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i");

    if (Preferences.get("boards." + Preferences.get("board") + ".upload.disable_flushing") == null
        || Preferences.getBoolean("boards." + Preferences.get("board") + ".upload.disable_flushing")
            == false) {
      flushSerialBuffer();
    }

    return avrdude(commandDownloader);
  }
  private Collection getProgrammerCommands(String programmer) {
    List params = new ArrayList();
    params.add("-c" + Preferences.get("programmers." + programmer + ".protocol"));

    if ("usb".equals(Preferences.get("programmers." + programmer + ".communication"))) {
      params.add("-Pusb");
    } else if ("serial".equals(Preferences.get("programmers." + programmer + ".communication"))) {
      params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
      // XXX: add support for specifying the baud rate for serial programmers.
    }
    // XXX: add support for specifying the port address for parallel
    // programmers, although avrdude has a default that works in most cases.

    if (Preferences.get("programmers." + programmer + ".force") != null
        && Preferences.getBoolean("programmers." + programmer + ".force")) params.add("-F");

    if (Preferences.get("programmers." + programmer + ".delay") != null)
      params.add("-i" + Preferences.get("programmers." + programmer + ".delay"));

    return params;
  }
 public void testChildrenNames() throws Exception {
   Preferences subnode = pref.node("c1");
   subnode.put("k", "v");
   subnode.flush();
   subnode = pref.node("c2");
   subnode.put("k", "v");
   subnode.flush();
   subnode = pref.node("c3/c4");
   subnode.put("k", "v");
   subnode.flush();
   assertEquals(
       new TreeSet<String>(Arrays.asList("c1", "c2", "c3")),
       new TreeSet<String>(Arrays.asList(storage.childrenNames())));
   pref.node("c2").removeNode();
   assertEquals(
       new TreeSet<String>(Arrays.asList("c1", "c3")),
       new TreeSet<String>(Arrays.asList(storage.childrenNames())));
   pref.node("c3").removeNode();
   assertEquals(
       Collections.singleton("c1"), new TreeSet<String>(Arrays.asList(storage.childrenNames())));
   pref.node("c1").removeNode();
   assertEquals(
       Collections.emptySet(), new TreeSet<String>(Arrays.asList(storage.childrenNames())));
 }
Exemple #27
0
  public void run() {
    StringBuffer onechar;

    // Adding an additional newline as a hack around other errors
    String originalText = editor.getText() + "\n";
    strOut = new StringBuffer();
    indentValue = Preferences.getInteger("editor.tabs.size");
    indentChar = new String(" ");

    lineNumber = 0;
    c_level = if_lev = level = e_flg = paren = 0;
    a_flg = q_flg = j = tabs = 0;
    if_flg = peek = -1;
    peekc = '`';
    s_flg = 1;
    jdoc = 0;

    s_level  = new int[10];
    sp_flg   = new int[20][10];
    s_ind    = new int[20][10];
    s_if_lev = new int[10];
    s_if_flg = new int[10];
    ind      = new int[10];
    p_flg    = new int[10];
    s_tabs   = new int[20][10];

    w_else = new String ("else");
    w_if_ = new String ("if");
    w_for = new String ("for");
    w_ds  = new String ("default");
    w_case  = new String ("case");
    w_cpp_comment = new String ("//");
    w_jdoc = new String ("/**");
    line_feed = new String ("\n");

    // read as long as there is something to read
    EOF = 0;  // = 1 set in getchr when EOF

    chars = new char[BLOCK_MAXLEN];
    string = new char[BLOCK_MAXLEN];
    try {  // the whole process
      // open for input
      reader = new CharArrayReader(originalText.toCharArray());

      // add buffering to that InputStream
//      bin = new BufferedInputStream(in);

      for (int ib = 0; ib < BLOCK_MAXLEN; ib++) chars[ib] = '\0';

      lineLength = readCount = 0;
      // read up a block - remember how many bytes read
      readCount = reader.read(chars);
      strBlock = new String(chars);

      lineLength = readCount;
      lineNumber  = 1;
      indexBlock = -1;
      j = 0;
      while (EOF == 0)
      {
        c = getchr();
        switch(c)
        {
        default:
          string[j++] = c;
          if(c != ',')
          {
            l_char = c;
          }
          break;

        case ' ':
        case '\t':
          if(lookup(w_else) == 1)
          {
            gotelse();
            if(s_flg == 0 || j > 0)string[j++] = c;
            indent_puts();
            s_flg = 0;
            break;
          }
          if(s_flg == 0 || j > 0)string[j++] = c;
          break;

        case '\r':  // <CR> for MS Windows 95
        case '\n':
          lineNumber++;
          if (EOF==1)
          {
            break;
          }
          //String j_string = new String(string);

          e_flg = lookup(w_else);
          if(e_flg == 1) gotelse();
          if (lookup_com(w_cpp_comment) == 1)
          {
            if (string[j] == '\n')
            {
              string[j] = '\0';
              j--;
            }
          }

          indent_puts();
          //fprintf(outfil, line_feed);
          fprintf(line_feed);
          s_flg = 1;
          if(e_flg == 1)
          {
            p_flg[level]++;
            tabs++;
          }
          else
            if(p_char == l_char)
            {
              a_flg = 1;
            }
          break;

        case '{':
          if(lookup(w_else) == 1)gotelse();
          if (s_if_lev.length == c_level) {
            s_if_lev = PApplet.expand(s_if_lev);
            s_if_flg = PApplet.expand(s_if_flg);
          }
          s_if_lev[c_level] = if_lev;
          s_if_flg[c_level] = if_flg;
          if_lev = if_flg = 0;
          c_level++;
          if(s_flg == 1 && p_flg[level] != 0)
          {
            p_flg[level]--;
            tabs--;
          }
          string[j++] = c;
          indent_puts();
          getnl() ;
          indent_puts();
          //fprintf(outfil,"\n");
          fprintf("\n");
          tabs++;
          s_flg = 1;
          if(p_flg[level] > 0)
          {
            ind[level] = 1;
            level++;
            s_level[level] = c_level;
          }
          break;

        case '}':
          c_level--;
          if (c_level < 0)
          {
            EOF = 1;
            //System.out.println("eof b");
            string[j++] = c;
            indent_puts();
            break;
          }
          if ((if_lev = s_if_lev[c_level]-1) < 0)
            if_lev = 0;
          if_flg = s_if_flg[c_level];
          indent_puts();
          tabs--;
          p_tabs();
          peekc = getchr();
          if( peekc == ';')
          {
            onechar = new StringBuffer();
            onechar.append(c);   // the }
            onechar.append(';');
            //fprintf(outfil, onechar.toString());
            fprintf(onechar.toString());
            peek = -1;
            peekc = '`';
          }
          else
          {
            onechar = new StringBuffer();
            onechar.append(c);
            //fprintf(outfil, onechar.toString());
            fprintf(onechar.toString());
            peek = 1;
          }
          getnl();
          indent_puts();
          //fprintf(outfil,"\n");
          fprintf("\n");
          s_flg = 1;
          if(c_level < s_level[level])
            if(level > 0) level--;
          if(ind[level] != 0)
          {
            tabs -= p_flg[level];
            p_flg[level] = 0;
            ind[level] = 0;
          }
          break;

        case '"':
        case '\'':
          string[j++] = c;
          cc = getchr();
          while(cc != c)
          {
            // max. length of line should be 256
            string[j++] = cc;

            if(cc == '\\')
            {
              cc = string[j++] = getchr();
            }
            if(cc == '\n')
            {
              lineNumber++;
              indent_puts();
              s_flg = 1;
            }
            cc = getchr();

          }
          string[j++] = cc;
          if(getnl() == 1)
          {
            l_char = cc;
            peek = 1;
            peekc = '\n';
          }
          break;

        case ';':
          string[j++] = c;
          indent_puts();
          if(p_flg[level] > 0 && ind[level] == 0)
          {
            tabs -= p_flg[level];
            p_flg[level] = 0;
          }
          getnl();
          indent_puts();
          //fprintf(outfil,"\n");
          fprintf("\n");
          s_flg = 1;
          if(if_lev > 0)
            if(if_flg == 1)
            {
              if_lev--;
              if_flg = 0;
            }
            else if_lev = 0;
          break;

        case '\\':
          string[j++] = c;
          string[j++] = getchr();
          break;

        case '?':
          q_flg = 1;
          string[j++] = c;
          break;

        case ':':
          string[j++] = c;
          peekc = getchr();
          if(peekc == ':')
          {
            indent_puts();
            //fprintf (outfil,":");
            fprintf(":");
            peek = -1;
            peekc = '`';
            break;
          }
          else
          {
            //int double_colon = 0;
            peek = 1;
          }

          if(q_flg == 1)
          {
            q_flg = 0;
            break;
          }
          if(lookup(w_ds) == 0 && lookup(w_case) == 0)
          {
            s_flg = 0;
            indent_puts();
          }
          else
          {
            tabs--;
            indent_puts();
            tabs++;
          }
          peekc = getchr();
          if(peekc == ';')
          {
            fprintf(";");
            peek = -1;
            peekc = '`';
          }
          else
          {
            peek = 1;
          }
          getnl();
          indent_puts();
          fprintf("\n");
          s_flg = 1;
          break;

        case '/':
          string[j++] = c;
          peekc = getchr();

          if(peekc == '/')
          {
            string[j++] = peekc;
            peekc = '`';
            peek = -1;
            cpp_comment();
            //fprintf(outfil,"\n");
            fprintf("\n");
            break;
          }
          else
          {
            peek = 1;
          }

          if(peekc != '*') {
            break;
          }
          else
          {
            if (j > 0) string[j--] = '\0';
            if (j > 0) indent_puts();
            string[j++] = '/';
            string[j++] = '*';
            peek = -1;
            peekc = '`';
            comment();
            break;
          }

        case '#':
          string[j++] = c;
          cc = getchr();
          while(cc != '\n')
          {
            string[j++] = cc;
            cc = getchr();
          }
          string[j++] = cc;
          s_flg = 0;
          indent_puts();
          s_flg = 1;
          break;

        case ')':
          paren--;
          if (paren < 0)
          {
            EOF = 1;
            //System.out.println("eof c");
          }
          string[j++] = c;
          indent_puts();
          if(getnl() == 1)
          {
            peekc = '\n';
            peek = 1;
            if(paren != 0)
            {
              a_flg = 1;
            }
            else if(tabs > 0)
            {
              p_flg[level]++;
              tabs++;
              ind[level] = 0;
            }
          }
          break;

        case '(':
          string[j++] = c;
          paren++;
          if ((lookup(w_for) == 1))
          {
            c = get_string();
            while(c != ';') c = get_string();
            ct=0;
            int for_done = 0;
            while (for_done==0)
            {
              c = get_string();
              while(c != ')')
              {
                if(c == '(') ct++;
                c = get_string();
              }
              if(ct != 0)
              {
                ct--;
              }
              else for_done = 1;
            }                        // endwhile for_done
            paren--;
            if (paren < 0)
            {
              EOF = 1;
              //System.out.println("eof d");
            }
            indent_puts();
            if(getnl() == 1)
            {
              peekc = '\n';
              peek = 1;
              p_flg[level]++;
              tabs++;
              ind[level] = 0;
            }
            break;
          }

          if(lookup(w_if_) == 1)
          {
            indent_puts();
            s_tabs[c_level][if_lev] = tabs;
            sp_flg[c_level][if_lev] = p_flg[level];
            s_ind[c_level][if_lev] = ind[level];
            if_lev++;
            if_flg = 1;
          }
        } // end switch

        //System.out.println("string len is " + string.length);
        //if (EOF == 1) System.out.println(string);
        //String j_string = new String(string);

      } // end while not EOF

      /*
      int bad;
      while ((bad = bin.read()) != -1) {
        System.out.print((char) bad);
      }
      */
      /*
      char bad;
      //while ((bad = getchr()) != 0) {
      while (true) {
        getchr();
        if (peek != -1) {
          System.out.print(last_char);
        } else {
          break;
        }
      }
      */

      // save current (rough) selection point
      int selectionEnd = editor.getSelectionStop();

      // make sure the caret would be past the end of the text
      if (strOut.length() < selectionEnd - 1) {
        selectionEnd = strOut.length() - 1;
      }

      reader.close(); // close buff

      String formattedText = strOut.toString();
      if (formattedText.equals(originalText)) {
        editor.statusNotice(_("No changes necessary for Auto Format."));

      } else if (paren != 0) {
        // warn user if there are too many parens in either direction
	if (paren < 0) {
	  editor.statusError(
	    _("Auto Format Canceled: Too many right parentheses."));
	} else {
	  editor.statusError(
	    _("Auto Format Canceled: Too many left parentheses."));
	}

      } else if (c_level != 0) {  // check braces only if parens are ok
	if (c_level < 0) {
	  editor.statusError(
	    _("Auto Format Canceled: Too many right curly braces."));
	} else {
	  editor.statusError(
	    _("Auto Format Canceled: Too many left curly braces."));
	}

      } else {
        // replace with new bootiful text
        // selectionEnd hopefully at least in the neighborhood
        editor.setText(formattedText);
        editor.setSelection(selectionEnd, selectionEnd);
        editor.getSketch().setModified(true);
        // mark as finished
        editor.statusNotice(_("Auto Format finished."));
      }

    } catch (Exception e) {
      editor.statusError(e);
    }
  }
Exemple #28
0
  protected String[] getSketchParams(boolean presenting) {
    ArrayList<String> params = new ArrayList<String>();

    // It's dangerous to add your own main() to your code,
    // but if you've done it, we'll respect your right to hang yourself.
    // http://processing.org/bugs/bugzilla/1446.html
    if (build.getFoundMain()) {
      params.add(build.getSketchClassName());

    } else {
      params.add("processing.core.PApplet");

      // get the stored device index (starts at 0)
      int runDisplay = Preferences.getInteger("run.display");

      // If there was a saved location (this guy has been run more than once)
      // then the location will be set to the last position of the sketch window.
      // This will be passed to the PApplet runner using something like
      // --location=30,20
      // Otherwise, the editor location will be passed, and the applet will
      // figure out where to place itself based on the editor location.
      // --editor-location=150,20
      if (editor != null) { // if running processing-cmd, don't do placement
        GraphicsDevice editorDevice = editor.getGraphicsConfiguration().getDevice();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] devices = ge.getScreenDevices();

        // Make sure the display set in Preferences actually exists
        GraphicsDevice runDevice = editorDevice;
        if (runDisplay >= 0 && runDisplay < devices.length) {
          runDevice = devices[runDisplay];
        } else {
          runDevice = editorDevice;
          for (int i = 0; i < devices.length; i++) {
            if (devices[i] == runDevice) {
              runDisplay = i;
              break;
              // Don't set the pref, might be a temporary thing. Users can
              // open/close Preferences to reset the device themselves.
              //              Preferences.setInteger("run.display", runDisplay);
            }
          }
        }

        Point windowLocation = editor.getSketchLocation();
        //        if (windowLocation != null) {
        //          // could check to make sure the sketch location is on the device
        //          // that's specified in Preferences, but that's going to be annoying
        //          // if you move a sketch to another window, then it keeps jumping
        //          // back to the specified window.
        ////          Rectangle screenRect =
        ////            runDevice.getDefaultConfiguration().getBounds();
        //        }
        if (windowLocation == null) {
          if (editorDevice == runDevice) {
            // If sketches are to be shown on the same display as the editor,
            // provide the editor location so the sketch's main() can place it.
            Point editorLocation = editor.getLocation();
            params.add(
                PApplet.ARGS_EDITOR_LOCATION + "=" + editorLocation.x + "," + editorLocation.y);
          } else {
            // The sketch's main() will set a location centered on the new
            // display. It has to happen in main() because the width/height
            // of the sketch are not known here.
            //             Set a location centered on the other display
            //            Rectangle screenRect =
            //              runDevice.getDefaultConfiguration().getBounds();
            //            int runX =
            //            params.add(PApplet.ARGS_LOCATION + "=" + runX + "," + runY);
          }
        } else {
          params.add(PApplet.ARGS_LOCATION + "=" + windowLocation.x + "," + windowLocation.y);
        }
        params.add(PApplet.ARGS_EXTERNAL);
      }

      params.add(PApplet.ARGS_DISPLAY + "=" + runDisplay);

      if (presenting) {
        params.add(PApplet.ARGS_FULL_SCREEN);
        //        if (Preferences.getBoolean("run.present.exclusive")) {
        //          params.add(PApplet.ARGS_EXCLUSIVE);
        //        }
        params.add(PApplet.ARGS_STOP_COLOR + "=" + Preferences.get("run.present.stop.color"));
        params.add(PApplet.ARGS_BGCOLOR + "=" + Preferences.get("run.present.bgcolor"));
      }

      params.add(build.getSketchClassName());
      params.add(PApplet.ARGS_SKETCH_FOLDER + "=" + build.getSketchPath());
      // Adding sketch path in the end coz it's likely to
      // contain spaces and things go wrong on UNIX systems.
    }

    //    String outgoing[] = new String[params.size()];
    //    params.toArray(outgoing);
    //    return outgoing;
    return params.toArray(new String[0]);
  }
Exemple #29
0
  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();
  }
  protected boolean exportApplicationPrompt() throws IOException, SketchException {
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(Box.createVerticalStrut(6));

    // Box panel = Box.createVerticalBox();

    // Box labelBox = Box.createHorizontalBox();
    //    String msg = "<html>Click Export to Application to create a standalone, " +
    //      "double-clickable application for the selected plaforms.";

    //    String msg = "Export to Application creates a standalone, \n" +
    //      "double-clickable application for the selected plaforms.";
    String line1 = "Export to Application creates double-clickable,";
    String line2 = "standalone applications for the selected plaforms.";
    JLabel label1 = new JLabel(line1, SwingConstants.CENTER);
    JLabel label2 = new JLabel(line2, SwingConstants.CENTER);
    label1.setAlignmentX(Component.LEFT_ALIGNMENT);
    label2.setAlignmentX(Component.LEFT_ALIGNMENT);
    //    label1.setAlignmentX();
    //    label2.setAlignmentX(0);
    panel.add(label1);
    panel.add(label2);
    int wide = label2.getPreferredSize().width;
    panel.add(Box.createVerticalStrut(12));

    final JCheckBox windowsButton = new JCheckBox("Windows");
    // windowsButton.setMnemonic(KeyEvent.VK_W);
    windowsButton.setSelected(Preferences.getBoolean("export.application.platform.windows"));
    windowsButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean(
                "export.application.platform.windows", windowsButton.isSelected());
          }
        });

    final JCheckBox macosxButton = new JCheckBox("Mac OS X");
    // macosxButton.setMnemonic(KeyEvent.VK_M);
    macosxButton.setSelected(Preferences.getBoolean("export.application.platform.macosx"));
    macosxButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.platform.macosx", macosxButton.isSelected());
          }
        });

    final JCheckBox linuxButton = new JCheckBox("Linux");
    // linuxButton.setMnemonic(KeyEvent.VK_L);
    linuxButton.setSelected(Preferences.getBoolean("export.application.platform.linux"));
    linuxButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.platform.linux", linuxButton.isSelected());
          }
        });

    JPanel platformPanel = new JPanel();
    // platformPanel.setLayout(new BoxLayout(platformPanel, BoxLayout.X_AXIS));
    platformPanel.add(windowsButton);
    platformPanel.add(Box.createHorizontalStrut(6));
    platformPanel.add(macosxButton);
    platformPanel.add(Box.createHorizontalStrut(6));
    platformPanel.add(linuxButton);
    platformPanel.setBorder(new TitledBorder("Platforms"));
    // Dimension goodIdea = new Dimension(wide, platformPanel.getPreferredSize().height);
    // platformPanel.setMaximumSize(goodIdea);
    wide = Math.max(wide, platformPanel.getPreferredSize().width);
    platformPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    panel.add(platformPanel);

    //  Box indentPanel = Box.createHorizontalBox();
    //  indentPanel.add(Box.createHorizontalStrut(new JCheckBox().getPreferredSize().width));
    final JCheckBox showStopButton = new JCheckBox("Show a Stop button");
    // showStopButton.setMnemonic(KeyEvent.VK_S);
    showStopButton.setSelected(Preferences.getBoolean("export.application.stop"));
    showStopButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.stop", showStopButton.isSelected());
          }
        });
    showStopButton.setEnabled(Preferences.getBoolean("export.application.fullscreen"));
    showStopButton.setBorder(new EmptyBorder(3, 13, 6, 13));
    //  indentPanel.add(showStopButton);
    //  indentPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

    final JCheckBox fullScreenButton = new JCheckBox("Full Screen (Present mode)");
    // fullscreenButton.setMnemonic(KeyEvent.VK_F);
    fullScreenButton.setSelected(Preferences.getBoolean("export.application.fullscreen"));
    fullScreenButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            boolean sal = fullScreenButton.isSelected();
            Preferences.setBoolean("export.application.fullscreen", sal);
            showStopButton.setEnabled(sal);
          }
        });
    fullScreenButton.setBorder(new EmptyBorder(3, 13, 3, 13));

    JPanel optionPanel = new JPanel();
    optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.Y_AXIS));
    optionPanel.add(fullScreenButton);
    optionPanel.add(showStopButton);
    //    optionPanel.add(indentPanel);
    optionPanel.setBorder(new TitledBorder("Options"));
    wide = Math.max(wide, platformPanel.getPreferredSize().width);
    // goodIdea = new Dimension(wide, optionPanel.getPreferredSize().height);
    optionPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    // optionPanel.setMaximumSize(goodIdea);
    panel.add(optionPanel);

    Dimension good;
    // label1, label2, platformPanel, optionPanel
    good = new Dimension(wide, label1.getPreferredSize().height);
    label1.setMaximumSize(good);
    good = new Dimension(wide, label2.getPreferredSize().height);
    label2.setMaximumSize(good);
    good = new Dimension(wide, platformPanel.getPreferredSize().height);
    platformPanel.setMaximumSize(good);
    good = new Dimension(wide, optionPanel.getPreferredSize().height);
    optionPanel.setMaximumSize(good);

    //    JPanel actionPanel = new JPanel();
    //    optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.X_AXIS));
    //    optionPanel.add(Box.createHorizontalGlue());

    //    final JDialog frame = new JDialog(editor, "Export to Application");

    //    JButton cancelButton = new JButton("Cancel");
    //    cancelButton.addActionListener(new ActionListener() {
    //      public void actionPerformed(ActionEvent e) {
    //        frame.dispose();
    //        return false;
    //      }
    //    });

    // Add the buttons in platform-specific order
    //    if (PApplet.platform == PConstants.MACOSX) {
    //      optionPanel.add(cancelButton);
    //      optionPanel.add(exportButton);
    //    } else {
    //      optionPanel.add(exportButton);
    //      optionPanel.add(cancelButton);
    //    }
    String[] options = {"Export", "Cancel"};
    final JOptionPane optionPane =
        new JOptionPane(
            panel,
            JOptionPane.PLAIN_MESSAGE,
            // JOptionPane.QUESTION_MESSAGE,
            JOptionPane.YES_NO_OPTION,
            null,
            options,
            options[0]);

    final JDialog dialog = new JDialog(this, "Export Options", true);
    dialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible()
                && (e.getSource() == optionPane)
                && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
              // If you were going to check something
              // before closing the window, you'd do
              // it here.
              dialog.setVisible(false);
            }
          }
        });
    dialog.pack();
    dialog.setResizable(false);

    Rectangle bounds = getBounds();
    dialog.setLocation(
        bounds.x + (bounds.width - dialog.getSize().width) / 2,
        bounds.y + (bounds.height - dialog.getSize().height) / 2);
    dialog.setVisible(true);

    Object value = optionPane.getValue();
    if (value.equals(options[0])) {
      return jmode.handleExportApplication(sketch);
    } else if (value.equals(options[1]) || value.equals(new Integer(-1))) {
      // closed window by hitting Cancel or ESC
      statusNotice("Export to Application canceled.");
    }
    return false;
  }