Esempio n. 1
0
  public void writeImageToStream(OutputStream os, String fileName, BufferedImage img) {
    // if we get here we need to save the image from the memory
    try {
      // try to write image using the format of the filename extension
      int pos = fileName.lastIndexOf('.');
      String ext = fileName.substring(pos + 1).toLowerCase(Locale.US);
      if (ext.equals("jpg") || ext.equals("jpeg")) ext = "JPG";
      else ext = "PNG";

      // circumvent security issues by disabling disk-based caching
      if (app.isApplet()) {
        javax.imageio.ImageIO.setUseCache(false);
      }

      ImageIO.write(img, ext, os);

      // restore caching to prevent side-effects
      if (app.isApplet()) {
        javax.imageio.ImageIO.setUseCache(true);
      }
    } catch (Exception e) {
      Application.debug(e.getMessage());
      try {
        // if this did not work save image as png
        ImageIO.write(img, "png", os);
      } catch (Exception ex) {
        Application.debug(ex.getMessage());
        return;
      }
    }
  }
Esempio n. 2
0
  // G.Sturr 2010-7-5
  // added 'allowErrorDialog' flag to handle the case of unquoted text
  // entries in the spreadsheet
  public GeoElement[] processAlgebraCommandNoExceptionHandling(
      String cmd, boolean storeUndo, boolean allowErrorDialog, boolean throwMyError)
      throws Exception {
    ValidExpression ve;
    try {
      ve = parser.parseGeoGebraExpression(cmd);
    } catch (ParseException e) {
      // e.printStackTrace();
      if (allowErrorDialog) {
        app.showError(app.getError("InvalidInput") + ":\n" + cmd);
        return null;
      }
      throw new MyException(app.getError("InvalidInput") + ":\n" + cmd, MyException.INVALID_INPUT);
    } catch (MyError e) {
      // e.printStackTrace();
      if (allowErrorDialog) {
        app.showError(e.getLocalizedMessage());
        return null;
      }
      throw new Exception(e.getLocalizedMessage());
    } catch (Error e) {
      // e.printStackTrace();
      if (allowErrorDialog) {
        app.showError(app.getError("InvalidInput") + ":\n" + cmd);
        return null;
      }
      throw new Exception(app.getError("InvalidInput") + ":\n" + cmd);
    }

    // process ValidExpression (built by parser)
    GeoElement[] geoElements = null;
    try {
      geoElements = processValidExpression(ve);
      if (storeUndo && geoElements != null) app.storeUndoInfo();
    } catch (MyError e) {
      e.printStackTrace();
      // throw new Exception(e.getLocalizedMessage());

      // show error with nice "Show Online Help" box
      if (allowErrorDialog) { // G.Sturr 2010-7-5
        app.showError(e);
        e.printStackTrace();
      } else if (throwMyError) throw new MyError(app, e.getLocalizedMessage(), e.getcommandName());

      return null;
    } catch (CircularDefinitionException e) {
      Application.debug("CircularDefinition");
      throw e;
    } catch (Exception ex) {
      Application.debug("Exception");
      ex.printStackTrace();
      throw new Exception(app.getError("Error") + ":\n" + ex.getLocalizedMessage());
    }
    return geoElements;
  }
  /*
   * Take a list of commands and return all possible syntaxes
   * for these commands
   */
  private List<String> getSyntaxes(List<String> commands) {
    if (commands == null) {
      return null;
    }
    ArrayList<String> syntaxes = new ArrayList<String>();
    for (String cmd : commands) {

      String cmdInt = app.getInternalCommand(cmd);

      String syntaxString;
      if (isCASInput) {
        syntaxString = app.getCommandSyntaxCAS(cmdInt);
      } else {
        syntaxString = app.getCommandSyntax(cmdInt);
      }
      if (syntaxString.endsWith(isCASInput ? app.syntaxCAS : app.syntaxStr)) {

        // command not found, check for macros
        Macro macro = isCASInput ? null : app.getKernel().getMacro(cmd);
        if (macro != null) {
          syntaxes.add(macro.toString());
        } else {
          // syntaxes.add(cmdInt + "[]");
          Application.debug("Can't find syntax for: " + cmd);
        }

        continue;
      }
      for (String syntax : syntaxString.split("\\n")) {
        syntaxes.add(syntax);
      }
    }
    return syntaxes;
  }
  private void updateListItems(double from, double to, double step) {
    if (isEmpty) return;

    double currentVal = from;
    int i = 0;

    while ((step > 0 && currentVal <= to + Kernel.MIN_PRECISION)
        || (step < 0 && currentVal >= to - Kernel.MIN_PRECISION)) {
      GeoElement listElement = list.get(i);

      // check we haven't run out of memory
      if (app.freeMemoryIsCritical()) {
        long mem = app.freeMemory();
        list.clearCache();
        kernel.initUndoInfo(); // clear all undo info
        Application.debug("AlgoSequence aborted: free memory reached " + mem);
        return;
      }

      // set local var value
      updateLocalVar(currentVal);

      // copy expression value to listElement
      // if it's undefined, just copy the undefined property
      if (expression.isDefined()) listElement.set(expression);
      else listElement.setUndefined();
      listElement.update();

      currentVal += step;
      if (kernel.isInteger(currentVal)) {
        currentVal = Math.round(currentVal);
      }
      i++;
    }
  }
