public void animatorFinished(AnimatorEvent arg0) {
      animations--;
      if (animations == 0) {
        for (Iterator iter = getNewSizes().keySet().iterator(); iter.hasNext(); ) {
          JRDesignElement element = (JRDesignElement) iter.next();
          Rectangle rectangle = getNewSizes().get(element);
          element.setX(rectangle.x);
          element.setY(rectangle.y);
          element.setWidth(rectangle.width);
          element.setHeight(rectangle.height);

          // Calculate the best font height...
          if (element instanceof JRDesignTextElement) {
            JRStyledTextParser styledTextParser = JRStyledTextParser.getInstance();
            JRDesignTextElement dte = (JRDesignTextElement) element;
            dte.setFontSize(null);
            for (int i = dte.getFontSize() - 1; i > 1; --i) {
              String text = "test";

              // Convert the element in a print element...
              Map<Attribute, Object> attributes =
                  JRFontUtil.getAttributes(new HashMap(), dte, Locale.getDefault());

              JRStyledText styledText =
                  styledTextParser.getStyledText(
                      attributes,
                      text,
                      JRCommonText.MARKUP_STYLED_TEXT.equals(
                          dte
                              .getMarkup()), // FIXMEMARKUP only static styled text appears on
                                             // preview. no other markup
                      Locale.getDefault());

              JasperReportsContext context = IRLocalJasperReportsContext.getInstance();

              JRTextMeasurerUtil measurerUtil = JRTextMeasurerUtil.getInstance(context);
              JRTextMeasurer measurer = measurerUtil.createTextMeasurer(dte);
              JRMeasuredText measuredText = measurer.measure(styledText, 0, dte.getHeight(), true);

              if (measuredText.getTextHeight() > dte.getHeight()) {
                if (i > 1) {
                  dte.setFontSize(i);
                } else {
                  break;
                }
              } else {
                break;
              }
            }
          }
        }
      }
    }
  private void organizeCellElements(JRDesignCellContents cell, CrosstabObjectScene sc) {

    int cW = cell.getWidth();
    int cH = cell.getHeight();
    List children = cell.getChildren();
    int y = 0;
    if (children.size() == 0) return;
    int h = cH / children.size();

    SceneAnimator animator = new SceneAnimator(sc);
    CellAnimatorListener listener = new CellAnimatorListener();
    animator.getPreferredBoundsAnimator().addAnimatorListener(listener);
    animator.getPreferredLocationAnimator().addAnimatorListener(listener);
    listener.addAnimation(); // bounds
    listener.addAnimation(); // location

    // 1 Calculate new elements size and location..
    for (int i = 0; i < children.size(); ++i) {
      if (children.get(i) instanceof JRDesignElement) {
        JRDesignElement element = (JRDesignElement) children.get(i);
        listener.getNewSizes().put(element, new Rectangle(0, i * h, cW, h));
      }
    }

    for (Iterator iter = listener.getNewSizes().keySet().iterator(); iter.hasNext(); ) {
      JRDesignElement element = (JRDesignElement) iter.next();
      Rectangle rectangle = listener.getNewSizes().get(element);
      Widget w = sc.findWidget(element);

      if (w != null) {
        Rectangle r = w.getPreferredBounds();
        r.width = rectangle.width;
        r.height = rectangle.height;
        animator.animatePreferredBounds(w, r);

        Point p = new Point(w.getLocation());
        p.x -= element.getX() + rectangle.x;
        p.y += -(element.getY()) + rectangle.y;

        animator.animatePreferredLocation(w, p);
      }
    }
  }
 public Map<JRElement, Rectangle> layout(JRElement[] elements, Dimension c) {
   Map<JRElement, Rectangle> map = new HashMap<JRElement, Rectangle>();
   int x = 0;
   int y = 0;
   int w = c.width;
   int h = (int) Math.floor((float) c.height / elements.length);
   int rest = c.height - h * elements.length;
   for (JRElement el : elements) {
     JRDesignElement del = (JRDesignElement) el;
     map.put(el, new Rectangle(el.getX(), el.getY(), el.getWidth(), el.getHeight()));
     del.setX(x);
     del.setY(y);
     del.setWidth(w);
     del.setHeight(h + rest);
     // if last grab free pixels
     y += h + rest;
     if (rest > 0) rest = 0;
     LayoutManager.layout(map, el);
   }
   return map;
 }
  @Override
  protected void performAction(Node[] nodes) {

    if (nodes.length == 0) return;
    JasperDesign jd = nodes[0].getLookup().lookup(JasperDesign.class);
    if (jd == null) return;

    List<JRDesignElement> elements = getSelectedElements(nodes);

    boolean aggregate = false;
    for (JRDesignElement element : elements) {
      Rectangle oldBounds = getElementBounds(element);

      // 1. Find the parent...
      Rectangle rect = ModelUtils.getParentBounds(jd, element);
      int oldY = element.getY();
      element.setY((rect.height / 2) - (element.getHeight() / 2));

      aggregate = addTransformationUndo(element, oldBounds, aggregate);
    }
  }
  public Object getValue() throws IllegalAccessException, InvocationTargetException {

    JRPropertiesMap map = element.getPropertiesMap();
    List properties = new ArrayList();
    String[] names = map.getPropertyNames();

    for (int i = 0; i < names.length; ++i) {
      properties.add(new GenericProperty(names[i], map.getProperty(names[i])));
    }

    // add to the list the expression properties...
    JRPropertyExpression[] expProperties = element.getPropertyExpressions();
    for (int i = 0; expProperties != null && i < expProperties.length; ++i) {
      properties.add(
          new GenericProperty(
              expProperties[i].getName(),
              (JRDesignExpression) expProperties[i].getValueExpression()));
    }

    return properties;
  }
  public void updateBounds() {
    JasperDesign jd = ((AbstractReportObjectScene) this.getScene()).getJasperDesign();

    // Point p =
    // JRBand band = ModelUtils.bandOfElement(element, jd);
    // int bandYLocation = ModelUtils.getBandLocation(band, jd);
    // setPreferredLocation(new Point( jd.getLeftMargin() + element.getX()-5, bandYLocation +
    // element.getY() -5) );
    // setPreferredBounds(new Rectangle(0,0,element.getWidth()+10, element.getHeight()+10));

    Point location = convertModelToLocalLocation(new Point(element.getX(), element.getY()));
    location.x -= getBorder().getInsets().left;
    location.y -= getBorder().getInsets().top;
    setPreferredLocation(location);
    setPreferredBounds(
        new Rectangle(
            0,
            0,
            element.getWidth() + getBorder().getInsets().left + getBorder().getInsets().right,
            element.getHeight() + getBorder().getInsets().top + getBorder().getInsets().bottom));
  }
  public void setValue(Object val)
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // if (!(val instanceof JRPropertiesMap)) throw new IllegalArgumentException();

    if (!(val instanceof List)) throw new IllegalArgumentException();

    // Fill this map with the content of the map we got here...

    // 1. Create the map...
    JRPropertiesMap map = new JRPropertiesMap();
    List values = (List) val;
    for (int i = 0; i < values.size(); ++i) {
      GenericProperty prop = (GenericProperty) values.get(i);
      if (!prop.isUseExpression()) {
        map.setProperty(prop.getKey(), (String) prop.getValue());
      }
    }

    ModelUtils.replacePropertiesMap(map, element.getPropertiesMap());
    ModelUtils.replaceExpressionProperties(element, values);

    com.jaspersoft.ireport.designer.IReportManager.getInstance().notifyReportChange();
  }
 @Override
 public void setStyle(JRStyle s) {
   element.setStyle(s);
 }
 @Override
 public JRStyle getStyle() {
   return element.getStyle();
 }
 @Override
 public void setStyleNameReference(String s) {
   element.setStyleNameReference(s);
 }
 @Override
 public String getStyleNameReference() {
   return element.getStyleNameReference();
 }
  public JRDesignElementWidget(AbstractReportObjectScene scene, JRDesignElement element) {
    super(scene);
    this.element = element;
    setBorder(new SimpleLineBorder(this));
    updateBounds();

    try {
      if (crosstabImage == null)
        crosstabImage =
            new javax.swing.ImageIcon(
                getClass()
                    .getResource("/com/jaspersoft/ireport/designer/resources/crosstab-32.png"));
      if (subreportImage == null)
        subreportImage =
            new javax.swing.ImageIcon(
                getClass()
                    .getResource("/com/jaspersoft/ireport/designer/resources/subreport-32.png"));
      if (multiaxisImage == null)
        multiaxisImage =
            new javax.swing.ImageIcon(
                getClass()
                    .getResource("/com/jaspersoft/ireport/designer/resources/chartaxis-32.png"));
      if (genericElementImage == null)
        genericElementImage =
            new javax.swing.ImageIcon(
                getClass()
                    .getResource(
                        "/com/jaspersoft/ireport/designer/resources/genericelement-48.png"));
    } catch (Exception ex) {
    }

    selectionWidget = new SelectionWidget(scene, this);
    notifyStateChanged(null, ObjectState.createNormal());
    selectionWidget.addDependency(
        new Dependency() {

          public void revalidateDependency() {
            // setPreferredLocation(selectionWidget.getPreferredLocation() );
            // setPreferredBounds(selectionWidget.getPreferredBounds());
            // System.out.println("Revaludated");
          }
        });

    element.getEventSupport().addPropertyChangeListener(this);

    if (element instanceof JRDesignGraphicElement) {
      JRDesignGraphicElement gele = (JRDesignGraphicElement) element;
      ((JRBasePen) gele.getLinePen()).getEventSupport().addPropertyChangeListener(this);
    }

    if (element instanceof JRBoxContainer) {
      JRBoxContainer boxcontainer = (JRBoxContainer) element;
      JRBaseLineBox baseBox = (JRBaseLineBox) boxcontainer.getLineBox();
      baseBox.getEventSupport().addPropertyChangeListener(this);
      ((JRBasePen) baseBox.getPen()).getEventSupport().addPropertyChangeListener(this);
      ((JRBasePen) baseBox.getTopPen()).getEventSupport().addPropertyChangeListener(this);
      ((JRBasePen) baseBox.getBottomPen()).getEventSupport().addPropertyChangeListener(this);
      ((JRBasePen) baseBox.getLeftPen()).getEventSupport().addPropertyChangeListener(this);
      ((JRBasePen) baseBox.getRightPen()).getEventSupport().addPropertyChangeListener(this);
    }

    if (element instanceof JRDesignTextElement) {
      ((JRBaseParagraph) ((JRDesignTextElement) element).getParagraph())
          .getEventSupport()
          .addPropertyChangeListener(this);
    }
  }
  protected void paintWidgetImplementation() {

    super.paintWidget();
    Graphics2D gr = getScene().getGraphics();

    // Java2DUtils.setClip(gr,getClientArea());
    // Move the gfx 10 pixel ahead...
    Rectangle r = getPreferredBounds();

    long t = new Date().getTime();
    // if (getElement() instanceof JRDesignImage) return;

    AffineTransform af = gr.getTransform();
    AffineTransform new_af = (AffineTransform) af.clone();
    AffineTransform translate =
        AffineTransform.getTranslateInstance(
            getBorder().getInsets().left + r.x, getBorder().getInsets().top + r.y);
    new_af.concatenate(translate);
    gr.setTransform(new_af);

    JasperDesign jd = ((AbstractReportObjectScene) this.getScene()).getJasperDesign();
    JRDesignElement e = this.getElement();
    DrawVisitor dv = ((AbstractReportObjectScene) this.getScene()).getDrawVisitor();
    if (dv == null) return;

    if (e instanceof JRDesignCrosstab) {
      Composite oldComposite = gr.getComposite();
      gr.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
      try {
        e.visit(dv);
      } catch (Exception ex) {
      }
      gr.setComposite(oldComposite);
      Shape oldClip = gr.getClip();
      Shape rect = new Rectangle2D.Float(0, 0, element.getWidth(), element.getHeight());

      gr.clip(rect);
      gr.drawImage(crosstabImage.getImage(), 4, 4, null);
      gr.setClip(oldClip);
    }
    //        if (e instanceof JRDesignFrame)
    //        {
    //            Composite oldComposite = gr.getComposite();
    //            gr.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    //            //try {
    //            //    e.visit( dv );
    //            //} catch (Exception ex){}
    //            gr.setComposite(oldComposite);
    //            Shape oldClip = gr.getClip();
    //            Shape rect = new Rectangle2D.Float(0,0,element.getWidth(), element.getHeight());
    //
    //        }
    else if (e instanceof JRDesignSubreport) {
      Composite oldComposite = gr.getComposite();
      gr.fillRect(0, 0, element.getWidth(), element.getHeight());
      gr.setComposite(oldComposite);
      Shape oldClip = gr.getClip();
      Shape rect = new Rectangle2D.Float(0, 0, element.getWidth(), element.getHeight());
      gr.clip(rect);
      gr.drawImage(subreportImage.getImage(), 4, 4, null);
      gr.setClip(oldClip);
    } else if (e instanceof JRDesignGenericElement) {
      // Composite oldComposite = gr.getComposite();
      Paint oldPaint = gr.getPaint();
      gr.setPaint(new Color(196, 200, 162, 64));
      gr.fillRect(0, 0, element.getWidth(), element.getHeight());
      gr.setPaint(oldPaint);
      // gr.setComposite(oldComposite);
      Shape oldClip = gr.getClip();
      Shape rect = new Rectangle2D.Float(0, 0, element.getWidth(), element.getHeight());
      gr.clip(rect);
      gr.drawImage(genericElementImage.getImage(), 4, 4, null);
      gr.setClip(oldClip);
    } else if (e instanceof JRDesignChart) {

      if (((JRDesignChart) e).getChartType() == JRDesignChart.CHART_TYPE_MULTI_AXIS) {
        Composite oldComposite = gr.getComposite();

        gr.fillRect(0, 0, element.getWidth(), element.getHeight());
        gr.setComposite(oldComposite);
        Shape oldClip = gr.getClip();
        Shape rect = new Rectangle2D.Float(0, 0, element.getWidth(), element.getHeight());
        gr.clip(rect);
        gr.drawImage(multiaxisImage.getImage(), 4, 4, null);
        gr.setClip(oldClip);
      } else {
        ClassLoader oldCL = null;

        dv.setGraphics2D(gr);
        oldCL = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(IReportManager.getJRExtensionsClassLoader());

        try {
          e.visit(dv);
        } catch (Exception ex) {

          System.err.println(
              "iReport - Element rendering exception " + getElement() + " " + ex.getMessage());
          // ex.printStackTrace();
        }

        if (oldCL != null) {
          Thread.currentThread().setContextClassLoader(oldCL);
        }
      }
    } else {
      dv.setGraphics2D(gr);
      try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(IReportManager.getJRExtensionsClassLoader());
        e.visit(dv);
        Thread.currentThread().setContextClassLoader(cl);
      } catch (Exception ex) {

        System.err.println(
            "iReport - Element rendering exception " + getElement() + " " + ex.getMessage());
        // ex.printStackTrace();
      }
    }

    // show the element and parent coordinates...
    /*
    Point p = getParentElementModelLocation();
    gr.setColor(Color.darkGray);
    gr.setFont(new Font("SansSerif",0,6));
    gr.drawString( getElement().getX() + "," + getElement().getY() + " - " + p.x + "," + p.y, 2, 12);
    */
    //
    gr.setTransform(af);
    // Java2DUtils.resetClip(gr);

    // System.out.println("Painted : " + (t - new Date().getTime()) + "   " + getElement());
  }