Exemplo n.º 1
0
  public JPanel update(Object[] geos) {
    this.geos = geos;
    if (!checkGeos(geos)) return null;

    tfAnimStep.removeActionListener(this);

    // check if properties have same values
    GeoElement temp, geo0 = (GeoElement) geos[0];
    boolean equalStep = true;
    boolean onlyAngles = true;

    for (int i = 0; i < geos.length; i++) {
      temp = (GeoElement) geos[i];
      // same object visible value
      if (!Kernel.isEqual(geo0.getAnimationStep(), temp.getAnimationStep())) equalStep = false;
      if (!(temp.isGeoAngle())) onlyAngles = false;
    }

    // set trace visible checkbox
    // int oldDigits = kernel.getMaximumFractionDigits();
    // kernel.setMaximumFractionDigits(PropertiesDialog.TEXT_FIELD_FRACTION_DIGITS);
    StringTemplate highPrecision =
        StringTemplate.printDecimals(
            StringType.GEOGEBRA, PropertiesDialog.TEXT_FIELD_FRACTION_DIGITS, false);

    if (equalStep) {
      GeoElement stepGeo = geo0.getAnimationStepObject();
      if (onlyAngles && (stepGeo == null || (!stepGeo.isLabelSet() && stepGeo.isIndependent())))
        tfAnimStep.setText(kernel.formatAngle(geo0.getAnimationStep(), highPrecision).toString());
      else tfAnimStep.setText(stepGeo.getLabel(highPrecision));
    } else tfAnimStep.setText("");

    tfAnimStep.addActionListener(this);
    return this;
  }
Exemplo n.º 2
0
  // calc angle between vectors A-B and C-B
  // angle in range [0, pi]
  @Override
  public void compute() {

    GeoPoint2 A = (GeoPoint2) An;
    GeoPoint2 B = (GeoPoint2) Bn;
    GeoPoint2 C = (GeoPoint2) Cn;

    if (!A.isFinite() || !B.isFinite() || !C.isFinite()) {
      angle.setUndefined(); // undefined
      return;
    }

    // get vectors v=BA and w=BC
    bx = B.inhomX;
    by = B.inhomY;
    vx = A.inhomX - bx;
    vy = A.inhomY - by;
    wx = C.inhomX - bx;
    wy = C.inhomY - by;

    if (Kernel.isZero(vx) && Kernel.isZero(vy) || Kernel.isZero(wx) && Kernel.isZero(wy)) {
      angle.setUndefined();
      return;
    }

    // |v| * |w| * sin(alpha) = det(v, w)
    // cos(alpha) = v . w / (|v| * |w|)
    // tan(alpha) = sin(alpha) / cos(alpha)
    // => tan(alpha) = det(v, w) / v . w
    double det = vx * wy - vy * wx;
    double prod = vx * wx + vy * wy;
    double value = Math.atan2(det, prod);

    angle.setValue(value);
  }
Exemplo n.º 3
0
  /**
   * Translates a given expression in the format expected by the cas.
   *
   * @param ve the Expression to be translated
   * @param casStringType one of StringType.{MAXIMA, MPREDUCE, MATH_PIPER}
   * @return the translated String.
   */
  protected String translateToCAS(ValidExpression ve, StringType casStringType) {
    Kernel kernel = ve.getKernel();
    StringType oldPrintForm = kernel.getCASPrintForm();
    kernel.setCASPrintForm(casStringType);

    try {
      ValidExpression tmp = ve;
      if (!ve.isExpressionNode()) tmp = new ExpressionNode(kernel, ve);

      String body = ((ExpressionNode) tmp).getCASstring(casStringType, true);

      // handle assignments
      String label = ve.getLabel();
      if (label != null) { // is an assignment or a function declaration
        // make sure to escape labels to avoid problems with reserved
        // CAS labels
        label = kernel.printVariableName(casStringType, label);
        if (ve instanceof FunctionNVar) {
          FunctionNVar fun = (FunctionNVar) ve;
          return translateFunctionDeclaration(label, fun.getVarString(), body);
        }
        return translateAssignment(label, body);
      }
      return body;
    } finally {
      kernel.setCASPrintForm(oldPrintForm);
    }
  }
Exemplo n.º 4
0
  /**
   * @param app application
   * @return All tools as a toolbar definition string
   */
  public static String getAllTools(AppD app) {
    StringBuilder sb = new StringBuilder();

    sb.append(ToolBar.getAllToolsNoMacros(true, false));

    // macros
    Kernel kernel = app.getKernel();
    int macroNumber = kernel.getMacroNumber();

    // check if at least one macro is shown
    // to avoid strange GUI
    boolean at_least_one_shown = false;
    for (int i = 0; i < macroNumber; i++) {
      Macro macro = kernel.getMacro(i);
      if (macro.isShowInToolBar()) {
        at_least_one_shown = true;
        break;
      }
    }

    if (macroNumber > 0 && at_least_one_shown) {
      sb.append(" || ");
      for (int i = 0; i < macroNumber; i++) {
        Macro macro = kernel.getMacro(i);
        if (macro.isShowInToolBar()) {
          sb.append(i + EuclidianConstants.MACRO_MODE_ID_OFFSET);
          sb.append(" ");
        }
      }
    }

    return sb.toString();
  }
Exemplo n.º 5
0
  /**
   * @param cmd the command to evaluate
   * @return the geo elements created
   * @throws Exception if it goes wrong!
   */
  public GeoElement[] evalCommand(String cmd) throws Exception {
    // this is new in GeoGebra 4.2 and it will stop some files working
    // but causes problems if the files are opened and edited
    boolean oldVal = kernel.isUsingInternalCommandNames();
    kernel.setUseInternalCommandNames(true);

    GeoElement[] ret =
        algProcessor.processAlgebraCommandNoExceptionHandling(cmd, false, false, false);

    kernel.setUseInternalCommandNames(oldVal);

    return ret;
  }
Exemplo n.º 6
0
  public final void compute() {
    // Check if the points are aligned

    double x1 = -A.inhomX;
    double y1 = -A.inhomY;
    double x2 = -B.inhomX;
    double y2 = -B.inhomY;
    double x3 = -C.inhomX;
    double y3 = -C.inhomY;

    double det = (-x2 + x3) * (y1 - y3) + (x1 - x3) * (y2 - y3);
    if (Kernel.isZero(det)) {
      poly.setUndefined();
    } else {
      ycoef[0].setValue((x3 - x2) / det);
      xcoef[0].setValue((y2 - y3) / det);
      constant[0].setValue(((x3 - x2) * y3 + (y2 - y3) * x3) / det);
      ycoef[1].setValue((x1 - x3) / det);
      xcoef[1].setValue((y3 - y1) / det);
      constant[1].setValue(((x1 - x3) * y1 + (y3 - y1) * x1) / det);
      ycoef[2].setValue((x2 - x1) / det);
      xcoef[2].setValue((y1 - y2) / det);
      constant[2].setValue(((x2 - x1) * y2 + (y1 - y2) * x2) / det);
      dd.update();
      poly.update();
    }
  }
Exemplo n.º 7
0
  @Override
  public final void update() {
    isVisible = geo.isEuclidianVisible();
    if (!isVisible) return;
    labelVisible = geo.isLabelVisible();
    updateStrokes(n);
    if (!geo.getDrawAlgorithm().equals(geo.getParentAlgorithm())) init();

    if (gp == null) gp = new GeneralPathClipped(view);
    else gp.reset();

    // init gp
    double aRW = a.getDouble();
    double bRW = b.getDouble();

    // for DrawParametricCurve.plotCurve to work with special values,
    // these changes are needed (also filter out out of screen integrals)
    // see #1234
    aRW = Math.max(aRW, view.getXmin() - EuclidianStatic.CLIP_DISTANCE);
    if (aRW > view.getXmax() + EuclidianStatic.CLIP_DISTANCE) return;

    bRW = Math.min(bRW, view.getXmax() + EuclidianStatic.CLIP_DISTANCE);
    if (bRW < view.getXmin() - EuclidianStatic.CLIP_DISTANCE) return;

    double ax = view.toScreenCoordXd(aRW);
    double bx = view.toScreenCoordXd(bRW);
    float y0 = (float) view.getyZero();

    // plot definite integral

    if (Kernel.isEqual(aRW, bRW)) {
      gp.moveTo(ax, y0);
      gp.lineTo(ax, view.toScreenCoordYd(f.evaluate(aRW)));
      gp.lineTo(ax, y0);
      return;
    }

    gp.moveTo(ax, y0);
    DrawParametricCurve.plotCurve(f, aRW, bRW, view, gp, false, DrawParametricCurve.GAP_LINE_TO);
    gp.lineTo(bx, y0);
    gp.lineTo(ax, y0);

    // gp on screen?
    if (!gp.intersects(0, 0, view.getWidth(), view.getHeight())) {
      isVisible = false;
      // don't return here to make sure that getBounds() works for
      // offscreen points too
    }

    if (labelVisible) {
      xLabel = (int) Math.round((ax + bx) / 2) - 6;
      yLabel = (int) view.getyZero() - view.getFontSize();
      labelDesc = geo.getLabelDescription();
      addLabelOffset();
    }
  }