Esempio n. 5
0
  public boolean initialize() {

    boolean success = true;

    try {
      sequencer = MidiSystem.getSequencer();
      sequencer.addMetaEventListener(this);

      if (synthesizer == null) {
        if ((synthesizer = MidiSystem.getSynthesizer()) == null) {
          Application.debug("getSynthesizer() failed!");
          return false;
        }

        Soundbank sb = synthesizer.getDefaultSoundbank();
        if (sb != null) {
          instruments = synthesizer.getDefaultSoundbank().getInstruments();
          synthesizer.loadInstrument(instruments[0]);
        }

        channels = synthesizer.getChannels();
      }
    } catch (MidiUnavailableException e) {
      e.printStackTrace();
      return false;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return success;
  }
Esempio n. 6
0
  /**
   * Calls Pcopy.updateCascade() to compute Qcopy. For non-continous constructions caching of
   * previous paramater positions is used.
   */
  private void pcopyUpdateCascade() {
    countUpdates++;

    if (continuous) {
      // CONTINOUS construction
      // don't use caching for continuous constructions:
      // the same position of Pcopy can have different results for Qcopy
      Pcopy.updateCascade();
    } else {
      // NON-CONTINOUS construction
      // check if the path parameter's resulting Qcopy is already in cache
      double param = Pcopy.getPathParameter().t;
      Point2D.Double cachedPoint = getCachedPoint(param);

      if (cachedPoint == null) {
        // measure time needed for update of construction
        long startTime = System.currentTimeMillis();

        // result not in cache: update Pcopy to compute Qcopy
        Pcopy.updateCascade();

        long updateTime = System.currentTimeMillis() - startTime;

        // if it takes too much time to calculate a single step, we stop
        if (updateTime > MAX_TIME_FOR_ONE_STEP) {
          Application.debug("AlgoLocus: max time exceeded " + updateTime);
          maxTimeExceeded = true;
        }

        // cache value of Qcopy
        putCachedPoint(param, Qcopy);
      } else {
        // use cached result to set Qcopy
        Qcopy.setCoords(cachedPoint.x, cachedPoint.y, 1.0);
        useCache++;
      }
    }

    //    	if (Qcopy.isDefined() && !Qcopy.isInfinite()) {
    //    		if (!foundDefined)
    //    			System.out.print(locus.label + " FIRST DEFINED param: " + Pcopy.getPathParameter().t);
    //    		else
    //    			System.out.print(locus.label + " param: " + Pcopy.getPathParameter().t);
    //        	System.out.println(", Qcopy: " + Qcopy);
    //    	} else {
    //    		System.out.print(locus.label + " param: " + Pcopy.getPathParameter().t);
    //        	System.out.println(", Qcopy: NOT DEFINED");
    //    	}

    // check found defined
    if (!foundDefined && Qcopy.isDefined() && !Qcopy.isInfinite()) {
      pathMover.init(Pcopy);
      PstartPos.set((GeoElement) Pcopy);
      QstartPos.set((GeoElement) Qcopy);
      foundDefined = true;

      // insert first point
      insertPoint(Qcopy.inhomX, Qcopy.inhomY, false);
    }
  }
Esempio n. 7
0
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    Application.debug(tfScript.getText());
    if (source == btApply) {
      Construction cons = app.getKernel().getConstruction();
      button = textField ? app.getKernel().textfield(null, linkedGeo) : new GeoButton(cons);
      button.setEuclidianVisible(true);
      button.setAbsoluteScreenLoc(x, y);

      button.setLabel(null);
      button.setClickScript(tfScript.getText(), true);

      // set caption text
      String strCaption = tfCaption.getText().trim();
      if (strCaption.length() > 0) {
        button.setCaption(strCaption);
      }

      button.setEuclidianVisible(true);
      button.setLabelVisible(true);
      button.updateRepaint();

      geoResult = button;
      setVisible(false);

      app.getKernel().storeUndoInfo();
    } else if (source == btCancel) {
      geoResult = null;
      setVisible(false);
    }
  }
Esempio n. 8
0
  /**
   * Parses given String str and tries to evaluate it to a GeoImplicitPoly object. Returns null if
   * something went wrong.
   *
   * @param str
   * @boolean showErrors if false, only stacktraces are printed
   * @return implicit polygon or null
   */
  public GeoElement evaluateToGeoElement(String str, boolean showErrors) {
    boolean oldMacroMode = cons.isSuppressLabelsActive();
    cons.setSuppressLabelCreation(true);

    GeoElement geo = null;
    try {
      ValidExpression ve = parser.parseGeoGebraExpression(str);
      GeoElement[] temp = processValidExpression(ve);
      geo = temp[0];
    } catch (CircularDefinitionException e) {
      Application.debug("CircularDefinition");
      app.showError("CircularDefinition");
    } catch (Exception e) {
      e.printStackTrace();
      if (showErrors) app.showError("InvalidInput", str);
    } catch (MyError e) {
      e.printStackTrace();
      if (showErrors) app.showError(e);
    } catch (Error e) {
      e.printStackTrace();
      if (showErrors) app.showError("InvalidInput", str);
    }

    cons.setSuppressLabelCreation(oldMacroMode);
    return geo;
  }
Esempio n. 9
0
  /**
   * Parses given String str and tries to evaluate it to a GeoFunction Returns null if something
   * went wrong. Michael Borcherds 2008-04-04
   */
  public GeoFunction evaluateToFunction(String str, boolean suppressErrors) {
    boolean oldMacroMode = cons.isSuppressLabelsActive();
    cons.setSuppressLabelCreation(true);

    GeoFunction func = null;
    try {
      ValidExpression ve = parser.parseGeoGebraExpression(str);
      GeoElement[] temp = processValidExpression(ve);

      if (temp[0].isGeoFunctionable()) {
        GeoFunctionable f = (GeoFunctionable) temp[0];
        func = f.getGeoFunction();
      } else if (!suppressErrors) app.showError("InvalidInput", str);

    } catch (CircularDefinitionException e) {
      Application.debug("CircularDefinition");
      if (!suppressErrors) app.showError("CircularDefinition");
    } catch (Exception e) {
      e.printStackTrace();
      if (!suppressErrors) app.showError("InvalidInput", str);
    } catch (MyError e) {
      e.printStackTrace();
      if (!suppressErrors) app.showError(e);
    } catch (Error e) {
      e.printStackTrace();
      if (!suppressErrors) app.showError("InvalidInput", str);
    }

    cons.setSuppressLabelCreation(oldMacroMode);
    return func;
  }