Exemplo n.º 8
0
 private void doActionPerformed() {
   NumberValue newVal = kernel.getAlgebraProcessor().evaluateToNumeric(tfAnimStep.getText(), true);
   if (newVal != null && !Double.isNaN(newVal.getDouble())) {
     for (int i = 0; i < geos.length; i++) {
       GeoElement geo = (GeoElement) geos[i];
       geo.setAnimationStep(newVal);
       geo.updateRepaint();
     }
   }
   update(geos);
 }
Exemplo n.º 9
0
  /** Called if the user changes the selected items. */
  public void updateSelection() {
    int layer = getSelectedLayer();

    /* layer values:
     *  -1 means nothing selected
     *  -2 means different layers selected
     */

    boolean justCreated =
        !(app.getActiveEuclidianView().getEuclidianController().getJustCreatedGeos().isEmpty());

    copyAction.setEnabled(!app.getSelectedGeos().isEmpty());
    pasteAction.setEnabled(!CopyPaste.isEmpty());

    deleteAction.setEnabled(layer != -1 || justCreated);
    deleteItem.setVisible(layer != -1 || justCreated);
    deleteSeparator.setVisible(layer != -1 || justCreated);

    showhideAction.setEnabled(layer != -1);
    showhideItem.setVisible(layer != -1);

    showhideLabelsAction.setEnabled(layer != -1);
    showhideLabelsItem.setVisible(layer != -1);

    // exactly one layer selected
    selectCurrentLayerAction.setEnabled(getSelectedLayer() >= 0);
    selectCurrentLayerItem.setVisible(getSelectedLayer() >= 0);

    boolean haveSelection = !app.getSelectedGeos().isEmpty();
    invertAction.setEnabled(haveSelection);
    invertItem.setVisible(haveSelection);
    selectAllDescendantsAction.setEnabled(haveSelection);
    selectAllDescendantsItem.setVisible(haveSelection);
    selectAllAncestorsAction.setEnabled(haveSelection);
    selectAllAncestorsItem.setVisible(haveSelection);
    selectionSeparator.setVisible(haveSelection);

    Kernel kernel = app.getKernel();
    propertiesAction.setEnabled(!kernel.isEmpty());
    selectAllAction.setEnabled(!kernel.isEmpty());
  }
Exemplo n.º 10
0
  private void addAxesRatioItems(JMenu menu) {
    ActionListener al =
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            try {
              zoomYaxis(Double.parseDouble(e.getActionCommand()));
            } catch (Exception ex) {
            }
          }
        };

    // get current axes ratio
    double scaleRatio = ((AbstractEuclidianView) app.getActiveEuclidianView()).getScaleRatio();

    JMenuItem mi;
    // int perc;
    // ImageIcon icon;
    boolean separatorAdded = false;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < axesRatios.length; i++) {
      // build text like "1 : 2"
      sb.setLength(0);
      if (axesRatios[i] > 1.0) {
        sb.append((int) axesRatios[i]);
        sb.append(" : 1");
        if (!separatorAdded) {
          menu.addSeparator();
          separatorAdded = true;
        }

      } else { // factor
        if (axesRatios[i] == 1) menu.addSeparator();
        sb.append("1 : ");
        sb.append((int) (1.0 / axesRatios[i]));
      }

      mi = new JCheckBoxMenuItem(sb.toString());
      mi.setSelected(Kernel.isEqual(axesRatios[i], scaleRatio));
      mi.setActionCommand("" + axesRatios[i]);
      mi.addActionListener(al);
      mi.setBackground(getBackground());
      menu.add(mi);
    }
  }
Exemplo n.º 11
0
 @Override
 public void compute() {
   if (!factorList.isDefined() || !Kernel.isInteger(number.getDouble())) {
     result.setUndefined();
     return;
   }
   long res = 1;
   for (int i = 0; i < factorList.size(); i++) {
     GeoList pair = (GeoList) factorList.get(i);
     double exp = ((NumberValue) pair.get(1)).getDouble();
     if (sum) {
       double prime = ((NumberValue) pair.get(0)).getDouble();
       App.debug(prime);
       res = res * Math.round((Math.pow(prime, exp + 1) - 1) / (prime - 1.0));
     } else {
       res = res * Math.round(exp + 1);
     }
   }
   result.setValue(res);
 }
Exemplo n.º 12
0
  private boolean processInput() {

    // avoid labeling of num
    Construction cons = kernel.getConstruction();
    boolean oldVal = cons.isSuppressLabelsActive();
    cons.setSuppressLabelCreation(true);

    inputText = inputPanel.getText();

    // negative orientation ?
    if (rbClockWise.getValue()) {
      inputText = "-(" + inputText + ")";
    }

    boolean success = inputHandler.processInput(inputText);

    cons.setSuppressLabelCreation(oldVal);

    if (success) {
      String angleText = inputPanel.getText();
      // keep angle entered if it ends with 'degrees'
      if (angleText.endsWith("\u00b0")) defaultRotateAngle = angleText;
      else defaultRotateAngle = "45" + "\u00b0";

      DialogManagerW.doAngleFixed(
          kernel,
          segments,
          points,
          selGeos,
          ((NumberInputHandler) inputHandler).getNum(),
          rbClockWise.getValue());

      return true;
    }

    return false;
  }
Exemplo n.º 13
0
 public void setLabels() {
   label.setText(kernel.getApplication().getPlain("AnimationStep") + ": ");
 }
Exemplo n.º 14
0
  public void updateFonts() {
    Font font = ((AppD) kernel.getApplication()).getPlainFont();

    label.setFont(font);
    tfAnimStep.setFont(font);
  }
Exemplo n.º 15
0
 /**
  * This method returns a CommandProcessor Object for a corresponding command name. This should be
  * called only if that CommandProcessor object is not there already in the command table.
  *
  * @param cmdName String command name
  * @return Processor for given command
  */
 public CommandProcessor commandTableSwitch(String cmdName) {
   try {
     // This enum switch is Markus's idea.
     // Arpad Fekete, 2011-09-28
     switch (Commands.valueOf(cmdName)) {
       case Mod:
         return new CmdMod(kernel);
       case Div:
         return new CmdDiv(kernel);
       case Min:
         return new CmdMin(kernel);
       case Max:
         return new CmdMax(kernel);
       case LCM:
         return new CmdLCM(kernel);
       case GCD:
         return new CmdGCD(kernel);
       case Expand:
         return new CmdExpand(kernel);
       case Factor:
         return new CmdFactor(kernel);
       case Simplify:
         return new CmdSimplify(kernel);
       case PrimeFactors:
         return new CmdPrimeFactors(kernel);
       case CompleteSquare:
         return new CmdCompleteSquare(kernel);
       case Line:
         return new CmdLine(kernel);
       case Ray:
         return new CmdRay(kernel);
       case AngularBisector:
         return new CmdAngularBisector(kernel);
       case OrthogonalLine:
         return new CmdOrthogonalLine(kernel);
       case Tangent:
         return new CmdTangent(kernel);
       case Segment:
         return new CmdSegment(kernel);
       case Slope:
         return new CmdSlope(kernel);
       case Angle:
         return new CmdAngle(kernel);
       case Direction:
         return new CmdDirection(kernel);
       case Point:
         return new CmdPoint(kernel);
       case Midpoint:
         return new CmdMidpoint(kernel);
       case LineBisector:
         return new CmdLineBisector(kernel);
       case Intersect:
         return new CmdIntersect(kernel);
       case IntersectRegion:
         return new CmdIntersectRegion(kernel);
       case Distance:
         return new CmdDistance(kernel);
       case Length:
         return new CmdLength(kernel);
       case Radius:
         return new CmdRadius(kernel);
       case CircleArc:
         return new CmdCircleArc(kernel);
       case Arc:
         return new CmdArc(kernel);
       case Sector:
         return new CmdSector(kernel);
       case CircleSector:
         return new CmdCircleSector(kernel);
       case CircumcircleSector:
         return new CmdCircumcircleSector(kernel);
       case CircumcircleArc:
         return new CmdCircumcircleArc(kernel);
       case Polygon:
         return new CmdPolygon(kernel);
       case RigidPolygon:
         return new CmdRigidPolygon(kernel);
       case Area:
         return new CmdArea(kernel);
       case Union:
         return new CmdUnion(kernel);
       case Circumference:
         return new CmdCircumference(kernel);
       case Perimeter:
         return new CmdPerimeter(kernel);
       case Locus:
         return new CmdLocus(kernel);
       case Centroid:
         return new CmdCentroid(kernel);
       case TriangleCenter:
         return new CmdKimberling(kernel);
       case Barycenter:
         return new CmdBarycenter(kernel);
       case Trilinear:
         return new CmdTrilinear(kernel);
       case TriangleCubic:
         return new CmdTriangleCubic(kernel);
       case TriangleCurve:
         return new CmdTriangleCurve(kernel);
       case Vertex:
         return new CmdVertex(kernel);
       case PolyLine:
         return new CmdPolyLine(kernel);
       case PointIn:
         return new CmdPointIn(kernel);
       case AffineRatio:
         return new CmdAffineRatio(kernel);
       case CrossRatio:
         return new CmdCrossRatio(kernel);
       case ClosestPoint:
         return new CmdClosestPoint(kernel);
       case Text:
         return new CmdText(kernel);
       case LaTeX:
         return new CmdLaTeX(kernel);
       case LetterToUnicode:
         return new CmdLetterToUnicode(kernel);
       case TextToUnicode:
         return new CmdTextToUnicode(kernel);
       case UnicodeToText:
         return new CmdUnicodeToText(kernel);
       case UnicodeToLetter:
         return new CmdUnicodeToLetter(kernel);
       case FractionText:
         return new CmdFractionText(kernel);
       case SurdText:
         return new CmdSurdText(kernel);
       case TableText:
         return new CmdTableText(kernel);
       case VerticalText:
         return new CmdVerticalText(kernel);
       case RotateText:
         return new CmdRotateText(kernel);
       case Ordinal:
         return new CmdOrdinal(kernel);
       case If:
         return new CmdIf(kernel);
       case CountIf:
         return new CmdCountIf(kernel);
       case IsInteger:
         return new CmdIsInteger(kernel);
       case KeepIf:
         return new CmdKeepIf(kernel);
       case Relation:
         return new CmdRelation(kernel);
       case Defined:
         return new CmdDefined(kernel);
       case IsInRegion:
         return new CmdIsInRegion(kernel);
       case Root:
         return new CmdRoot(kernel);
       case Roots:
         return new CmdRoots(kernel);
       case TurningPoint:
         return new CmdTurningPoint(kernel);
       case Polynomial:
         return new CmdPolynomial(kernel);
       case Function:
         return new CmdFunction(kernel);
       case Extremum:
         return new CmdExtremum(kernel);
       case CurveCartesian:
         return new CmdCurveCartesian(kernel);
       case Derivative:
         return new CmdDerivative(kernel);
       case Integral:
         return new CmdIntegral(kernel, false);
       case IntegralBetween:
         return new CmdIntegral(kernel, true);
       case LowerSum:
         return new CmdLowerSum(kernel);
       case LeftSum:
         return new CmdLeftSum(kernel);
       case RectangleSum:
         return new CmdRectangleSum(kernel);
       case TaylorSeries:
         return new CmdTaylorSeries(kernel);
       case UpperSum:
         return new CmdUpperSum(kernel);
       case TrapezoidalSum:
         return new CmdTrapezoidalSum(kernel);
       case Limit:
         return new CmdLimit(kernel);
       case LimitBelow:
         return new CmdLimitBelow(kernel);
       case LimitAbove:
         return new CmdLimitAbove(kernel);
       case Factors:
         return new CmdFactors(kernel);
       case Degree:
         return new CmdDegree(kernel);
       case Coefficients:
         return new CmdCoefficients(kernel);
       case PartialFractions:
         return new CmdPartialFractions(kernel);
       case Numerator:
         return new CmdNumerator(kernel);
       case Denominator:
         return new CmdDenominator(kernel);
       case ComplexRoot:
         return new CmdComplexRoot(kernel);
       case SolveODE:
         return new CmdSolveODE(kernel);
       case Iteration:
         return new CmdIteration(kernel);
       case PathParameter:
         return new CmdPathParameter(kernel);
       case Asymptote:
         return new CmdAsymptote(kernel);
       case CurvatureVector:
         return new CmdCurvatureVector(kernel);
       case Curvature:
         return new CmdCurvature(kernel);
       case OsculatingCircle:
         return new CmdOsculatingCircle(kernel);
       case IterationList:
         return new CmdIterationList(kernel);
       case RootList:
         return new CmdRootList(kernel);
       case ImplicitCurve:
         return new CmdImplicitPoly(kernel);
       case Ellipse:
         return new CmdEllipse(kernel);
       case Hyperbola:
         return new CmdHyperbola(kernel);
       case SecondAxisLength:
         return new CmdSecondAxisLength(kernel);
       case SecondAxis:
         return new CmdSecondAxis(kernel);
       case Directrix:
         return new CmdDirectrix(kernel);
       case Diameter:
         return new CmdDiameter(kernel);
       case Conic:
         return new CmdConic(kernel);
       case FirstAxis:
         return new CmdFirstAxis(kernel);
       case Circle:
         return new CmdCircle(kernel);
       case Incircle:
         return new CmdIncircle(kernel);
       case Semicircle:
         return new CmdSemicircle(kernel);
       case FirstAxisLength:
         return new CmdFirstAxisLength(kernel);
       case Parabola:
         return new CmdParabola(kernel);
       case Focus:
         return new CmdFocus(kernel);
       case Parameter:
         return new CmdParameter(kernel);
       case Center:
         return new CmdCenter(kernel);
       case Polar:
         return new CmdPolar(kernel);
       case Excentricity:
         return new CmdExcentricity(kernel);
       case Eccentricity:
         return new CmdEccentricity(kernel);
       case Axes:
         return new CmdAxes(kernel);
       case Sort:
         return new CmdSort(kernel);
       case First:
         return new CmdFirst(kernel);
       case Last:
         return new CmdLast(kernel);
       case Take:
         return new CmdTake(kernel);
       case RemoveUndefined:
         return new CmdRemoveUndefined(kernel);
       case Reverse:
         return new CmdReverse(kernel);
       case Element:
         return new CmdElement(kernel);
       case IndexOf:
         return new CmdIndexOf(kernel);
       case Append:
         return new CmdAppend(kernel);
       case Join:
         return new CmdJoin(kernel);
       case Flatten:
         return new CmdFlatten(kernel);
       case Insert:
         return new CmdInsert(kernel);
       case Sequence:
         return new CmdSequence(kernel);
       case SelectedElement:
         return new CmdSelectedElement(kernel);
       case SelectedIndex:
         return new CmdSelectedIndex(kernel);
       case RandomElement:
         return new CmdRandomElement(kernel);
       case Product:
         return new CmdProduct(kernel);
       case Frequency:
         return new CmdFrequency(kernel);
       case Unique:
         return new CmdUnique(kernel);
       case Classes:
         return new CmdClasses(kernel);
       case Zip:
         return new CmdZip(kernel);
       case Intersection:
         return new CmdIntersection(kernel);
       case PointList:
         return new CmdPointList(kernel);
       case OrdinalRank:
         return new CmdOrdinalRank(kernel);
       case TiedRank:
         return new CmdTiedRank(kernel);
       case BarChart:
         return new CmdBarChart(kernel);
       case BoxPlot:
         return new CmdBoxPlot(kernel);
       case Histogram:
         return new CmdHistogram(kernel);
       case HistogramRight:
         return new CmdHistogramRight(kernel);
       case DotPlot:
         return new CmdDotPlot(kernel);
       case StemPlot:
         return new CmdStemPlot(kernel);
       case ResidualPlot:
         return new CmdResidualPlot(kernel);
       case FrequencyPolygon:
         return new CmdFrequencyPolygon(kernel);
       case NormalQuantilePlot:
         return new CmdNormalQuantilePlot(kernel);
       case FrequencyTable:
         return new CmdFrequencyTable(kernel);
       case Sum:
         return new CmdSum(kernel);
       case Mean:
         return new CmdMean(kernel);
       case Variance:
         return new CmdVariance(kernel);
       case SD:
         return new CmdSD(kernel);
       case SampleVariance:
         return new CmdSampleVariance(kernel);
       case SampleSD:
         return new CmdSampleSD(kernel);
       case Median:
         return new CmdMedian(kernel);
       case Q1:
         return new CmdQ1(kernel);
       case Q3:
         return new CmdQ3(kernel);
       case Mode:
         return new CmdMode(kernel);
       case SigmaXX:
         return new CmdSigmaXX(kernel);
       case SigmaXY:
         return new CmdSigmaXY(kernel);
       case SigmaYY:
         return new CmdSigmaYY(kernel);
       case Covariance:
         return new CmdCovariance(kernel);
       case SXY:
         return new CmdSXY(kernel);
       case SXX:
         return new CmdSXX(kernel);
       case SYY:
         return new CmdSYY(kernel);
       case MeanX:
         return new CmdMeanX(kernel);
       case MeanY:
         return new CmdMeanY(kernel);
       case PMCC:
         return new CmdPMCC(kernel);
       case SampleSDX:
         return new CmdSampleSDX(kernel);
       case SampleSDY:
         return new CmdSampleSDY(kernel);
       case SDX:
         return new CmdSDX(kernel);
       case SDY:
         return new CmdSDY(kernel);
       case FitLineY:
         return new CmdFitLineY(kernel);
       case FitLineX:
         return new CmdFitLineX(kernel);
       case FitPoly:
         return new CmdFitPoly(kernel);
       case FitExp:
         return new CmdFitExp(kernel);
       case FitLog:
         return new CmdFitLog(kernel);
       case FitPow:
         return new CmdFitPow(kernel);
       case Fit:
         return new CmdFit(kernel);
       case FitGrowth:
         return new CmdFitGrowth(kernel);
       case FitSin:
         return new CmdFitSin(kernel);
       case FitLogistic:
         return new CmdFitLogistic(kernel);
       case SumSquaredErrors:
         return new CmdSumSquaredErrors(kernel);
       case RSquare:
         return new CmdRSquare(kernel);
       case Sample:
         return new CmdSample(kernel);
       case Shuffle:
         return new CmdShuffle(kernel);
       case Spearman:
         return new CmdSpearman(kernel);
       case TTest:
         return new CmdTTest(kernel);
       case TTestPaired:
         return new CmdTTestPaired(kernel);
       case TTest2:
         return new CmdTTest2(kernel);
       case TMeanEstimate:
         return new CmdTMeanEstimate(kernel);
       case TMean2Estimate:
         return new CmdTMean2Estimate(kernel);
       case ANOVA:
         return new CmdANOVA(kernel);
       case Percentile:
         return new CmdPercentile(kernel);
       case GeometricMean:
         return new CmdGeometricMean(kernel);
       case HarmonicMean:
         return new CmdHarmonicMean(kernel);
       case RootMeanSquare:
         return new CmdRootMeanSquare(kernel);
       case Random:
         return new CmdRandom(kernel);
       case RandomNormal:
         return new CmdRandomNormal(kernel);
       case RandomUniform:
         return new CmdRandomUniform(kernel);
       case RandomBinomial:
         return new CmdRandomBinomial(kernel);
       case RandomPoisson:
         return new CmdRandomPoisson(kernel);
       case Normal:
         return new CmdNormal(kernel);
       case LogNormal:
         return new CmdLogNormal(kernel);
       case Logistic:
         return new CmdLogistic(kernel);
       case InverseNormal:
         return new CmdInverseNormal(kernel);
       case Binomial:
         return new CmdBinomial(kernel);
       case BinomialDist:
         return new CmdBinomialDist(kernel);
       case Bernoulli:
         return new CmdBernoulli(kernel);
       case InverseBinomial:
         return new CmdInverseBinomial(kernel);
       case TDistribution:
         return new CmdTDistribution(kernel);
       case InverseTDistribution:
         return new CmdInverseTDistribution(kernel);
       case FDistribution:
         return new CmdFDistribution(kernel);
       case InverseFDistribution:
         return new CmdInverseFDistribution(kernel);
       case Gamma:
         return new CmdGamma(kernel);
       case InverseGamma:
         return new CmdInverseGamma(kernel);
       case Cauchy:
         return new CmdCauchy(kernel);
       case InverseCauchy:
         return new CmdInverseCauchy(kernel);
       case ChiSquared:
         return new CmdChiSquared(kernel);
       case InverseChiSquared:
         return new CmdInverseChiSquared(kernel);
       case Exponential:
         return new CmdExponential(kernel);
       case InverseExponential:
         return new CmdInverseExponential(kernel);
       case HyperGeometric:
         return new CmdHyperGeometric(kernel);
       case InverseHyperGeometric:
         return new CmdInverseHyperGeometric(kernel);
       case Pascal:
         return new CmdPascal(kernel);
       case InversePascal:
         return new CmdInversePascal(kernel);
       case Poisson:
         return new CmdPoisson(kernel);
       case InversePoisson:
         return new CmdInversePoisson(kernel);
       case Weibull:
         return new CmdWeibull(kernel);
       case InverseWeibull:
         return new CmdInverseWeibull(kernel);
       case Zipf:
         return new CmdZipf(kernel);
       case InverseZipf:
         return new CmdInverseZipf(kernel);
       case Triangular:
         return new CmdTriangular(kernel);
       case Uniform:
         return new CmdUniform(kernel);
       case Erlang:
         return new CmdErlang(kernel);
       case ApplyMatrix:
         return new CmdApplyMatrix(kernel);
       case UnitVector:
         return new CmdUnitVector(kernel);
       case Vector:
         return new CmdVector(kernel);
       case UnitOrthogonalVector:
         return new CmdUnitOrthogonalVector(kernel);
       case OrthogonalVector:
         return new CmdOrthogonalVector(kernel);
       case Invert:
         return new CmdInvert(kernel);
       case Transpose:
         return new CmdTranspose(kernel);
       case ReducedRowEchelonForm:
         return new CmdReducedRowEchelonForm(kernel);
       case Determinant:
         return new CmdDeterminant(kernel);
       case Identity:
         return new CmdIdentity(kernel);
       case Mirror:
         return new CmdMirror(kernel);
       case Dilate:
         return new CmdDilate(kernel);
       case Rotate:
         return new CmdRotate(kernel);
       case Translate:
         return new CmdTranslate(kernel);
       case Shear:
         return new CmdShear(kernel);
       case Stretch:
         return new CmdStretch(kernel);
       case CellRange:
         return new CmdCellRange(kernel); // cell range for spreadsheet like A1:A5
       case Row:
         return new CmdRow(kernel);
       case Column:
         return new CmdColumn(kernel);
       case ColumnName:
         return new CmdColumnName(kernel);
       case FillRow:
         return new CmdFillRow(kernel);
       case FillColumn:
         return new CmdFillColumn(kernel);
       case FillCells:
         return new CmdFillCells(kernel);
       case Cell:
         return new CmdCell(kernel);
       case CopyFreeObject:
         return new CmdCopyFreeObject(kernel);
       case SetColor:
         return new CmdSetColor(kernel);
       case SetBackgroundColor:
         return new CmdSetBackgroundColor(kernel);
       case SetDynamicColor:
         return new CmdSetDynamicColor(kernel);
       case SetConditionToShowObject:
         return new CmdSetConditionToShowObject(kernel);
       case SetFilling:
         return new CmdSetFilling(kernel);
       case SetLineThickness:
         return new CmdSetLineThickness(kernel);
       case SetLineStyle:
         return new CmdLineStyle(kernel);
       case SetPointStyle:
         return new CmdSetPointStyle(kernel);
       case SetPointSize:
         return new CmdSetPointSize(kernel);
       case SetFixed:
         return new CmdSetFixed(kernel);
       case Rename:
         return new CmdRename(kernel);
       case HideLayer:
         return new CmdHideLayer(kernel);
       case ShowLayer:
         return new CmdShowLayer(kernel);
       case SetCoords:
         return new CmdSetCoords(kernel);
       case Pan:
         return new CmdPan(kernel);
       case ZoomIn:
         return new CmdZoomIn(kernel);
       case ZoomOut:
         return new CmdZoomOut(kernel);
       case SetActiveView:
         return new CmdSetActiveView(kernel);
       case SelectObjects:
         return new CmdSelectObjects(kernel);
       case SetLayer:
         return new CmdSetLayer(kernel);
       case SetCaption:
         return new CmdSetCaption(kernel);
       case SetLabelMode:
         return new CmdSetLabelMode(kernel);
       case SetTooltipMode:
         return new CmdSetTooltipMode(kernel);
       case UpdateConstruction:
         return new CmdUpdateConstruction(kernel);
       case SetValue:
         return new CmdSetValue(kernel);
       case PlaySound:
         return new CmdPlaySound(kernel);
       case ParseToNumber:
         return new CmdParseToNumber(kernel);
       case ParseToFunction:
         return new CmdParseToFunction(kernel);
       case StartAnimation:
         return new CmdStartAnimation(kernel);
       case Delete:
         return new CmdDelete(kernel);
       case Slider:
         return new CmdSlider(kernel);
       case Checkbox:
         return new CmdCheckbox(kernel);
       case Textfield:
         return new CmdTextfield(kernel);
       case Button:
         return new CmdButton(kernel);
       case Execute:
         return new CmdExecute(kernel);
       case GetTime:
         return new CmdGetTime(kernel);
       case ShowLabel:
         return new CmdShowLabel(kernel);
       case SetAxesRatio:
         return new CmdSetAxesRatio(kernel);
       case SetVisibleInView:
         return new CmdSetVisibleInView(kernel);
       case Voronoi:
         return new CmdVoronoi(kernel);
       case Hull:
         return new CmdHull(kernel);
       case ConvexHull:
         return new CmdConvexHull(kernel);
       case MinimumSpanningTree:
         return new CmdMinimumSpanningTree(kernel);
       case DelauneyTriangulation:
         return new CmdDelauneyTriangulation(kernel);
       case TravelingSalesman:
         return new CmdTravelingSalesman(kernel);
       case ShortestDistance:
         return new CmdShortestDistance(kernel);
       case Corner:
         return new CmdCorner(kernel);
       case AxisStepX:
         return new CmdAxisStepX(kernel);
       case AxisStepY:
         return new CmdAxisStepY(kernel);
       case ConstructionStep:
         return new CmdConstructionStep(kernel);
       case Object:
         return new CmdObject(kernel);
       case Name:
         return new CmdName(kernel);
       case SlowPlot:
         return new CmdSlowPlot(kernel);
       case ToolImage:
         return new CmdToolImage(kernel);
       case BarCode:
         return kernel.getApplication().newCmdBarCode();
       case DynamicCoordinates:
         return new CmdDynamicCoordinates(kernel);
       case Maximize:
         return new CmdMaximize(kernel);
       case Minimize:
         return new CmdMinimize(kernel);
       case Curve:
         return new CmdCurveCartesian(kernel);
       case FormulaText:
         return new CmdLaTeX(kernel);
       case IsDefined:
         return new CmdDefined(kernel);
       case ConjugateDiameter:
         return new CmdDiameter(kernel);
       case LinearEccentricity:
         return new CmdExcentricity(kernel);
       case MajorAxis:
         return new CmdFirstAxis(kernel);
       case SemiMajorAxisLength:
         return new CmdFirstAxisLength(kernel);
       case PerpendicularBisector:
         return new CmdLineBisector(kernel);
       case PerpendicularLine:
         return new CmdOrthogonalLine(kernel);
       case PerpendicularVector:
         return new CmdOrthogonalVector(kernel);
       case MinorAxis:
         return new CmdSecondAxis(kernel);
       case SemiMinorAxisLength:
         return new CmdSecondAxisLength(kernel);
       case UnitPerpendicularVector:
         return new CmdUnitOrthogonalVector(kernel);
       case CorrelationCoefficient:
         return new CmdPMCC(kernel);
       case FitLine:
         return new CmdFitLineY(kernel);
       case BinomialCoefficient:
         return new CmdBinomial(kernel);
       case RandomBetween:
         return new CmdRandom(kernel);
       default:
         AbstractApplication.debug("missing case in CommandDispatcher");
         return null;
     }
   } catch (Exception e) {
     AbstractApplication.debug("Warning: command not found / CAS command called:" + cmdName);
   }
   return null;
 }