Esempio n. 10
0
  /**
   * for AlgebraView changes in the tree selection and redefine dialog
   *
   * @return changed geo
   */
  public GeoElement changeGeoElementNoExceptionHandling(
      GeoElement geo, ValidExpression newValue, boolean redefineIndependent, boolean storeUndoInfo)
      throws Exception {
    String oldLabel, newLabel;
    GeoElement[] result;

    try {
      oldLabel = geo.getLabel();
      newLabel = newValue.getLabel();

      if (newLabel == null) {
        newLabel = oldLabel;
        newValue.setLabel(newLabel);
      }

      // make sure that points stay points and vectors stay vectors
      if (newValue instanceof ExpressionNode) {
        ExpressionNode n = (ExpressionNode) newValue;
        if (geo.isGeoPoint()) n.setForcePoint();
        else if (geo.isGeoVector()) n.setForceVector();
        else if (geo.isGeoFunction()) n.setForceFunction();
      }

      if (newLabel.equals(oldLabel)) {
        // try to overwrite
        result = processValidExpression(newValue, redefineIndependent);
        if (result != null && storeUndoInfo) app.storeUndoInfo();
        return result[0];
      } else if (cons.isFreeLabel(newLabel)) {
        newValue.setLabel(oldLabel);
        // rename to oldLabel to enable overwriting
        result = processValidExpression(newValue, redefineIndependent);
        result[0].setLabel(newLabel); // now we rename
        if (storeUndoInfo) app.storeUndoInfo();
        return result[0];
      } else {
        String str[] = {"NameUsed", newLabel};
        throw new MyError(app, str);
      }
    } catch (CircularDefinitionException e) {
      Application.debug("CircularDefinition");
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception(app.getError("InvalidInput") + ":\n" + newValue);
    } catch (MyError e) {
      e.printStackTrace();
      throw new Exception(e.getLocalizedMessage());
    } catch (Error e) {
      e.printStackTrace();
      throw new Exception(app.getError("InvalidInput") + ":\n" + newValue);
    }
  }
  public synchronized void handleOpenApplication(com.apple.eawt.ApplicationEvent ev) {
    Application.debug("handleOpenApplication event, filename: " + ev.getFilename());

    // open file
    String fileName = ev.getFilename();
    if (fileName != null) {
      handleOpenFile(ev);
    } else {
      GeoGebraFrame wnd = getGGBInstance();
      if (!wnd.isShowing()) wnd.setVisible(true);
    }
  }
  private void createNewList(double from, double to, double step) {
    // clear list if defined
    int i = 0;
    int oldListSize = list.size();
    list.clear();

    if (!isEmpty) {
      //  needed capacity
      int n = (int) Math.ceil((to - from) / step) + 1;
      list.ensureCapacity(n);

      // create the sequence
      double currentVal = from;

      while ((step > 0 && currentVal <= to + Kernel.MIN_PRECISION)
          || (step < 0 && currentVal >= to - Kernel.MIN_PRECISION)) {

        // check we haven't run out of memory
        if (app.freeMemoryIsCritical()) {
          long mem = app.freeMemory();
          list.clearCache();
          kernel.initUndoInfo(); // clear all undo info
          Application.debug("AlgoSequence aborted: free memory reached " + mem);
          return;
        }

        // set local var value
        updateLocalVar(currentVal);

        addElement(i);

        currentVal += step;
        if (kernel.isInteger(currentVal)) {
          currentVal = Math.round(currentVal);
        }
        i++;
      }
    }

    // if the old list was longer than the new one
    // we need to set some cached elements to undefined
    for (int k = oldListSize - 1; k >= i; k--) {
      GeoElement oldElement = list.getCached(k);
      oldElement.setUndefined();
      oldElement.update();
    }

    // remember current values
    last_from = from;
    last_to = to;
    last_step = step;
  }
Esempio n. 13
0
 public void debug(GeoElement geo) {
   System.out.println("=====================================");
   System.out.println(geo.toString());
   Field[] fields = TraceSettings.class.getDeclaredFields();
   for (Field field : fields) {
     try {
       System.out.println(field.getName() + ": " + field.get(this).toString());
     } catch (Exception e) {
       Application.debug(e.getMessage());
     }
   }
   System.out.println("=====================================");
 }
 /**
  * Gets active instance of GeoGebra window. This method waits until an active instance was created
  * by GeoGebra.main()
  *
  * @return
  */
 private synchronized GeoGebraFrame getGGBInstance() {
   GeoGebraFrame wnd = null;
   while (wnd == null) {
     try {
       Thread.sleep(100);
       wnd = GeoGebraFrame.getActiveInstance();
     } catch (Exception e) {
       Application.debug("MacApplicationListener.getGGBInstance(): " + e.getMessage());
       wnd = null;
     }
   }
   return wnd;
 }
Esempio n. 15
0
  @SuppressWarnings("deprecation")
  protected final void compute() {

    if (input[0].isDefined() && input[1].isDefined() && input[2].isDefined()) {
      int param = (int) Math.round(a.getDouble());
      double val = b.getDouble();
      try {
        PoissonDistribution dist = getPoissonDistribution(param);
        if (isCumulative.getBoolean()) num.setValue(dist.cumulativeProbability(val)); // P(X <= val)
        else num.setValue(dist.probability(val)); // P(X = val)
      } catch (Exception e) {
        Application.debug(e.getMessage());
        num.setUndefined();
      }
    } else num.setUndefined();
  }
Esempio n. 16
0
 private void initType(ExpressionValue ev) {
   if (ev.isBooleanValue()) {
     isBooleanFunction = true;
   } else if (ev.isNumberValue()) {
     isBooleanFunction = false;
   } else if (ev instanceof FunctionNVar) {
     expression = ((FunctionNVar) ev).getExpression();
     fVars = ((FunctionNVar) ev).getFunctionVariables();
   } else {
     Application.debug(
         "InvalidFunction:"
             + expression.toString()
             + " "
             + ev.toString()
             + ev.getClass().getName());
     throw new MyError(kernel.getApplication(), "InvalidFunction");
   }
 }
Esempio n. 17
0
  /**
   * Parses given String str and tries to evaluate it to a GeoPoint. Returns null if something went
   * wrong.
   */
  public GeoPointND evaluateToPoint(String str, boolean showErrors) {
    boolean oldMacroMode = cons.isSuppressLabelsActive();
    cons.setSuppressLabelCreation(true);

    GeoPointND p = null;
    GeoElement[] temp = null;
    ;
    try {
      ValidExpression ve = parser.parseGeoGebraExpression(str);
      if (ve instanceof ExpressionNode) {
        ExpressionNode en = (ExpressionNode) ve;
        en.setForcePoint();
      }

      temp = processValidExpression(ve);
      p = (GeoPointND) temp[0];
    } catch (CircularDefinitionException e) {
      if (showErrors) {
        Application.debug("CircularDefinition");
        app.showError("CircularDefinition");
      }
    } catch (Exception e) {
      if (showErrors) {
        e.printStackTrace();
        app.showError("InvalidInput", str);
      }
    } catch (MyError e) {
      if (showErrors) {
        e.printStackTrace();
        app.showError(e);
      }
    } catch (Error e) {
      if (showErrors) {
        e.printStackTrace();
        app.showError("InvalidInput", str);
      }
    }

    cons.setSuppressLabelCreation(oldMacroMode);
    return p;
  }
Esempio n. 18
0
 /** Set all elements in locusConsElements to the current values of the main construction */
 private void resetMacroConstruction() {
   Iterator<ConstructionElement> it = locusConsOrigElements.iterator();
   while (it.hasNext()) {
     ConstructionElement ce = it.next();
     if (ce.isGeoElement()) {
       GeoElement geoOrig = (GeoElement) ce;
       // do not copy functions, their expressions already
       // include references to the correct other geos
       if (!geoOrig.isGeoFunction()) {
         GeoElement geoCopy = macroCons.lookupLabel(geoOrig.label);
         if (geoCopy != null) {
           try {
             geoCopy.set(geoOrig);
             geoCopy.update();
           } catch (Exception e) {
             Application.debug("AlgoLocus: error in resetMacroConstruction(): " + e.getMessage());
           }
         }
       }
     }
   }
 }
  public synchronized void handleOpenFile(com.apple.eawt.ApplicationEvent ev) {
    Application.debug("handleOpenFile event, filename: " + ev.getFilename());

    // open file
    String fileName = ev.getFilename();

    if (fileName != null) {
      File openFile = new File(fileName);
      if (openFile.exists()) {
        // get application instance
        GeoGebraFrame ggb = getGGBInstance();
        Application app = ggb.getApplication();

        // open file
        File[] files = {openFile};
        boolean openInThisWindow = app.getCurrentFile() == null;
        app.getGuiManager().doOpenFiles(files, openInThisWindow);

        // make sure window is visible
        if (openInThisWindow) ggb.setVisible(true);
      }
    }
  }
  private void addElement(int i) {
    // only add new objects
    GeoElement listElement = null;
    int cacheListSize = list.getCacheSize();
    if (i < cacheListSize) {
      // we reuse existing list element from cache
      listElement = list.getCached(i);

      if (expIsFunctionOrCurve) {
        // for functions we always need a new element
        listElement.setParentAlgorithm(null);
        listElement.doRemove();

        // replace old list element by a new one
        listElement = createNewListElement();
      }
    } else {
      // create new list element
      listElement = createNewListElement();
    }

    // copy current expression value to listElement
    if (!expIsFunctionOrCurve) {
      listElement.set(expression);
      AlgoElement drawAlgo = expression.getDrawAlgorithm();
      if (listElement instanceof GeoNumeric && drawAlgo instanceof AlgoDrawInformation) {
        Application.debug(expression.getDrawAlgorithm().getClass().getName());
        listElement.setDrawAlgorithm(((AlgoDrawInformation) drawAlgo).copy());
        listElement.setEuclidianVisible(true);
      }
    }

    // set the value of our element
    listElement.update();
    list.add(listElement);
  }