Exemplo n.º 16
0
  private static GeoElement updateOldValue(
      Kernel kernel, GeoElement oldValue, String name, String text) throws Exception {
    String text0 = text;
    if (text.charAt(0) == '=') {
      text = text.substring(1);
    }
    GeoElement newValue = null;
    try {
      // always redefine objects in spreadsheet, don't store undo info
      // here
      newValue =
          kernel
              .getAlgebraProcessor()
              .changeGeoElementNoExceptionHandling(oldValue, text, true, false);

      // newValue.setConstructionDefaults();
      newValue.setAllVisualProperties(oldValue, true);
      if (oldValue.isAuxiliaryObject()) {
        newValue.setAuxiliaryObject(true);
      }

      // Application.debug("GeoClassType = " +
      // newValue.getGeoClassType()+" " + newValue.getGeoClassType());
      if (newValue.getGeoClassType() == oldValue.getGeoClassType()) {
        // newValue.setVisualStyle(oldValue);
      } else {
        kernel.getApplication().refreshViews();
      }
    } catch (CircularDefinitionException cde) {
      kernel.getApplication().showError("CircularDefinition");
      return null;
    } catch (Throwable e) {
      // if exception is thrown treat the input as text and try to update
      // the cell as a GeoText
      {
        // reset the text string if old value is GeoText
        if (oldValue.isGeoText()) {
          ((GeoText) oldValue).setTextString(text0);
          oldValue.updateCascade();
        }

        // if not currently a GeoText and no children, redefine the cell
        // as new GeoText
        else if (!oldValue.hasChildren()) {
          oldValue.remove();

          // add input as text
          try {
            newValue = prepareNewValue(kernel, name, "\"" + text0 + "\"");
          } catch (Throwable t) {
            newValue = prepareNewValue(kernel, name, "");
          }
          newValue.setEuclidianVisible(false);
          newValue.update();
        }

        // otherwise throw an exception and let the cell revert to the
        // old value
        else {
          throw new Exception(e);
        }
      }
    }
    return newValue;
  }