Esempio n. 21
0
  /**
   * Reads zipped file from zip input stream that includes the construction saved in xml format and
   * maybe image files.
   */
  private final void readZip(ZipInputStream zip, boolean isGGTfile) throws Exception {

    // we have to read everything (i.e. all images)
    // before we process the XML file, that's why we
    // read the XML file into a buffer first
    byte[] xmlFileBuffer = null;
    byte[] macroXmlFileBuffer = null;
    boolean xmlFound = false;
    boolean macroXMLfound = false;

    boolean ggbHandler = false;

    // get all entries from the zip archive
    while (true) {
      ZipEntry entry = zip.getNextEntry();
      if (entry == null) break;

      String name = entry.getName();
      if (name.equals(XML_FILE) || name.equals(I2G_PRIVATE + XML_FILE)) {
        // load xml file into memory first
        xmlFileBuffer = Util.loadIntoMemory(zip);
        xmlFound = true;
        ggbHandler = true;
        // Added for Intergeo File Format (Yves Kreis) -->
        handler = getGGBHandler();
      } else if (!ggbHandler && name.equals(I2G_FILE)) {
        // load i2g file into memory first
        xmlFileBuffer = Util.loadIntoMemory(zip);
        xmlFound = true;
        handler = getI2GHandler();
        // <-- Added for Intergeo File Format (Yves Kreis)
      } else if (name.equals(XML_FILE_MACRO) || name.equals(I2G_PRIVATE + XML_FILE_MACRO)) {
        // load macro xml file into memory first
        macroXmlFileBuffer = Util.loadIntoMemory(zip);
        macroXMLfound = true;
        ggbHandler = true;
        handler = getGGBHandler();
      } else if (name.equals(JAVASCRIPT_FILE)) {
        // load JavaScript
        kernel.setLibraryJavaScript(Util.loadIntoString(zip));
      } else {
        // try to load image
        try {
          BufferedImage img = ImageIO.read(zip);
          app.addExternalImage(name, img);
        } catch (IOException e) {
          Application.debug("readZipFromURL: image could not be loaded: " + name);
          e.printStackTrace();
        }
      }

      // get next entry
      zip.closeEntry();
    }
    zip.close();

    if (!isGGTfile) {
      // ggb file: remove all macros from kernel before processing
      kernel.removeAllMacros();
    }

    // process macros
    if (macroXmlFileBuffer != null) {
      // don't clear kernel for macro files
      processXMLBuffer(macroXmlFileBuffer, !isGGTfile, isGGTfile);
    }

    // process construction
    if (!isGGTfile && xmlFileBuffer != null) {
      processXMLBuffer(xmlFileBuffer, !macroXMLfound, isGGTfile);
    }

    if (!(macroXMLfound || xmlFound)) throw new Exception("No XML data found in file.");
  }