Exemplo n.º 17
0
  private static GeoElement prepareNewValue(Kernel kernel, String name, String inputText)
      throws Exception {
    String text = inputText;
    if (text == null) {
      return null;
    }

    // remove leading equal sign, e.g. "= A1 + A2"
    if (text.length() > 0 && text.charAt(0) == '=') {
      text = text.substring(1);
    }
    text = text.trim();

    // no equal sign in input
    GeoElement[] newValues = null;
    try {
      // check if input is same as name: circular definition
      if (text.equals(name)) {
        // circular definition
        throw new CircularDefinitionException();
      }

      // evaluate input text without an error dialog in case of unquoted
      // text
      newValues =
          kernel
              .getAlgebraProcessor()
              .processAlgebraCommandNoExceptionHandling(text, false, false, false);

      // check if text was the label of an existing geo
      // toUpperCase() added to fix bug A1=1, enter just 'a1' or 'A1' into
      // cell B1 -> A1 disappears
      if (StringUtil.toLowerCase(text).equals(newValues[0].getLabel(StringTemplate.defaultTemplate))
          // also need eg =a to work
          || text.equals(newValues[0].getLabel(StringTemplate.defaultTemplate))) {
        // make sure we create a copy of this existing or auto-created
        // geo
        // by providing the new cell name in the beginning
        text = name + " = " + text;
        newValues = kernel.getAlgebraProcessor().processAlgebraCommandNoExceptions(text, false);
      }

      // check if name was auto-created: if yes we could have a circular
      // definition
      GeoElement autoCreateGeo = kernel.lookupLabel(name);
      if (autoCreateGeo != null) {
        // check for circular definition: if newValue depends on
        // autoCreateGeo
        boolean circularDefinition = false;
        for (int i = 0; i < newValues.length; i++) {
          if (newValues[i].isChildOf(autoCreateGeo)) {
            circularDefinition = true;
            break;
          }
        }

        if (circularDefinition) {
          // remove the auto-created object and the result
          autoCreateGeo.remove();
          newValues[0].remove();

          // circular definition
          throw new CircularDefinitionException();
        }
      }

      for (int i = 0; i < newValues.length; i++) {
        newValues[i].setAuxiliaryObject(true);
        if (newValues[i].isGeoText()) {
          newValues[i].setEuclidianVisible(false);
        }
      }

      GeoElement.setLabels(name, newValues); // set names to be D1,
      // E1,
      // F1, etc for multiple
      // objects
    } catch (CircularDefinitionException ce) {
      // circular definition
      kernel.getApplication().showError("CircularDefinition");
      return null;
    } catch (Exception e) {
      // create text if something went wrong
      if (text.startsWith("\"")) text = text.substring(1, text.length() - 2);
      text = "\"" + (text.replace("\"", "\"+UnicodeToLetter[34]+\"")) + "\"";
      newValues = kernel.getAlgebraProcessor().processAlgebraCommandNoExceptions(text, false);
      newValues[0].setLabel(name);
      newValues[0].setEuclidianVisible(false);
      newValues[0].update();
    }
    return newValues[0];
  }