Esempio n. 22
0
  /**
   * Evaluates a Maxima expression and returns the result as a string in Maxima syntax, e.g.
   * evaluateMaxima("integrate (sin(x)^3, x);") returns "cos(x)^3/3-cos(x)".
   *
   * @return result string (null possible)
   */
  public final synchronized String evaluateMaxima(String exp) {
    try {
      String result;

      // MathPiper has problems with indices like a_3, b_{12}
      exp = casParser.replaceIndices(exp);

      // Maxima uses [] for lists
      while (exp.indexOf('{') > -1) exp = exp.replace('{', '[');
      while (exp.indexOf('}') > -1) exp = exp.replace('}', ']');

      final boolean debug = true;
      if (debug) Application.debug("Expression for Maxima: " + exp, 1);

      String res = executeRaw(exp);

      while (res.indexOf('\n') > -1) res = res.replace('\n', ' ');

      String results[] = res.split("\\(%[oi]\\d+\\)\\s*");

      result = results[results.length - 1];

      // if last line is empty, look for next non-empty previous line
      if (result.trim().length() == 0 && results.length > 1) {
        int i = results.length - 2;
        while (results[i].trim().length() == 0 && i > 0) i--;
        result = results[i];
      }

      // remove (%o1) at start
      // result = result.replaceFirst("\\(%o\\d+\\)\\s*", "").trim();

      if (result.indexOf("%c") > -1) {
        result = result.replaceAll("%c", "const");
        Application.debug("WARNING: replacing %c by const", 1);
      }

      if (result.indexOf("%e") > -1) {
        result = result.replaceAll("%e", "e");
        Application.debug("WARNING: replacing %e by e", 1);
      }

      if (result.indexOf(" =") > -1) { // y = not :=
        result = result.replaceAll(" =", "==");
        Application.debug("WARNING: replacing = by ==", 1);
      }

      if (debug) {
        for (int i = 0; i < results.length; i++)
          System.err.println("Result " + i + ": " + results[i]);
        System.out.println("result: " + result);
      }

      // undo special character handling
      result = casParser.insertSpecialChars(result);

      // replace eg [x=0,x=1] with {x=0,x=1}
      while (result.indexOf('[') > -1) result = result.replace('[', '{');
      while (result.indexOf(']') > -1) result = result.replace(']', '}');

      // if the result consists of a list containing only 1 other list, flatten it
      result = result.trim();
      int cnt = 0;
      for (int i = 0; i < result.length(); ++i) if (result.charAt(i) == '{') ++cnt;
      if (cnt == 2) {
        if (result.startsWith("{{") && result.endsWith("}}"))
          result = result.substring(1, result.length() - 1);
        else
          throw new UnsupportedOperationException(
              "An unexpected error occurred while parsing Maxima's output");
      }

      return result;
    } catch (MaximaTimeoutException e) {
      Application.debug("Timeout from Maxima, resetting");
      ggbMaxima = null;
      return "?";
    }
  }
  // evaluate the current value of the arithmetic tree
  protected final void compute() {
    // get resulting list of ExpressionNodes
    ExpressionValue evlist = root.evaluate();
    MyList myList = (evlist instanceof MyList) ? (MyList) evlist : ((GeoList) evlist).getMyList();

    int evalListSize = myList.size();
    int cachedListSize = list.getCacheSize();

    list.clear();
    for (int i = 0; i < evalListSize; i++) {
      ExpressionValue element = myList.getListElement(i).evaluate();
      GeoElement geo = null;

      // number result
      if (element.isNumberValue()) {
        double val = ((NumberValue) element).getDouble();

        // try to use cached element of same type
        if (i < cachedListSize) {
          GeoElement cachedGeo = list.getCached(i);

          // the cached element is a number: set value
          if (cachedGeo.isGeoNumeric()) {
            ((GeoNumeric) cachedGeo).setValue(val);
            geo = cachedGeo;
          }
        }

        // no cached number: create new one
        if (geo == null) {
          geo = new GeoNumeric(cons, val);
        }

        // add number to list
        list.add(geo);
      }

      // point
      else if (element.isVectorValue()) {
        GeoVec2D vec = ((VectorValue) element).getVector();

        // try to use cached element of same type
        if (i < cachedListSize) {
          GeoElement cachedGeo = list.getCached(i);

          // the cached element is a point: set value
          if (cachedGeo.isGeoPoint()) {
            ((GeoPoint) cachedGeo).setCoords(vec);
            geo = cachedGeo;
          }
        }

        // no cached point: create new one
        if (geo == null) {
          GeoPoint point = new GeoPoint(cons);
          point.setCoords(vec);
          geo = point;
        }

        // add point to list
        list.add(geo);
      }

      // needed for matrix multiplication
      // eg {{1,3,5},{2,4,6}}*{{11,14},{12,15},{13,a}}
      else if (element instanceof MyList) {
        MyList myList2 = (MyList) element;
        GeoList list2 = new GeoList(cons);
        list2.clear();

        /* removed Michael Borcherds 20080602
         * bug: 9PointCubic.ggb (matrix multiplication)
        // try to use cached element of  type GeoList
        GeoList list2 = null;
        if (i < cachedListSize) {
        	GeoElement cachedGeo = list.getCached(i);

        	// the cached element is a number: set value
        	if (cachedGeo.isGeoList()) {
        		list2 = (GeoList) cachedGeo;
        	}
        }

        if (list2 == null) {
        	list2 = new GeoList(cons);
        } */

        for (int j = 0; j < myList2.size(); j++) {
          ExpressionValue en = myList2.getListElement(j);
          ExpressionValue ev = en.evaluate();

          if (ev instanceof MyDouble) {
            GeoNumeric geo2 = new GeoNumeric(cons);
            geo2.setValue(((NumberValue) ev).getDouble());
            list2.add(geo2);
          }
        }

        list.add(list2);
      } else if (element instanceof MyStringBuffer) {
        MyStringBuffer str = (MyStringBuffer) element;
        // try to use cached element of same type
        if (i < cachedListSize) {
          GeoElement cachedGeo = list.getCached(i);

          // the cached element is a point: set value
          if (cachedGeo.isGeoText()) {
            ((GeoText) cachedGeo).setTextString(str.toValueString());
            geo = cachedGeo;
          }
        }

        // no cached point: create new one
        if (geo == null) {
          GeoText text = new GeoText(cons);
          text.setTextString(str.toValueString());
          geo = text;
        }

        // add point to list
        list.add(geo);
      } else if (element instanceof MyBoolean) {
        MyBoolean bool = (MyBoolean) element;
        // try to use cached element of same type
        if (i < cachedListSize) {
          GeoElement cachedGeo = list.getCached(i);

          // the cached element is a point: set value
          if (cachedGeo.isGeoBoolean()) {
            ((GeoBoolean) cachedGeo).setValue(bool.getBoolean());
            geo = cachedGeo;
          }
        }

        // no cached point: create new one
        if (geo == null) {
          GeoBoolean geoBool = new GeoBoolean(cons);
          geoBool.setValue(bool.getBoolean());
          geo = geoBool;
        }

        // add point to list
        list.add(geo);
      } else if (element instanceof GeoFunction) {
        GeoFunction fun = (GeoFunction) element;
        if (i < cachedListSize) {
          GeoElement cachedGeo = list.getCached(i);

          // the cached element is a point: set value
          if (cachedGeo.isGeoFunction()) {
            ((GeoFunction) cachedGeo).set(fun);
            geo = cachedGeo;
          }
        }

        // no cached point: create new one
        if (geo == null) {
          GeoFunction geoFun = new GeoFunction(cons);
          geoFun.set(fun);
          geo = geoFun;
        }
        list.add(geo);

      } else {
        Application.debug("unsupported list addition: " + element.getClass() + "");
      }
    }
  }
Esempio n. 24
0
  /**
   * compare this to another Drawable3D with picking
   *
   * @param d the other Drawable3D
   * @param checkPickOrder say if the comparison has to look to pick order
   * @return 1 if this is in front, 0 if equality, -1 either
   */
  public int comparePickingTo(Drawable3D d, boolean checkPickOrder) {

    // check if one is transparent and the other not
    if ((!this.isTransparent()) && (d.isTransparent())) return -1;
    if ((this.isTransparent()) && (!d.isTransparent())) return 1;

    // check if the two objects are "mixed"
    if ((this.zPickMin - d.zPickMin) * (this.zPickMax - d.zPickMax) < EPSILON_Z) {

      if (DEBUG) {
        DecimalFormat df = new DecimalFormat("0.000000000");
        Application.debug(
            "mixed :\n"
                + "zMin= "
                + df.format(this.zPickMin)
                + " | zMax= "
                + df.format(this.zPickMax)
                + " ("
                + this.getGeoElement().getLabel()
                + ")\n"
                + "zMin= "
                + df.format(d.zPickMin)
                + " | zMax= "
                + df.format(d.zPickMax)
                + " ("
                + d.getGeoElement().getLabel()
                + ")\n");
      }

      if (checkPickOrder) {
        if (this.getPickOrder() < d.getPickOrder()) return -1;
        if (this.getPickOrder() > d.getPickOrder()) return 1;
      }

      // if both are points, check if one is on a path and the other not
      if (this.getGeoElement().isGeoPoint() && d.getGeoElement().isGeoPoint()) {
        if ((((GeoPointND) this.getGeoElement()).hasPath())
            && (!((GeoPointND) d.getGeoElement()).hasPath())) return -1;
        if ((!((GeoPointND) this.getGeoElement()).hasPath())
            && (((GeoPointND) d.getGeoElement()).hasPath())) return 1;
      }

      // smaller object is more likely to be picked
      // Note: all objects that are not yet have defined a measure have a default measure = 0
      // so that they are not affected by this comparison.
      if (Kernel.isGreater(d.getGeoElement().getMeasure(), this.getGeoElement().getMeasure()))
        return -1;
      if (Kernel.isGreater(this.getGeoElement().getMeasure(), d.getGeoElement().getMeasure()))
        return 1;

      // check if one is the child of the other
      if (this.getGeoElement().isChildOf(d.getGeoElement())) return -1;
      if (d.getGeoElement().isChildOf(d.getGeoElement())) return 1;
    }

    // finally check if one is before the other
    if (this.zPickMin < d.zPickMin) return -1;
    if (this.zPickMin > d.zPickMin) return 1;

    // says that the two objects are equal for the comparator
    if (DEBUG) {
      DecimalFormat df = new DecimalFormat("0.000000000");
      Application.debug(
          "equality :\n"
              + "zMin= "
              + df.format(this.zPickMin)
              + " | zMax= "
              + df.format(this.zPickMax)
              + " ("
              + this.getGeoElement().getLabel()
              + ")\n"
              + "zMin= "
              + df.format(d.zPickMin)
              + " | zMax= "
              + df.format(d.zPickMax)
              + " ("
              + d.getGeoElement().getLabel()
              + ")\n");
    }
    return 0;
  }