Exemplo n.º 18
0
 /**
  * Create a new text object
  *
  * @param text the text
  * @return new Geo text
  */
 public GeoText geoText(String text) {
   return kernel.getAlgebraProcessor().Text(null, text);
 }
Exemplo n.º 19
0
  public static GeoElement doCopyNoStoringUndoInfo0(
      Kernel kernel, App app, GeoElement value, GeoElement oldValue, int dx, int dy)
      throws Exception {
    if (value == null) {
      if (oldValue != null) {
        MatchResult matcher =
            GeoElementSpreadsheet.spreadsheetPatternPart.exec(
                oldValue.getLabel(StringTemplate.defaultTemplate));
        int column = GeoElementSpreadsheet.getSpreadsheetColumn(matcher);
        int row = GeoElementSpreadsheet.getSpreadsheetRow(matcher);

        prepareAddingValueToTableNoStoringUndoInfo(kernel, app, null, oldValue, column, row);
      }
      return null;
    }
    String text = null;

    // make sure a/0.001 doesn't become a/0

    StringTemplate highPrecision = StringTemplate.maxPrecision;
    if (value.isPointOnPath() || value.isPointInRegion()) {
      text = value.getCommandDescription(highPrecision);
    } else if (value.isChangeable()) {
      text = value.toValueString(highPrecision);
    } else {
      text = value.getCommandDescription(highPrecision);
    }

    // handle GeoText source value
    if (value.isGeoText() && !((GeoText) value).isTextCommand()) {
      // enclose text in quotes if we are copying an independent GeoText,
      // e.g. "2+3"
      if (value.isIndependent()) {
        text = "\"" + text + "\"";
      } else {

        // check if 'text' parses to a GeoText
        GeoText testGeoText = kernel.getAlgebraProcessor().evaluateToText(text, false, false);

        // if it doesn't then force it to by adding +"" on the end
        if (testGeoText == null) {
          text = text + "+\"\"";
        }
      }
    }

    // for E1 = Polynomial[D1] we need value.getCommandDescription();
    // even though it's a GeoFunction
    if (value.isGeoFunction() && text.equals("")) {
      // we need the definition without A1(x)= on the front
      text = ((GeoFunction) value).toSymbolicString(highPrecision);
    }

    boolean freeImage = false;

    if (value.isGeoImage()) {
      GeoImage image = (GeoImage) value;
      if (image.getParentAlgorithm() == null) {
        freeImage = true;
      }
    }

    // Application.debug("before:"+text);
    text = updateCellReferences(value, text, dx, dy);
    // Application.debug("after:"+text);

    // condition to show object
    GeoBoolean bool = value.getShowObjectCondition();
    String boolText = null, oldBoolText = null;
    if (bool != null) {
      if (bool.isChangeable()) {
        oldBoolText = bool.toValueString(highPrecision);
      } else {
        oldBoolText = bool.getCommandDescription(highPrecision);
      }
    }

    if (oldBoolText != null) {
      boolText = updateCellReferences(bool, oldBoolText, dx, dy);
    }

    String startPoints[] = null;
    if (value instanceof Locateable) {
      Locateable loc = (Locateable) value;

      GeoPointND[] pts = loc.getStartPoints();

      startPoints = new String[pts.length];

      for (int i = 0; i < pts.length; i++) {
        startPoints[i] = ((GeoElement) pts[i]).getLabel(highPrecision);
        startPoints[i] = updateCellReferences((GeoElement) pts[i], startPoints[i], dx, dy);
      }
    }

    // dynamic color function
    GeoList dynamicColorList = value.getColorFunction();
    String colorText = null, oldColorText = null;
    if (dynamicColorList != null) {
      if (dynamicColorList.isChangeable()) {
        oldColorText = dynamicColorList.toValueString(highPrecision);
      } else {
        oldColorText = dynamicColorList.getCommandDescription(highPrecision);
      }
    }

    if (oldColorText != null) {
      colorText = updateCellReferences(dynamicColorList, oldColorText, dx, dy);
    }

    // allow pasting blank strings
    if (text.equals("")) {
      text = "\"\"";
    }

    // make sure that non-GeoText elements are copied when the
    // equalsRequired option is set
    if (!value.isGeoText() && app.getSettings().getSpreadsheet().equalsRequired()) {
      text = "=" + text;
    }

    // Application.debug("add text = " + text + ", name = " + (char)('A' +
    // column + dx) + (row + dy + 1));

    // create the new cell geo
    MatchResult matcher =
        GeoElementSpreadsheet.spreadsheetPatternPart.exec(
            value.getLabel(StringTemplate.defaultTemplate));
    int column0 = GeoElementSpreadsheet.getSpreadsheetColumn(matcher);
    int row0 = GeoElementSpreadsheet.getSpreadsheetRow(matcher);
    GeoElement value2;
    if (freeImage || value.isGeoButton()) {
      value2 = value.copy();
      if (oldValue != null) {
        oldValue.remove();
      }
      // value2.setLabel(table.getModel().getColumnName(column0 + dx)
      //		+ (row0 + dy + 1));
      value2.setLabel(GeoElementSpreadsheet.getSpreadsheetCellName(column0 + dx, row0 + dy + 1));
      value2.updateRepaint();
    } else {
      value2 =
          prepareAddingValueToTableNoStoringUndoInfo(
              kernel, app, text, oldValue, column0 + dx, row0 + dy);
    }
    value2.setAllVisualProperties(value, false);

    value2.setAuxiliaryObject(true);

    // attempt to set updated condition to show object (if it's changed)
    if ((boolText != null)) {
      // removed as doesn't work for eg "random()<0.5" #388
      // && !boolText.equals(oldBoolText)) {
      try {
        // Application.debug("new condition to show object: "+boolText);
        GeoBoolean newConditionToShowObject =
            kernel.getAlgebraProcessor().evaluateToBoolean(boolText);
        value2.setShowObjectCondition(newConditionToShowObject);
        value2.update(); // needed to hide/show object as appropriate
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }

    // attempt to set updated dynamic color function (if it's changed)
    if ((colorText != null)) {
      // removed as doesn't work for eg "random()" #388
      // && !colorText.equals(oldColorText)) {
      try {
        // Application.debug("new color function: "+colorText);
        GeoList newColorFunction = kernel.getAlgebraProcessor().evaluateToList(colorText);
        value2.setColorFunction(newColorFunction);
        // value2.update();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }

    if (startPoints != null) {
      for (int i = 0; i < startPoints.length; i++) {
        ((Locateable) value2)
            .setStartPoint(
                kernel.getAlgebraProcessor().evaluateToPoint(startPoints[i], false, true), i);
      }

      value2.update();
    }

    // Application.debug((row + dy) + "," + column);
    // Application.debug("isGeoFunction()=" + value2.isGeoFunction());
    // Application.debug("row0 ="+row0+" dy="+dy+" column0= "+column0+" dx="+dx);

    return value2;
  }
  public void onMouseUp(MouseUpEvent e) {

    GPoint p = table.getIndexFromPixel(e.getClientX(), e.getClientY());
    if (p.getY() == 0 && p.getX() > 0) {
      if (table.isEditing()) editor.cancelCellEditing();
      table.scc.onMouseUp(e);
      return;
    } else if (p.getX() == 0 && p.getY() > 0) {
      if (table.isEditing()) editor.cancelCellEditing();
      table.srh.onMouseUp(e);
      return;
    }

    mouseIsDown = false;
    e.preventDefault();
    boolean eConsumed = false;

    boolean rightClick = (e.getNativeButton() == NativeEvent.BUTTON_RIGHT);

    if (table.getTableMode() == MyTable.TABLE_MODE_AUTOFUNCTION) {
      table.stopAutoFunction();
      return;
    }

    if (!rightClick) {
      if (editor.isEditing()) {
        String text = editor.getEditingValue();
        if (text.startsWith("=")) {
          GPoint point = table.getIndexFromPixel(e.getClientX(), e.getClientY());
          if (point != null) {
            int column = point.getX();
            int row = point.getY();
            if (column != editor.column || row != editor.row) {
              eConsumed = true;
            }
          }
        }
        selectedCellName = null;
        prefix0 = null;
        postfix0 = null;
        table.isDragging2 = false;
        table.repaint();
      }

      if (table.isOverDot) {
        // prevent UI manager from changing selection when mouse
        // is in a neighbor cell but is still over the dot region
        eConsumed = true;
      }

      if (table.isDragingDot) {
        if (table.dragingToColumn == -1 || table.dragingToRow == -1) return;
        int x1 = -1;
        int y1 = -1;
        int x2 = -1;
        int y2 = -1;
        // -|1|-
        // 2|-|3
        // -|4|-
        if (table.dragingToColumn < table.minSelectionColumn) { // 2
          x1 = table.dragingToColumn;
          y1 = table.minSelectionRow;
          x2 = table.minSelectionColumn - 1;
          y2 = table.maxSelectionRow;
        } else if (table.dragingToRow > table.maxSelectionRow) { // 4
          x1 = table.minSelectionColumn;
          y1 = table.maxSelectionRow + 1;
          x2 = table.maxSelectionColumn;
          y2 = table.dragingToRow;
        } else if (table.dragingToRow < table.minSelectionRow) { // 1
          x1 = table.minSelectionColumn;
          y1 = table.dragingToRow;
          x2 = table.maxSelectionColumn;
          y2 = table.minSelectionRow - 1;
        } else if (table.dragingToColumn > table.maxSelectionColumn) { // 3
          x1 = table.maxSelectionColumn + 1;
          y1 = table.minSelectionRow;
          x2 = table.dragingToColumn;
          y2 = table.maxSelectionRow;
        }

        // copy the cells
        boolean succ =
            relativeCopy.doDragCopy(
                table.minSelectionColumn - 1,
                table.minSelectionRow - 1,
                table.maxSelectionColumn - 1,
                table.maxSelectionRow - 1,
                x1 - 1,
                y1 - 1,
                x2 - 1,
                y2 - 1);
        if (succ) {
          app.storeUndoInfo();
        }

        // extend the selection to include the drag copy selection
        table.setSelection(
            Math.min(x1, table.minSelectionColumn) - 1,
            Math.min(y1, table.minSelectionRow) - 1,
            Math.max(x2, table.maxSelectionColumn) - 1,
            Math.max(y2, table.maxSelectionRow) - 1);

        // reset flags and cursor
        table.isOverDot = false;
        table.isDragingDot = false;
        table.dragingToRow = -1;
        table.dragingToColumn = -1;
        // TODO//setTableCursor();

        // prevent UI manager from changing selection
        eConsumed = true;

        table.repaint();
      }
    }

    // Alt click: copy definition to input field
    if (!table.isEditing() && e.isAltKeyDown() && app.showAlgebraInput()) {
      int row = p.getY(); // table.rowAtPoint(e.getPoint());
      int col = p.getX(); // table.columnAtPoint(e.getPoint());
      GeoElement geo = (GeoElement) model.getValueAt(row - 1, col - 1);

      if (geo != null) {
        // F3 key: copy definition to input bar
        app.getGlobalKeyDispatcher().handleFunctionKeyForAlgebraInput(3, geo);
        return;
      }
    }

    // handle right click
    if (rightClick) {
      if (!((AppW) kernel.getApplication()).letShowPopupMenu()) return;

      // change selection if right click is outside current selection
      if (p.getY() < table.minSelectionRow
          || p.getY() > table.maxSelectionRow
          || p.getX() < table.minSelectionColumn
          || p.getX() > table.maxSelectionColumn) {
        // switch to cell selection mode

        if (table.getSelectionType() != MyTable.CELL_SELECT) {
          table.setSelectionType(MyTable.CELL_SELECT);
        }

        // now change the selection
        if (p.getX() > 0 && p.getY() > 0)
          table.changeSelection(p.getY() - 1, p.getX() - 1, false, false);
      }

      // create and show context menu
      /*TODO SpreadsheetContextMenu popupMenu = new SpreadsheetContextMenu(
      		table, e.isShiftDown());
      popupMenu.show(e.getComponent(), e.getX(), e.getY());*/
    }

    if (eConsumed) return;

    // MyTable's default listeners follow, they should be simulated in Web e.g. here

    // change selection if right click is outside current selection
    if (p.getY() != table.leadSelectionRow + 1 || p.getX() != table.leadSelectionColumn + 1) {
      // switch to cell selection mode

      if (p.getY() > 0 && p.getX() > 0) {

        if (table.getSelectionType() != MyTable.CELL_SELECT) {
          table.setSelectionType(MyTable.CELL_SELECT);
        }

        // now change the selection
        table.changeSelection(p.getY() - 1, p.getX() - 1, false, true);
        table.repaint();
      }
    }
  }
Exemplo n.º 21
0
 /**
  * Create a new PythonAPI instance
  *
  * @param app the running application instance
  */
 public PythonFlatAPI(AppD app) {
   this.app = app;
   this.kernel = app.getKernel();
   this.cons = kernel.getConstruction();
   this.algProcessor = kernel.getAlgebraProcessor();
 }
Exemplo n.º 22
0
 /**
  * Find a Geo with a given label
  *
  * @param label a GeoElement's label
  * @return the Geo with that label
  */
 public GeoElement lookupLabel(String label) {
   return kernel.lookupLabel(label);
 }
Exemplo n.º 23
0
 /**
  * Get the Python init script
  *
  * @return the Python init script
  */
 public String getInitScript() {
   return kernel.getLibraryPythonScript();
 }
Exemplo n.º 24
0
 /**
  * Create new polyline
  *
  * @param points the vertices of the polyline
  * @return new polyline
  */
 public GeoPolyLine geoPolyLine(GeoPointND[] points) {
   return (GeoPolyLine) kernel.PolyLine(null, points, false)[0];
 }
Exemplo n.º 25
0
 /**
  * Create new polygon
  *
  * @param points the vertices of the polygon
  * @return new polygon
  */
 public GeoPolygon geoPolygon(GeoPointND[] points) {
   return (GeoPolygon) kernel.Polygon(null, points)[0];
 }
Exemplo n.º 26
0
  /**
   * @param c Command to be executed
   * @param labelOutput specifies if output GeoElements of this command should get labels
   * @throws MyError in case command execution fails
   * @return Geos created by the command
   */
  public final GeoElement[] processCommand(Command c, boolean labelOutput) throws MyError {

    if (cmdTable == null) {
      initCmdTable();
    }

    // cmdName
    String cmdName = c.getName();
    CommandProcessor cmdProc;
    //
    //        // remove CAS variable prefix from command name if present
    //        cmdName = cmdName.replace(ExpressionNode.GGBCAS_VARIABLE_PREFIX, "");

    // MACRO: is there a macro with this command name?
    MacroInterface macro = kernel.getMacro(cmdName);
    if (macro != null) {
      c.setMacro(macro);
      cmdProc = macroProc;
    }
    // STANDARD CASE
    else {
      // get CommandProcessor object for command name from command table
      cmdProc = cmdTable.get(cmdName);

      if (cmdProc == null) {
        cmdProc = commandTableSwitch(cmdName);
        if (cmdProc != null) {
          cmdTable.put(cmdName, cmdProc);
        }
      }

      if (cmdProc == null && internalCmdTable != null) {
        // try internal command
        cmdProc = internalCmdTable.get(cmdName);
      }
    }

    if (cmdProc == null)
      throw new MyError(app, app.getError("UnknownCommand") + " : " + app.getCommand(c.getName()));

    // switch on macro mode to avoid labeling of output if desired
    boolean oldMacroMode = cons.isSuppressLabelsActive();
    if (!labelOutput) cons.setSuppressLabelCreation(true);

    GeoElement[] ret = null;
    try {
      ret = cmdProc.process(c);
    } catch (MyError e) {
      throw e;
    } catch (Exception e) {
      cons.setSuppressLabelCreation(oldMacroMode);
      e.printStackTrace();
      throw new MyError(app, app.getError("CAS.GeneralErrorMessage"));
    } finally {
      cons.setSuppressLabelCreation(oldMacroMode);
    }

    // remember macro command used:
    // this is needed when a single tool A[] is exported to find
    // all other tools that are needed for A[]
    if (macro != null) cons.addUsedMacro(macro);

    return ret;
  }
Exemplo n.º 27
0
 public RelativeCopy(Kernel kernel0) {
   kernel = kernel0;
   app = kernel.getApplication();
 }
Exemplo n.º 28
0
  /**
   * Performs spreadsheet drag-copy operation.
   *
   * @param sx1 source minimum column
   * @param sy1 source minimum row
   * @param sx2 source maximum column
   * @param sy2 source maximum row
   * @param dx1 destination minimum column
   * @param dy1 destination minimum row
   * @param dx2 destination maximum column
   * @param dy2 destination maximum row
   * @return
   */
  public boolean doDragCopy(
      int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) {
    // -|1|-
    // 2|-|3
    // -|4|-
    app.setWaitCursor();
    Construction cons = kernel.getConstruction();

    try {
      boolean success = false;

      // collect all redefine operations
      cons.startCollectingRedefineCalls();

      boolean patternOK = isPatternSource(new CellRange(app, sx1, sy1, sx2, sy2));

      // ==============================================
      // vertical drag
      // ==============================================
      if ((sx1 == dx1) && (sx2 == dx2)) {

        if (dy2 < sy1) { // 1 ----- drag up
          if (((sy1 + 1) == sy2) && patternOK) {
            // two row source, so drag copy a linear pattern
            for (int x = sx1; x <= sx2; ++x) {
              GeoElement v1 = getValue(app, x, sy1);
              GeoElement v2 = getValue(app, x, sy2);
              if ((v1 == null) || (v2 == null)) {
                continue;
              }
              for (int y = dy2; y >= dy1; --y) {
                GeoElement v3 = getValue(app, x, y + 2);
                GeoElement v4 = getValue(app, x, y + 1);
                String vs1 = v3.isGeoFunction() ? "(x)" : "";
                String vs2 = v4.isGeoFunction() ? "(x)" : "";
                String d0 = GeoElementSpreadsheet.getSpreadsheetCellName(x, y + 2) + vs1;
                String d1 = GeoElementSpreadsheet.getSpreadsheetCellName(x, y + 1) + vs2;
                String text = "=2*" + d1 + "-" + d0;
                doCopyNoStoringUndoInfo1(kernel, app, text, v4, x, y);
              }
            }
          } else { // not two row source, so drag-copy the first row
            // of the source
            doCopyVerticalNoStoringUndoInfo1(sx1, sx2, sy1, dy1, dy2);
          }
          success = true;
        } else if (dy1 > sy2) { // 4 ---- drag down
          if (((sy1 + 1) == sy2) && patternOK) {
            // two row source, so drag copy a linear pattern
            for (int x = sx1; x <= sx2; ++x) {
              GeoElement v1 = getValue(app, x, sy1);
              GeoElement v2 = getValue(app, x, sy2);
              if ((v1 == null) || (v2 == null)) {
                continue;
              }
              for (int y = dy1; y <= dy2; ++y) {
                GeoElement v3 = getValue(app, x, y - 2);
                GeoElement v4 = getValue(app, x, y - 1);
                String vs1 = v3.isGeoFunction() ? "(x)" : "";
                String vs2 = v4.isGeoFunction() ? "(x)" : "";
                String d0 = GeoElementSpreadsheet.getSpreadsheetCellName(x, y - 2) + vs1;
                String d1 = GeoElementSpreadsheet.getSpreadsheetCellName(x, y - 1) + vs2;
                String text = "=2*" + d1 + "-" + d0;
                doCopyNoStoringUndoInfo1(kernel, app, text, v4, x, y);
              }
            }
          } else {
            // not two row source, so drag-copy the last row of the
            // source
            doCopyVerticalNoStoringUndoInfo1(sx1, sx2, sy2, dy1, dy2);
          }
          success = true;
        }
      }

      // ==============================================
      // horizontal drag
      // ==============================================
      else if ((sy1 == dy1) && (sy2 == dy2)) {
        if (dx2 < sx1) { // 2 ---- drag left
          if (((sx1 + 1) == sx2) && patternOK) {
            // two column source, so drag copy a linear pattern
            for (int y = sy1; y <= sy2; ++y) {
              GeoElement v1 = getValue(app, sx1, y);
              GeoElement v2 = getValue(app, sx2, y);
              if ((v1 == null) || (v2 == null)) {
                continue;
              }
              for (int x = dx2; x >= dx1; --x) {
                GeoElement v3 = getValue(app, x + 2, y);
                GeoElement v4 = getValue(app, x + 1, y);
                String vs1 = v3.isGeoFunction() ? "(x)" : "";
                String vs2 = v4.isGeoFunction() ? "(x)" : "";
                String d0 = GeoElementSpreadsheet.getSpreadsheetCellName(x + 2, y) + vs1;
                String d1 = GeoElementSpreadsheet.getSpreadsheetCellName(x + 1, y) + vs2;
                String text = "=2*" + d1 + "-" + d0;
                doCopyNoStoringUndoInfo1(kernel, app, text, v4, x, y);
              }
            }
          } else {
            // not two column source, so drag-copy the first column
            // of the source
            doCopyHorizontalNoStoringUndoInfo1(sy1, sy2, sx1, dx1, dx2);
          }
          success = true;
        } else if (dx1 > sx2) { // 4 --- drag right
          if (((sx1 + 1) == sx2) && patternOK) {
            // two column source, so drag copy a linear pattern
            for (int y = sy1; y <= sy2; ++y) {
              GeoElement v1 = getValue(app, sx1, y);
              GeoElement v2 = getValue(app, sx2, y);
              if ((v1 == null) || (v2 == null)) {
                continue;
              }
              for (int x = dx1; x <= dx2; ++x) {
                GeoElement v3 = getValue(app, x - 2, y);
                GeoElement v4 = getValue(app, x - 1, y);
                String vs1 = v3.isGeoFunction() ? "(x)" : "";
                String vs2 = v4.isGeoFunction() ? "(x)" : "";
                String d0 = GeoElementSpreadsheet.getSpreadsheetCellName(x - 2, y) + vs1;
                String d1 = GeoElementSpreadsheet.getSpreadsheetCellName(x - 1, y) + vs2;
                String text = "=2*" + d1 + "-" + d0;
                doCopyNoStoringUndoInfo1(kernel, app, text, v4, x, y);
              }
            }
          } else {
            // not two column source, so drag-copy the last column
            // of the source
            doCopyHorizontalNoStoringUndoInfo1(sy1, sy2, sx2, dx1, dx2);
          }
          success = true;
        }
      }

      // now do all redefining and build new construction
      cons.processCollectedRedefineCalls();

      if (success) {
        return true;
      }

      String msg =
          "sx1 = " + sx1 + "\r\n" + "sy1 = " + sy1 + "\r\n" + "sx2 = " + sx2 + "\r\n" + "sy2 = "
              + sy2 + "\r\n" + "dx1 = " + dx1 + "\r\n" + "dy1 = " + dy1 + "\r\n" + "dx2 = " + dx2
              + "\r\n" + "dy2 = " + dy2 + "\r\n";
      throw new RuntimeException("Error from RelativeCopy.doCopy:\r\n" + msg);
    } catch (Exception ex) {
      // kernel.getApplication().showError(ex.getMessage());
      ex.printStackTrace();
      return false;
    } finally {
      cons.stopCollectingRedefineCalls();
      app.setDefaultCursor();
    }
  }
Exemplo n.º 29
0
 /**
  * Set the Python init script
  *
  * @param script the new Python init script
  */
 public void setInitScript(String script) {
   kernel.setLibraryPythonScript(script);
 }
Exemplo n.º 30
0
 private AlgoDispatcher getAlgoDispatcher() {
   return kernel.getAlgoDispatcher();
 }