Esempio n. 25
0
  public GeoElement[] processExpressionNode(ExpressionNode n) throws MyError {
    // command is leaf: process command
    if (n.isLeaf()) {
      ExpressionValue leaf = n.getLeft();
      if (leaf instanceof Command) {
        Command c = (Command) leaf;
        c.setLabels(n.getLabels());
        return cmdDispatcher.processCommand(c, true);
      } else if (leaf instanceof Equation) {
        Equation eqn = (Equation) leaf;
        eqn.setLabels(n.getLabels());
        return processEquation(eqn);
      } else if (leaf instanceof Function) {
        Function fun = (Function) leaf;
        fun.setLabels(n.getLabels());
        return processFunction(n, fun);
      } else if (leaf instanceof FunctionNVar) {
        FunctionNVar fun = (FunctionNVar) leaf;
        fun.setLabels(n.getLabels());
        return processFunctionNVar(n, fun);
      }
    }

    // ELSE:  resolve variables and evaluate expressionnode
    n.resolveVariables();
    eval = n.evaluate();
    boolean dollarLabelFound = false;

    ExpressionNode myNode = n;
    if (myNode.isLeaf()) myNode = myNode.getLeftTree();
    // leaf (no new label specified): just return the existing GeoElement
    if (eval.isGeoElement()
        && n.getLabel() == null
        && !(n.operation.equals(Operation.ELEMENT_OF))) {
      // take care of spreadsheet $ names: don't loose the wrapper ExpressionNode here
      // check if we have a Variable
      switch (myNode.getOperation()) {
        case $VAR_COL:
        case $VAR_ROW:
        case $VAR_ROW_COL:
          // don't do anything here: we need to keep the wrapper ExpressionNode
          // and must not return the GeoElement here
          dollarLabelFound = true;
          break;

        default:
          // return the GeoElement
          GeoElement[] ret = {(GeoElement) eval};
          return ret;
      }
    }

    if (eval.isBooleanValue()) return processBoolean(n, eval);
    else if (eval.isNumberValue()) return processNumber(n, eval);
    else if (eval.isVectorValue()) return processPointVector(n, eval);
    else if (eval.isVector3DValue()) return processPointVector3D(n, eval);
    else if (eval.isTextValue()) return processText(n, eval);
    else if (eval instanceof MyList) {
      return processList(n, (MyList) eval);
    } else if (eval instanceof Function) {
      return processFunction(n, (Function) eval);
    } else if (eval instanceof FunctionNVar) {

      return processFunctionNVar(n, (FunctionNVar) eval);
    }
    // we have to process list in case list=matrix1(1), but not when list=list2
    else if (eval instanceof GeoList && myNode.hasOperations()) {
      Application.debug("should work");
      return processList(n, ((GeoList) eval).getMyList());
    } else if (eval.isGeoElement()) {

      // e.g. B1 = A1 where A1 is a GeoElement and B1 does not exist yet
      // create a copy of A1
      if (n.getLabel() != null || dollarLabelFound) {
        return processGeoCopy(n.getLabel(), n);
      }
    }

    // REMOVED due to issue 131: http://code.google.com/p/geogebra/issues/detail?id=131
    //		// expressions like 2 a (where a:x + y = 1)
    //		// A1=b doesn't work for these objects
    //		else if (eval instanceof GeoLine) {
    //			if (((GeoLine)eval).getParentAlgorithm() instanceof AlgoDependentLine) {
    //				GeoElement[] ret = {(GeoElement) eval };
    //				return ret;
    //			}
    //
    //		}

    // if we get here, nothing worked
    Application.debug("Unhandled ExpressionNode: " + eval + ", " + eval.getClass());
    return null;
  }
Esempio n. 26
0
  protected void updateLabel() {

    // draw numbers
    GeoAxis3D axis = (GeoAxis3D) getGeoElement();

    NumberFormat numberFormat = axis.getNumberFormat();
    double distance = axis.getNumbersDistance();

    // Application.debug("drawMinMax="+getDrawMin()+","+getDrawMax());
    double[] minmax = getDrawMinMax();

    int iMin = (int) (minmax[0] / distance);
    int iMax = (int) (minmax[1] / distance);
    int nb = iMax - iMin + 1;

    // Application.debug("iMinMax="+iMin+","+iMax);

    if (nb < 1) {
      Application.debug("nb=" + nb);
      // labels = null;
      return;
    }

    // sets all already existing labels not visible
    for (DrawLabel3D label : labels.values()) label.setIsVisible(false);

    for (int i = iMin; i <= iMax; i++) {
      double val = i * distance;
      Coords origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);

      // draw numbers
      String strNum = getView3D().getKernel().formatPiE(val, numberFormat);

      // check if the label already exists
      DrawLabel3D label = labels.get(strNum);
      if (label != null) {
        // sets the label visible
        label.setIsVisible(true);
        label.update(
            strNum,
            10,
            getGeoElement().getObjectColor(),
            origin.copyVector(),
            axis.getNumbersXOffset(),
            axis.getNumbersYOffset());
        // TODO optimize this
      } else {
        // creates new label
        label = new DrawLabel3D(getView3D());
        label.setAnchor(true);
        label.update(
            strNum,
            10,
            getGeoElement().getObjectColor(),
            origin.copyVector(),
            axis.getNumbersXOffset(),
            axis.getNumbersYOffset());
        labels.put(strNum, label);
      }
    }

    // update end of axis label
    label.update(
        ((GeoAxis3D) getGeoElement()).getAxisLabel(),
        10,
        getGeoElement().getObjectColor(),
        ((GeoCoordSys1D) getGeoElement()).getPoint(minmax[1]),
        axis.labelOffsetX - 4,
        axis.labelOffsetY - 6);
  }
Esempio n. 27
0
  /**
   * processes valid expression.
   *
   * @param ve
   * @param redefineIndependent == true: independent objects are redefined too
   * @throws MyError
   * @throws Exception
   * @return
   */
  public GeoElement[] processValidExpression(ValidExpression ve, boolean redefineIndependent)
      throws MyError, Exception {

    // check for existing labels
    String[] labels = ve.getLabels();
    GeoElement replaceable = null;
    if (labels != null && labels.length > 0) {
      boolean firstTime = true;
      for (int i = 0; i < labels.length; i++) {
        GeoElement geo = kernel.lookupLabel(labels[i]);
        if (geo != null) {
          if (geo.isFixed()) {
            String[] strs = {
              "IllegalAssignment", "AssignmentToFixed", ":\n", geo.getLongDescription()
            };
            throw new MyError(app, strs);
          } else {
            // replace (overwrite or redefine) geo
            if (firstTime) { // only one geo can be replaced
              replaceable = geo;
              firstTime = false;
            }
          }
        }
      }
    }

    GeoElement[] ret;
    boolean oldMacroMode = cons.isSuppressLabelsActive();
    if (replaceable != null) cons.setSuppressLabelCreation(true);

    // we have to make sure that the macro mode is
    // set back at the end
    try {
      ret = doProcessValidExpression(ve);

      if (ret == null) { // eg (1,2,3) running in 2D
        Application.debug("Unhandled ValidExpression : " + ve);
        throw new MyError(app, app.getError("InvalidInput") + ":\n" + ve);
      }
    } finally {
      cons.setSuppressLabelCreation(oldMacroMode);
    }

    //	try to replace replaceable geo by ret[0]
    if (replaceable != null && ret != null && ret.length > 0) {
      // a changeable replaceable is not redefined:
      // it gets the value of ret[0]
      // (note: texts are always redefined)
      if (!redefineIndependent && replaceable.isChangeable() && !(replaceable.isGeoText())) {
        try {
          replaceable.set(ret[0]);
          replaceable.updateRepaint();
          ret[0] = replaceable;
        } catch (Exception e) {
          String errStr =
              app.getError("IllegalAssignment")
                  + "\n"
                  + replaceable.getLongDescription()
                  + "     =     "
                  + ret[0].getLongDescription();
          throw new MyError(app, errStr);
        }
      }
      // redefine
      else {
        try {
          // SPECIAL CASE: set value
          // new and old object are both independent and have same type:
          // simply assign value and don't redefine
          if (replaceable.isIndependent()
              && ret[0].isIndependent()
              && replaceable.getGeoClassType() == ret[0].getGeoClassType()) {
            replaceable.set(ret[0]);
            replaceable.updateRepaint();
            ret[0] = replaceable;
          }

          // STANDARD CASE: REDFINED
          else {
            GeoElement newGeo = ret[0];
            cons.replace(replaceable, newGeo);

            // now all objects have changed
            // get the new object with same label as our result
            String newLabel = newGeo.isLabelSet() ? newGeo.getLabel() : replaceable.getLabel();
            ret[0] = kernel.lookupLabel(newLabel, false);
          }
        } catch (CircularDefinitionException e) {
          throw e;
        } catch (Exception e) {
          e.printStackTrace();
          throw new MyError(app, "ReplaceFailed");
        } catch (MyError e) {
          e.printStackTrace();
          throw new MyError(app, "ReplaceFailed");
        }
      }
    }

    return ret;
  }
 public synchronized void handleReOpenApplication(com.apple.eawt.ApplicationEvent arg0) {
   Application.debug("handleReOpenApplication event, filename: " + arg0.getFilename());
 }
 public synchronized void handlePreferences(com.apple.eawt.ApplicationEvent arg0) {
   Application.debug("handlePreferences event, filename: " + arg0.getFilename());
 }
  public synchronized void handlePrintFile(com.apple.eawt.ApplicationEvent event) {
    Application.debug("handlePrintFile event, filename: " + event.getFilename());

    handleOpenFile(event);
    getGGBInstance().getApplication().getGuiManager().showPrintPreview();
  }