Example usage for java.awt.geom Rectangle2D getWidth

List of usage examples for java.awt.geom Rectangle2D getWidth

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D getWidth.

Prototype

public abstract double getWidth();

Source Link

Document

Returns the width of the framing rectangle in double precision.

Usage

From source file:org.forester.archaeopteryx.TreePanel.java

final private int paintTaxonomy(final Graphics2D g, final PhylogenyNode node, final boolean is_in_found_nodes,
        final boolean to_pdf, final boolean to_graphics_file) {
    final Taxonomy taxonomy = node.getNodeData().getTaxonomy();
    g.setFont(getTreeFontSet().getLargeItalicFont());
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);//from  w ww  . j  a  v  a  2  s .c om
    } else if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeItalicFont().deriveFont(TreeFontSet.BOLD_AND_ITALIC));
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getTaxonomyColor());
    }
    final double start_x = node.getXcoord() + 3 + TreePanel.HALF_BOX_SIZE;
    final double start_y = node.getYcoord()
            + (getTreeFontSet()._fm_large.getAscent() / (node.getNumberOfDescendants() == 1 ? 1 : 3.0));
    _sb.setLength(0);
    if (_control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty(taxonomy.getTaxonomyCode())) {
        _sb.append(taxonomy.getTaxonomyCode());
        _sb.append(" ");
    }
    if (_control_panel.isShowTaxonomyNames()) {
        if (!ForesterUtil.isEmpty(taxonomy.getScientificName())
                && !ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" (");
            _sb.append(taxonomy.getCommonName());
            _sb.append(") ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getScientificName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getCommonName());
            _sb.append(" ");
        }
    }
    final String label = _sb.toString();
    /* GUILHEM_BEG */
    if ((label.length() > 0) && (node.getNodeData().isHasSequence())
            && node.getNodeData().getSequence().equals(_query_sequence)) {
        // invert font color and background color to show that this is the query sequence
        final Rectangle2D nodeTextBounds = new TextLayout(label, g.getFont(),
                new FontRenderContext(null, false, false)).getBounds();
        g.fillRect((int) start_x - 1, (int) start_y - 8, (int) nodeTextBounds.getWidth() + 4, 11);
        g.setColor(getTreeColorSet().getBackgroundColor());
    }
    /* GUILHEM_END */
    TreePanel.drawString(label, start_x, start_y, g);
    if (is_in_found_nodes) {
        return getTreeFontSet()._fm_large_italic_bold.stringWidth(label);
    } else {
        return getTreeFontSet()._fm_large_italic.stringWidth(label);
    }
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private void paintNodeData(final Graphics2D g, final PhylogenyNode node, final boolean to_graphics_file,
        final boolean to_pdf, final boolean is_in_found_nodes) {
    if (isNodeDataInvisible(node) && !to_graphics_file && !to_pdf) {
        return;/*from ww w .  j av a2  s.c o  m*/
    }
    if (getOptions().isShowBranchLengthValues()
            && ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE))
            && (!node.isRoot()) && (node.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT)) {
        paintBranchLength(g, node, to_pdf, to_graphics_file);
    }
    if (!getControlPanel().isShowInternalData() && !node.isExternal() && !node.isCollapse()) {
        return;
    }
    int x = 0;
    if (node.getNodeData().isHasTaxonomy()
            && (getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyNames())) {
        x = paintTaxonomy(g, node, is_in_found_nodes, to_pdf, to_graphics_file);
    }
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);
    } else if (is_in_found_nodes) {
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getSequenceColor());
    }
    _sb.setLength(0);
    if (node.isCollapse() && ((!node.isRoot() && !node.getParent().isCollapse()) || node.isRoot())) {
        _sb.append(" [");
        _sb.append(node.getAllExternalDescendants().size());
        _sb.append("]");
    }
    if (getControlPanel().isShowNodeNames() && (node.getNodeName().length() > 0)) {
        if (_sb.length() > 0) {
            _sb.append(" ");
        }
        _sb.append(node.getNodeName());
    }
    if (node.getNodeData().isHasSequence()) {
        if (getControlPanel().isShowGeneSymbols()
                && (node.getNodeData().getSequence().getSymbol().length() > 0)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            _sb.append(node.getNodeData().getSequence().getSymbol());
        }
        if (getControlPanel().isShowGeneNames() && (node.getNodeData().getSequence().getName().length() > 0)) {
            //                if ( _sb.length() > 0 ) {
            //                    _sb.append( " " );
            //                }
            //                _sb.append( node.getNodeData().getSequence().getName() );
            PhylogenyNode parent = node.getParent();
            double x1 = parent.getXcoord();
            double y1 = parent.getYcoord();
            double x2 = node.getXcoord();
            double y2 = node.getYcoord();
            double above_the_line = 1.0;

            if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = Math.abs(y1 + y2) / 2.0;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0 + EURO_D;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            }

        }
        if (getControlPanel().isShowSequenceAcc()
                && (node.getNodeData().getSequence().getAccession() != null)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            if (!ForesterUtil.isEmpty(node.getNodeData().getSequence().getAccession().getSource())) {
                _sb.append(node.getNodeData().getSequence().getAccession().getSource());
                _sb.append(":");
            }
            _sb.append(node.getNodeData().getSequence().getAccession().getValue());
        }
    }
    g.setFont(getTreeFontSet().getLargeFont());
    if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeFont().deriveFont(Font.BOLD));
    }
    double down_shift_factor = 3.0;
    if (!node.isExternal() && (node.getNumberOfDescendants() == 1)) {
        down_shift_factor = 1;
    }
    // GUILHEM_BEG ______________
    final double posX = node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE;
    final double posY = (node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor));
    final int CONFIDENCE_LEFT_MARGIN = 4;
    final String sNodeText = _sb.toString();
    if (_control_panel.isShowSequenceRelations() && node.getNodeData().isHasSequence()
            && (_query_sequence != null)) {
        int nodeTextBoundsWidth = 0;
        if (sNodeText.length() > 0) {
            final Rectangle2D node_text_bounds = new TextLayout(sNodeText, g.getFont(), _frc).getBounds(); //would like to remove this 'new', but how...
            nodeTextBoundsWidth = (int) node_text_bounds.getWidth();
        }
        if (node.getNodeData().getSequence().equals(_query_sequence)) {
            if (nodeTextBoundsWidth > 0) { // invert font color and background color to show that this is the query sequence
                g.fillRect((int) posX - 1, (int) posY - 8, nodeTextBoundsWidth + 5, 11);
                g.setColor(getTreeColorSet().getBackgroundColor());
            }
        } else {
            final List<SequenceRelation> seqRelations = node.getNodeData().getSequence().getSequenceRelations();
            for (final SequenceRelation seqRelation : seqRelations) {
                final boolean fGotRelationWithQuery = (seqRelation.getRef0().isEqual(_query_sequence)
                        || seqRelation.getRef1().isEqual(_query_sequence))
                        && seqRelation.getType()
                                .equals(getControlPanel().getSequenceRelationTypeBox().getSelectedItem());
                if (fGotRelationWithQuery) { // we will underline the text to show that this sequence is ortholog to the query
                    final double linePosX = node.getXcoord() + 2 + TreePanel.HALF_BOX_SIZE;
                    final String sConfidence = (!getControlPanel().isShowSequenceRelationConfidence()
                            || (seqRelation.getConfidence() == null)) ? null
                                    : " (" + seqRelation.getConfidence().getValue() + ")";
                    if (sConfidence != null) {
                        double confidenceX = posX;
                        if (sNodeText.length() > 0) {
                            confidenceX += new TextLayout(sNodeText, g.getFont(), _frc).getBounds().getWidth()
                                    + CONFIDENCE_LEFT_MARGIN;
                        }
                        if (confidenceX > linePosX) { // let's only display confidence value if we are already displaying at least one of Prot/Gene Name and Taxonomy Code 
                            final int confidenceWidth = (int) new TextLayout(sConfidence, g.getFont(), _frc)
                                    .getBounds().getWidth();
                            TreePanel.drawString(sConfidence, confidenceX, posY, g);
                            x += CONFIDENCE_LEFT_MARGIN + confidenceWidth;
                        }
                    }
                    if (x + nodeTextBoundsWidth > 0) /* we only underline if there is something displayed */
                    {
                        if (nodeTextBoundsWidth == 0) {
                            nodeTextBoundsWidth -= 3; /* the gap between taxonomy code and node name should not be underlined if nothing comes after it */
                        } else {
                            nodeTextBoundsWidth += 2;
                        }
                        g.drawLine((int) linePosX + 1, 3 + (int) posY, (int) linePosX + x + nodeTextBoundsWidth,
                                3 + (int) posY);
                        break;
                    }
                }
            }
        }
    }
    if (sNodeText.length() > 0) {
        TreePanel.drawString(sNodeText, posX, posY, g);
    }
    // GUILHEM_END _____________
    // COMMENTED_OUT_BY_GUILHEM_BEG _______________
    // TODO FIXME need to check this one!
    //if ( _sb.length() > 0 ) {
    //    TreePanel.drawString( _sb.toString(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord()
    //            + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
    //}
    // COMMENTED_OUT_BY_GUILHEM_END ________________
    if (getControlPanel().isShowAnnotation() && node.getNodeData().isHasSequence()
            && (node.getNodeData().getSequence().getAnnotations() != null)
            && (!node.getNodeData().getSequence().getAnnotations().isEmpty())) {
        if (_sb.length() > 0) {
            x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
        }
        final Annotation ann = (Annotation) node.getNodeData().getSequence().getAnnotations().get(0);
        if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
            g.setColor(Color.BLACK);
        } else {
            g.setColor(calculateColorForAnnotation(ann));
        }
        final String ann_str = ann.asSimpleText().toString();
        TreePanel.drawString(ann_str, node.getXcoord() + x + 3 + TreePanel.HALF_BOX_SIZE,
                node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
        _sb.setLength(0);
        _sb.append(ann_str);
    }
    if ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)) {
        if ((getControlPanel().isShowBinaryCharacters() || getControlPanel().isShowBinaryCharacterCounts())
                && node.getNodeData().isHasBinaryCharacters()) {
            if (_sb.length() > 0) {
                x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
            }
            if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
                g.setColor(Color.BLACK);
            } else {
                g.setColor(getTreeColorSet().getBinaryDomainCombinationsColor());
            }
            if (getControlPanel().isShowBinaryCharacters()) {
                TreePanel.drawString(
                        node.getNodeData().getBinaryCharacters().getPresentCharactersAsStringBuffer()
                                .toString(),
                        node.getXcoord() + x + 1 + TreePanel.HALF_BOX_SIZE,
                        node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                paintGainedAndLostCharacters(g, node,
                        node.getNodeData().getBinaryCharacters().getGainedCharactersAsStringBuffer().toString(),
                        node.getNodeData().getBinaryCharacters().getLostCharactersAsStringBuffer().toString());
            } else {
                if (DRAW_MEAN_COUNTS && node.isInternal()) {
                    final List<PhylogenyNode> ec = node.getAllExternalDescendants();
                    double sum = 0;
                    int count = 0;
                    for (final PhylogenyNode phylogenyNode : ec) {
                        count++;
                        if (phylogenyNode.getNodeData().getBinaryCharacters() != null) {
                            sum += phylogenyNode.getNodeData().getBinaryCharacters().getPresentCount();
                        }
                    }
                    final double mean = ForesterUtil.round(sum / count, 1);
                    TreePanel.drawString(
                            node.getNodeData().getBinaryCharacters().getPresentCount() + " [" + mean + "]",
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                } else {
                    TreePanel.drawString(node.getNodeData().getBinaryCharacters().getPresentCount(),
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                }
                paintGainedAndLostCharacters(g, node,
                        "+" + node.getNodeData().getBinaryCharacters().getGainedCount(),
                        "-" + node.getNodeData().getBinaryCharacters().getLostCount());
            }
        }
    }
}

From source file:gda.plots.SimplePlot.java

/**
 * Recalculates the rectangle which should be magnified.
 * /*from w ww  .j a v a2s .  c o m*/
 * @param e
 *            the MouseEvent which triggered the recalculation
 */
private void recalculateMagnifyRectangle(MouseEvent e) {
    if (magnifyWidth == 0 || magnifyHeight == 0)
        return;

    Rectangle2D scaledDataArea = getScreenDataArea();

    double widthToUse;
    double heightToUse;
    double xToUse;
    double yToUse;

    // If magnifyWidth is positive then e.getX() is
    // the end of the rectangle so the start is (e.getX() - magnifyWidth ).
    // If magnifyWidth is negative then e.getX() is the start of a
    // rectangle with the opposite sign width. Similarly for y.

    if (magnifyWidth > 0) {
        xToUse = e.getX() - magnifyWidth;
        widthToUse = magnifyWidth;
    } else {
        xToUse = e.getX();
        widthToUse = -1.0 * magnifyWidth;
    }

    if (magnifyHeight > 0) {
        yToUse = e.getY() - magnifyHeight;
        heightToUse = magnifyHeight;
    } else {
        yToUse = e.getY();
        heightToUse = -1.0 * magnifyHeight;
    }

    // xToUse and yToUse now specify the top left of the rectangle. In order
    // to keep the magnified rectangle inside the data area the start point
    // must be inside a rectangle which is the scaledDataArea reduced in
    // width
    // and height by the width and height of the magnifyRectangle.

    Point2D revisedStartPoint = ShapeUtilities.getPointInRectangle(xToUse, yToUse,
            new Rectangle2D.Double(scaledDataArea.getMinX(), scaledDataArea.getMinY(),
                    scaledDataArea.getWidth() - magnifyWidth, scaledDataArea.getHeight() - magnifyHeight));
    magnifyRectangle = new Rectangle2D.Double(revisedStartPoint.getX(), revisedStartPoint.getY(), widthToUse,
            heightToUse);
}

From source file:ucar.unidata.idv.control.chart.MyXYPlot.java

/**
 * A utility method for drawing the axes.
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param plotArea  the plot area (<code>null</code> not permitted).
 * @param dataArea  the data area (<code>null</code> not permitted).
 * @param plotState  collects information about the plot (<code>null</code>
 *                   permitted).//from w  w w  . j av  a 2  s  .com
 *
 * @return A map containing the state for each axis drawn.
 */
protected Map drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) {

    AxisCollection axisCollection = new AxisCollection();

    // add domain axes to lists...
    for (int index = 0; index < this.domainAxes.size(); index++) {
        ValueAxis axis = (ValueAxis) this.domainAxes.get(index);
        if (axis != null) {
            axisCollection.add(axis, getDomainAxisEdge(index));
        }
    }

    // add range axes to lists...
    for (int index = 0; index < this.rangeAxes.size(); index++) {
        ValueAxis yAxis = (ValueAxis) this.rangeAxes.get(index);
        if (yAxis != null) {
            axisCollection.add(yAxis, getRangeAxisEdge(index));
        }
    }

    Map axisStateMap = new HashMap();

    // draw the top axes
    double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(dataArea.getHeight());
    Iterator iterator = axisCollection.getAxesAtTop().iterator();
    while (iterator.hasNext()) {
        ValueAxis axis = (ValueAxis) iterator.next();
        AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState);
        cursor = info.getCursor();
        axisStateMap.put(axis, info);
    }

    // draw the bottom axes
    cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight());
    iterator = axisCollection.getAxesAtBottom().iterator();
    while (iterator.hasNext()) {
        ValueAxis axis = (ValueAxis) iterator.next();
        AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState);
        cursor = info.getCursor();
        axisStateMap.put(axis, info);
    }

    // draw the left axes
    cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth());
    iterator = axisCollection.getAxesAtLeft().iterator();
    while (iterator.hasNext()) {
        ValueAxis axis = (ValueAxis) iterator.next();
        AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState);
        cursor = info.getCursor();
        axisStateMap.put(axis, info);
    }

    // draw the right axes
    cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth());
    iterator = axisCollection.getAxesAtRight().iterator();
    while (iterator.hasNext()) {
        ValueAxis axis = (ValueAxis) iterator.next();
        AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState);
        cursor = info.getCursor();
        axisStateMap.put(axis, info);
    }

    return axisStateMap;
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * Process the lat/lon labels tag//from   w w w  . j a v a 2 s .co  m
 *
 * @param child  the XML
 * @param viewManager  the associated view manager
 * @param image  the image to draw on
 * @param imageProps  the image properties
 *
 * @return  a new image
 *
 * @throws Exception  on badness
 */
public BufferedImage doLatLonLabels(Element child, ViewManager viewManager, BufferedImage image,
        Hashtable imageProps) throws Exception {

    if (viewManager == null) {
        throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a view");
    }
    if (!(viewManager instanceof MapViewManager)) {
        throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a map view");
    }
    MapViewManager mvm = (MapViewManager) viewManager;
    NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster();
    DecimalFormat format = new DecimalFormat(applyMacros(child, ATTR_FORMAT, "##0.0"));
    Color color = applyMacros(child, ATTR_COLOR, Color.red);
    Color lineColor = applyMacros(child, ATTR_LINECOLOR, color);
    Color bg = applyMacros(child, ATTR_LABELBACKGROUND, (Color) null);

    double[] latValues = Misc.parseDoubles(applyMacros(child, ATTR_LAT_VALUES, ""));
    List<String> latLabels = StringUtil.split(applyMacros(child, ATTR_LAT_LABELS, ""), ",", true, true);
    double[] lonValues = Misc.parseDoubles(applyMacros(child, ATTR_LON_VALUES, ""));
    List<String> lonLabels = StringUtil.split(applyMacros(child, ATTR_LON_LABELS, ""), ",", true, true);

    boolean drawLonLines = applyMacros(child, ATTR_DRAWLONLINES, false);
    boolean drawLatLines = applyMacros(child, ATTR_DRAWLATLINES, false);
    boolean showTop = applyMacros(child, ATTR_SHOWTOP, false);
    boolean showBottom = applyMacros(child, ATTR_SHOWBOTTOM, true);
    boolean showLeft = applyMacros(child, ATTR_SHOWLEFT, true);
    boolean showRight = applyMacros(child, ATTR_SHOWRIGHT, false);

    int width = image.getWidth(null);
    int height = image.getHeight(null);
    int centerX = width / 2;
    int centerY = height / 2;
    EarthLocation nw, ne, se, sw;

    //don: this  what I added
    Double north = (Double) imageProps.get(ATTR_NORTH);
    Double south = (Double) imageProps.get(ATTR_SOUTH);
    Double east = (Double) imageProps.get(ATTR_EAST);
    Double west = (Double) imageProps.get(ATTR_WEST);
    //Assume if we have one we have them all
    if (north != null) {
        nw = DisplayControlImpl.makeEarthLocation(north.doubleValue(), west.doubleValue(), 0);

        ne = DisplayControlImpl.makeEarthLocation(north.doubleValue(), east.doubleValue(), 0);
        sw = DisplayControlImpl.makeEarthLocation(south.doubleValue(), west.doubleValue(), 0);
        se = DisplayControlImpl.makeEarthLocation(south.doubleValue(), east.doubleValue(), 0);

    } else {
        nw = display.screenToEarthLocation(0, 0);
        ne = display.screenToEarthLocation(width, 0);
        se = display.screenToEarthLocation(0, height);
        sw = display.screenToEarthLocation(width, height);
    }

    double widthDegrees = ne.getLongitude().getValue() - nw.getLongitude().getValue();
    double heightDegrees = ne.getLatitude().getValue() - se.getLatitude().getValue();

    Insets insets = getInsets(child, 0);
    int delta = 2;
    int bgPad = 1;

    image = doMatte(image, child, 0);

    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setFont(getFont(child));
    FontMetrics fm = g.getFontMetrics();

    int lineOffsetRight = applyMacros(child, ATTR_LINEOFFSET_RIGHT, 0);
    int lineOffsetLeft = applyMacros(child, ATTR_LINEOFFSET_LEFT, 0);
    int lineOffsetTop = applyMacros(child, ATTR_LINEOFFSET_TOP, 0);
    int lineOffsetBottom = applyMacros(child, ATTR_LINEOFFSET_BOTTOM, 0);

    Stroke lineStroke;
    if (XmlUtil.hasAttribute(child, ATTR_DASHES)) {
        lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0), BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 1.0f, Misc.parseFloats(applyMacros(child, ATTR_DASHES, "8")), 0.0f);
    } else {
        lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0));
    }

    g.setStroke(lineStroke);
    double leftLon = nw.getLongitude().getValue(CommonUnit.degree);
    double rightLon = ne.getLongitude().getValue(CommonUnit.degree);
    Range lonRange = new Range(leftLon, rightLon);

    for (int i = 0; i < lonValues.length; i++) {
        double lon = GeoUtils.normalizeLongitude(lonRange, lonValues[i]);
        double percent = (lon - nw.getLongitude().getValue()) / widthDegrees;
        //            if(percent<0 || percent>1) continue;
        String label;
        if (i < lonLabels.size()) {
            label = lonLabels.get(i);
        } else {
            label = format.format(lonValues[i]);
        }
        Rectangle2D rect = fm.getStringBounds(label, g);
        int baseX = insets.left + (int) (percent * width);
        int x = baseX - (int) rect.getWidth() / 2;
        int topY;
        if (insets.top == 0) {
            topY = (int) rect.getHeight() + delta;
        } else {
            topY = insets.top - delta;
        }
        if (drawLonLines) {
            g.setColor(lineColor);
            g.drawLine(baseX, insets.top + lineOffsetTop, baseX, insets.top + height - lineOffsetBottom);
        }

        if (showTop) {
            if (bg != null) {
                g.setColor(bg);
                g.fillRect(x - bgPad, topY - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2,
                        (int) rect.getHeight() + bgPad * 2);
            }
            g.setColor(color);
            g.drawString(label, x, topY);
        }
        int bottomY;
        if (insets.bottom == 0) {
            bottomY = insets.top + height - delta;
        } else {
            bottomY = insets.top + height + (int) rect.getHeight() + delta;
        }
        if (showBottom) {
            if (bg != null) {
                g.setColor(bg);
                g.fillRect(x - bgPad, bottomY - (int) rect.getHeight() - bgPad,
                        (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2);
            }
            g.setColor(color);
            g.drawString(label, x, bottomY);
        }
    }

    for (int i = 0; i < latValues.length; i++) {
        double lat = latValues[i];
        double percent = 1.0 - (lat - se.getLatitude().getValue()) / heightDegrees;
        int baseY = insets.top + (int) (percent * height);
        //            if(percent<0 || percent>1) continue;
        String label;
        if (i < latLabels.size()) {
            label = latLabels.get(i);
        } else {
            label = format.format(lat);
        }
        Rectangle2D rect = fm.getStringBounds(label, g);
        int y = baseY + (int) rect.getHeight() / 2;
        int leftX;
        if (insets.left == 0) {
            leftX = 0 + delta;
        } else {
            leftX = insets.left - (int) rect.getWidth() - delta;
        }
        if (drawLonLines) {
            g.setColor(lineColor);
            g.drawLine(insets.left + lineOffsetRight, baseY, insets.left + width - lineOffsetRight, baseY);
        }

        if (showLeft) {
            if (bg != null) {
                g.setColor(bg);
                g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2,
                        (int) rect.getHeight() + bgPad * 2);
            }
            g.setColor(color);
            g.drawString(label, leftX, y);
        }

        if (insets.right == 0) {
            leftX = insets.left + width - (int) rect.getWidth() - delta;
        } else {
            leftX = insets.left + width + delta;
        }
        if (showRight) {
            if (bg != null) {
                g.setColor(bg);
                g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2,
                        (int) rect.getHeight() + bgPad * 2);
            }
            g.setColor(color);
            g.drawString(label, leftX, y);
        }
    }

    return image;

}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * Process the image// w w  w.  j  av  a 2  s  . c  o m
 *
 * @param image The image
 * @param filename File to write the image to
 * @param node Node to process
 * @param props Extra properties
 * @param viewManager The viewmanager this image came from
 * @param imageProps  the image properties
 *
 *
 * @return The processed image
 * @throws Throwable On badness
 */
protected BufferedImage processImage(BufferedImage image, String filename, Element node, Hashtable props,
        ViewManager viewManager, Hashtable imageProps) throws Throwable {

    if (node == null) {
        return image;
    }

    if (props == null) {
        props = new Hashtable();
    }
    if (viewManager != null) {
        Animation animation = viewManager.getAnimation();
        props.put(PROP_ANIMATIONTIME, "");
        if (animation != null) {
            if (animation.getAniValue() != null) {
                props.put(PROP_ANIMATIONTIME, animation.getAniValue());
            }
        }
    }
    getProperties().putAll(props);

    NodeList elements = XmlUtil.getElements(node);
    Hashtable seenColorTable = new Hashtable();
    for (int childIdx = 0; childIdx < elements.getLength(); childIdx++) {
        boolean shouldIterateChildren = true;
        BufferedImage newImage = null;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        Element child = (Element) elements.item(childIdx);
        String tagName = child.getTagName();

        if (tagName.equals(TAG_RESIZE)) {
            newImage = ImageUtils.toBufferedImage(resize(image, child));
        } else if (tagName.equals(TAG_FILESET)) {
            //ignore
        } else if (tagName.equals(TAG_OUTPUT)) {
            processTagOutput(child);
        } else if (tagName.equals(TAG_DISPLAYLIST)) {
            if (viewManager != null) {
                newImage = ImageUtils.toBufferedImage(image, true);
                Graphics g = newImage.getGraphics();
                String valign = applyMacros(child, ATTR_VALIGN, VALUE_BOTTOM);
                Font font = getFont(child);
                if (XmlUtil.hasAttribute(child, ATTR_MATTEBG)) {
                    int height = viewManager.paintDisplayList((Graphics2D) g, null, imageWidth, imageHeight,
                            valign.equals(VALUE_BOTTOM), null, font);

                    int top = (valign.equals(VALUE_TOP) ? height : 0);
                    int bottom = (valign.equals(VALUE_BOTTOM) ? height : 0);
                    newImage = ImageUtils.matte(image, top, bottom, 0, 0,
                            applyMacros(child, ATTR_MATTEBG, Color.white));
                    g = newImage.getGraphics();
                    imageHeight += height;
                }

                Color c = applyMacros(child, ATTR_COLOR, (Color) null);
                viewManager.paintDisplayList((Graphics2D) g, null, imageWidth, imageHeight,
                        valign.equals(VALUE_BOTTOM), c, font);
            }
        } else if (tagName.equals(TAG_COLORBAR) || tagName.equals(TAG_KML_COLORBAR)) {
            // only do one colorbar if we are writing to kml
            Integer index = (Integer) props.get(PROP_IMAGEINDEX);
            if ((index != null) && (index.intValue() > 0) && tagName.equals(TAG_KML_COLORBAR)) {
                continue;
            }

            boolean showLines = applyMacros(child, ATTR_SHOWLINES, false);

            List<DisplayControlImpl> controls = (List<DisplayControlImpl>) ((viewManager != null)
                    ? viewManager.getControls()
                    : new ArrayList());

            if (XmlUtil.hasAttribute(child, ATTR_DISPLAY)) {
                DisplayControlImpl display = ((controls.size() > 0)
                        ? findDisplayControl(XmlUtil.getAttribute(child, ATTR_DISPLAY), controls)
                        : findDisplayControl(child));
                if (display == null) {
                    error("Could not find display:" + XmlUtil.toString(node));
                    return null;
                }
                controls = Misc.newList(display);
            }

            int width = applyMacros(child, ATTR_WIDTH, 150);
            int height = applyMacros(child, ATTR_HEIGHT, 20);
            int ticks = applyMacros(child, ATTR_TICKMARKS, 0);
            double interval = applyMacros(child, ATTR_INTERVAL, -1.0);
            String valuesStr = applyMacros(child, ATTR_VALUES, (String) null);
            Color c = applyMacros(child, ATTR_COLOR, Color.black);

            Color lineColor = applyMacros(child, ATTR_LINECOLOR, c);

            Rectangle imageRect = new Rectangle(0, 0, imageWidth, imageHeight);

            Point pp = ImageUtils.parsePoint(applyMacros(child, ATTR_PLACE, "ll,10,-10"), imageRect);
            Point ap = ImageUtils.parsePoint(applyMacros(child, ATTR_ANCHOR, "ll"),
                    new Rectangle(0, 0, width, height));

            String orientation = applyMacros(child, ATTR_ORIENTATION, VALUE_BOTTOM);
            boolean vertical = orientation.equals(VALUE_RIGHT) || orientation.equals(VALUE_LEFT);
            int baseY = pp.y - ap.y + (vertical ? 0 : height);
            int baseX = pp.x - ap.x;

            List colorTables = new ArrayList();
            List ranges = new ArrayList();
            List units = new ArrayList();

            boolean forKml = tagName.equals(TAG_KML_COLORBAR);

            for (int i = 0; i < controls.size(); i++) {
                DisplayControlImpl control = (DisplayControlImpl) controls.get(i);
                ColorTable colorTable = control.getColorTable();
                if (colorTable == null) {
                    continue;
                }
                Range range = control.getRangeForColorTable();
                //only do unique color tables
                Object[] key = { colorTable, range };
                if (seenColorTable.get(key) != null) {
                    continue;
                }
                seenColorTable.put(key, key);
                colorTables.add(colorTable);
                ranges.add(range);
                units.add(control.getDisplayUnit());
            }

            for (int i = 0; i < colorTables.size(); i++) {
                ColorTable colorTable = (ColorTable) colorTables.get(i);
                Range range = (Range) ranges.get(i);
                Unit unit = (Unit) units.get(i);
                Image imageToDrawIn;
                if (forKml) {
                    if (vertical) {
                        baseX = 0;
                        baseY = 0;
                    } else {
                        baseX = 0;
                        baseY = height;
                    }
                    int space = applyMacros(child, ATTR_SPACE, (vertical ? width : height));
                    imageToDrawIn = new BufferedImage(width + (vertical ? space : 0),
                            height + (vertical ? 0 : space), BufferedImage.TYPE_INT_RGB);
                } else {
                    imageToDrawIn = newImage = ImageUtils.toBufferedImage(image);
                }
                Graphics g = imageToDrawIn.getGraphics();
                if (forKml) {
                    Color bgColor = applyMacros(child, ATTR_BACKGROUND, Color.white);
                    g.setColor(bgColor);
                    g.fillRect(0, 0, imageToDrawIn.getWidth(null), imageToDrawIn.getHeight(null));
                }
                boolean includeAlpha = applyMacros(child, ATTR_TRANSPARENCY, true);

                float[][] ctValues;

                if (includeAlpha) {
                    ctValues = colorTable.getAlphaTable();
                } else {
                    ctValues = colorTable.getNonAlphaTable();
                }
                ColorMap colorMap = new BaseRGBMap(ctValues);
                ColorPreview preview = new ColorPreview(colorMap, (vertical ? width : height));
                if (vertical) {
                    preview.setSize(new Dimension(height, width));
                } else {
                    preview.setSize(new Dimension(width, height));
                }
                Image previewImage = ColorTableCanvas.getImage(colorTable, (vertical ? height : width),
                        (vertical ? width : height), includeAlpha);

                if (vertical) {
                    int imageType = includeAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;

                    BufferedImage tmpImage = new BufferedImage(width, height, imageType);

                    Graphics2D tmpG = (Graphics2D) tmpImage.getGraphics();
                    tmpG.rotate(Math.toRadians(90.0));
                    tmpG.drawImage(previewImage, 0, 0 - width, null);
                    previewImage = tmpImage;
                }
                if (forKml) {
                    g.drawImage(previewImage, 0, 0, null);
                } else {
                    g.drawImage(previewImage, baseX, (vertical ? baseY : baseY - height), null);
                }
                if (showLines) {
                    g.setColor(lineColor);
                    g.drawRect(baseX, (vertical ? baseY : baseY - height), width - 1,
                            height - (vertical ? 1 : 0));
                }
                setFont(g, child);
                FontMetrics fm = g.getFontMetrics();
                List values = new ArrayList();
                String suffixFrequency = XmlUtil.getAttribute(child, ATTR_SUFFIXFREQUENCY,
                        XmlUtil.getAttribute(child, ATTR_SHOWUNIT, "false")).toLowerCase();
                String unitDefault = (!suffixFrequency.equals("false")) ? " %unit%" : "";
                String labelSuffix = applyMacros(child, ATTR_SUFFIX, unitDefault);
                if (unit != null) {
                    labelSuffix = labelSuffix.replace("%unit%", "" + unit);
                } else {
                    labelSuffix = labelSuffix.replace("%unit%", "");
                }
                if (valuesStr != null) {
                    double[] valueArray = Misc.parseDoubles(valuesStr, ",");
                    for (int valueIdx = 0; valueIdx < valueArray.length; valueIdx++) {
                        values.add(new Double(valueArray[valueIdx]));
                    }
                } else if (ticks > 0) {
                    int spacing = ((ticks == 1) ? 0 : (vertical ? height : width) / (ticks - 1));
                    for (int tickIdx = 0; tickIdx < ticks; tickIdx++) {
                        double percent = ((ticks > 1) ? (double) tickIdx / (double) (ticks - 1) : 0.0);
                        values.add(new Double(range.getValueOfPercent(percent)));
                    }
                } else if (interval > 0) {
                    double value = range.getMin();
                    double max = range.getMax();
                    while (value <= max) {
                        values.add(new Double(value));
                        value += interval;
                    }
                }
                for (int valueIdx = 0; valueIdx < values.size(); valueIdx++) {
                    double value = ((Double) values.get(valueIdx)).doubleValue();
                    int x;
                    int y;
                    if (vertical) {
                        if (orientation.equals(VALUE_RIGHT)) {
                            x = baseX + width;
                        } else {
                            x = baseX;
                        }
                        y = baseY + (int) (range.getPercent(value) * height);
                        if (y > baseY + height) {
                            break;
                        }
                    } else {
                        if (orientation.equals(VALUE_BOTTOM)) {
                            y = baseY;
                        } else {
                            y = baseY - height;
                        }

                        if (range != null) {
                            x = baseX + (int) (range.getPercent(value) * width);
                        } else {
                            x = baseX;
                        }

                        if (x > baseX + width) {
                            break;
                        }
                    }
                    String tickLabel = getIdv().getDisplayConventions().format(value);
                    if (suffixFrequency.equals(VALUE_LAST) && (valueIdx == values.size() - 1)) {
                        tickLabel += labelSuffix;
                    } else if (suffixFrequency.equals(VALUE_FIRST) && (valueIdx == 0)) {
                        tickLabel += labelSuffix;
                    } else if (suffixFrequency.equals(VALUE_ALL) || suffixFrequency.equals("true")) {
                        tickLabel += labelSuffix;
                    }

                    Rectangle2D rect = fm.getStringBounds(tickLabel, g);
                    g.setColor(lineColor);
                    if (orientation.equals(VALUE_RIGHT)) {
                        g.drawLine(x + 1, y, x, y);
                        if (showLines) {
                            g.drawLine(x, y, x - width, y);
                        }
                    } else if (orientation.equals(VALUE_LEFT)) {
                        g.drawLine(x - 1, y, x, y);
                        if (showLines) {
                            g.drawLine(x, y, x + width, y);
                        }
                    } else if (orientation.equals(VALUE_BOTTOM)) {
                        g.drawLine(x, y + 1, x, y);
                        if (showLines) {
                            g.drawLine(x, y, x, y - height);
                        }
                    } else {
                        g.drawLine(x, y - 1, x, y);
                        if (showLines) {
                            g.drawLine(x, y, x, y + height);
                        }
                    }
                    g.setColor(c);
                    if (orientation.equals(VALUE_RIGHT)) {
                        int yLoc = y + (int) (rect.getHeight() / 2) - 2;
                        if (forKml) {
                            if (valueIdx == 0) {
                                yLoc = y + (int) (rect.getHeight()) - 2;
                            } else if (valueIdx == values.size() - 1) {
                                yLoc = y - (int) (rect.getHeight()) + 6;
                            }
                        }
                        g.drawString(tickLabel, x + 2, yLoc);
                    } else if (orientation.equals(VALUE_LEFT)) {
                        int xLoc = x - 2 - (int) rect.getWidth();
                        g.drawString(tickLabel, xLoc, y + (int) (rect.getHeight() / 2) - 2);
                    } else if (orientation.equals(VALUE_BOTTOM)) {
                        int xLoc = x - (int) (rect.getWidth() / 2);
                        if (forKml) {
                            if (valueIdx == 0) {
                                xLoc = x + 2;
                            } else if (valueIdx == values.size() - 1) {
                                xLoc = x - (int) rect.getWidth() + 2;
                            }
                        }
                        g.drawString(tickLabel, xLoc, y + (int) rect.getHeight() + 2);
                    } else {
                        g.drawString(tickLabel, x - (int) (rect.getWidth() / 2), y - 2);
                    }
                }
                if (vertical) {
                    baseX += width + 30;
                } else {
                    baseY += height + 30;
                }
                if (forKml) {
                    String tmpImageFile = applyMacros(child, ATTR_FILE,
                            getIdv().getStore().getTmpFile("testcolorbar${viewindex}.png"));
                    String template = "<ScreenOverlay><name>${kml.name}</name><Icon><href>${icon}</href></Icon>\n"
                            + "<overlayXY x=\"${kml.overlayXY.x}\" y=\"${kml.overlayXY.y}\" xunits=\"${kml.overlayXY.xunits}\" yunits=\"${kml.overlayXY.yunits}\"/>\n"
                            + "<screenXY x=\"${kml.screenXY.x}\" y=\"${kml.screenXY.y}\" xunits=\"${kml.screenXY.xunits}\" yunits=\"${kml.screenXY.yunits}\"/>\n"
                            + "<size x=\"${kml.size.x}\" y=\"${kml.size.y}\" xunits=\"${kml.size.xunits}\" yunits=\"${kml.size.yunits}\"/>\n"
                            + "</ScreenOverlay>\n";
                    String[] macros = { "kml.name", "kml.overlayXY.x", "kml.overlayXY.y",
                            "kml.overlayXY.xunits", "kml.overlayXY.yunits", "kml.screenXY.x", "kml.screenXY.y",
                            "kml.screenXY.xunits", "kml.screenXY.yunits", "kml.size.x", "kml.size.y",
                            "kml.size.xunits", "kml.size.yunits" };
                    String[] macroValues = { "", "0", "1", "fraction", "fraction", "0", "1", "fraction",
                            "fraction", "-1", "-1", "pixels", "pixels" };

                    for (int macroIdx = 0; macroIdx < macros.length; macroIdx++) {
                        template = template.replace("${" + macros[macroIdx] + "}",
                                applyMacros(child, macros[macroIdx], macroValues[macroIdx]));
                    }
                    template = template.replace("${icon}", IOUtil.getFileTail(tmpImageFile));
                    imageProps.put("kml", template);
                    List kmlFiles = (List) imageProps.get("kmlfiles");
                    //TODO: Only do the first one for now
                    if (kmlFiles == null) {
                        kmlFiles = new ArrayList();
                        imageProps.put("kmlfiles", kmlFiles);
                    }
                    kmlFiles.add(tmpImageFile);

                    //                        System.out.println(template);
                    ImageUtils.writeImageToFile(imageToDrawIn, tmpImageFile);
                }
            }

        } else if (tagName.equals(TAG_TRANSPARENT) || tagName.equals(TAG_BGTRANSPARENT)) {
            Color c = null;
            if (tagName.equals(TAG_BGTRANSPARENT)) {
                c = viewManager.getBackground();
            } else {
                c = applyMacros(child, ATTR_COLOR, (Color) null);
            }
            //                System.err.println ("c:" + c);
            int[] redRange = { 0, 0 };
            int[] greenRange = { 0, 0 };
            int[] blueRange = { 0, 0 };
            if (c != null) {
                //                    System.err.println("got color");
                redRange[0] = redRange[1] = c.getRed();
                greenRange[0] = greenRange[1] = c.getGreen();
                blueRange[0] = blueRange[1] = c.getBlue();
            } else {
            }
            newImage = ImageUtils.makeColorTransparent(image, redRange, greenRange, blueRange);
        } else if (tagName.equals(TAG_SHOW)) {
            JComponent contents = new JLabel(new ImageIcon(image));
            String message = applyMacros(child, ATTR_MESSAGE, (String) null);
            if (message != null) {
                contents = GuiUtils.topCenter(new JLabel(message), contents);
            }
            if (!GuiUtils.askOkCancel("Continue?", contents)) {
                throw new MyQuitException();
            }
        } else if (tagName.equals(TAG_MATTE)) {
            newImage = doMatte(image, child, 0);
        } else if (tagName.equals(TAG_LATLONLABELS)) {
            newImage = doLatLonLabels(child, viewManager, image, imageProps);
        } else if (tagName.equals(TAG_WRITE)) {
            ImageUtils.writeImageToFile(image, getImageFileName(applyMacros(child, ATTR_FILE)));

        } else if (tagName.equals(TAG_PUBLISH)) {
            getIdv().getPublishManager().publishIslImage(this, node, image);
        } else if (tagName.equals(TAG_CLIP)) {
            int[] ul;
            int[] lr;
            if (XmlUtil.hasAttribute(child, ATTR_DISPLAY)) {
                //                    System.err.println("Clipping from display");
                DisplayControlImpl dc = findDisplayControl(child);
                if (dc == null) {
                    throw new IllegalArgumentException("Could not find display:" + XmlUtil.toString(node));
                }
                NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster();
                MapProjection mapProjection = dc.getDataProjection();
                java.awt.geom.Rectangle2D rect = mapProjection.getDefaultMapArea();
                LatLonPoint llplr = mapProjection.getLatLon(new double[][] { { rect.getX() + rect.getWidth() },
                        { rect.getY() + rect.getHeight() } });
                LatLonPoint llpul = mapProjection
                        .getLatLon(new double[][] { { rect.getX() }, { rect.getY() } });
                EarthLocation ulEl = new EarthLocationTuple(llpul, new Real(RealType.Altitude, 0));
                EarthLocation lrEl = new EarthLocationTuple(llplr, new Real(RealType.Altitude, 0));
                ul = display.getScreenCoordinates(display.getSpatialCoordinates(ulEl, null));
                lr = display.getScreenCoordinates(display.getSpatialCoordinates(lrEl, null));
                //System.err.println("ul:" + ulEl + " lr:" + lrEl);
                if (ul[0] > lr[0]) {
                    int tmp = ul[0];
                    ul[0] = lr[0];
                    lr[0] = tmp;
                }
                if (ul[1] > lr[1]) {
                    int tmp = ul[1];
                    ul[1] = lr[1];
                    lr[1] = tmp;
                }
                imageProps.put(ATTR_NORTH, new Double(ulEl.getLatitude().getValue()));
                imageProps.put(ATTR_WEST, new Double(ulEl.getLongitude().getValue()));
                imageProps.put(ATTR_SOUTH, new Double(lrEl.getLatitude().getValue()));
                imageProps.put(ATTR_EAST, new Double(lrEl.getLongitude().getValue()));
            } else if ((viewManager != null) && XmlUtil.hasAttribute(child, ATTR_NORTH)) {
                NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster();
                EarthLocation el1 = DisplayControlImpl.makeEarthLocation(toDouble(child, ATTR_NORTH),
                        toDouble(child, ATTR_WEST), 0);
                EarthLocation el2 = DisplayControlImpl.makeEarthLocation(toDouble(child, ATTR_SOUTH),
                        toDouble(child, ATTR_EAST), 0);
                ul = display.getScreenCoordinates(display.getSpatialCoordinates(el1, null));
                lr = display.getScreenCoordinates(display.getSpatialCoordinates(el2, null));
                imageProps.put(ATTR_NORTH, new Double(el1.getLatitude().getValue()));
                imageProps.put(ATTR_WEST, new Double(el1.getLongitude().getValue()));
                imageProps.put(ATTR_SOUTH, new Double(el2.getLatitude().getValue()));
                imageProps.put(ATTR_EAST, new Double(el2.getLongitude().getValue()));
            } else if (XmlUtil.hasAttribute(child, ATTR_LEFT)) {
                ul = new int[] { (int) toDouble(child, ATTR_LEFT, imageWidth),
                        (int) toDouble(child, ATTR_TOP, imageHeight) };
                lr = new int[] { (int) toDouble(child, ATTR_RIGHT, imageWidth),
                        (int) toDouble(child, ATTR_BOTTOM, imageHeight) };
            } else if (viewManager != null) {
                //TODO: Clip on visad coordinates
                NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster();
                ul = display.getScreenCoordinates(new double[] { -1, 1, 0 });
                lr = display.getScreenCoordinates(new double[] { 1, -1, 0 });
                int space = applyMacros(child, ATTR_SPACE, 0);
                int hspace = applyMacros(child, ATTR_HSPACE, space);
                int vspace = applyMacros(child, ATTR_VSPACE, space);
                ul[0] -= applyMacros(child, ATTR_SPACE_LEFT, hspace);
                ul[1] -= applyMacros(child, ATTR_SPACE_TOP, vspace);
                lr[0] += applyMacros(child, ATTR_SPACE_RIGHT, hspace);
                lr[1] += applyMacros(child, ATTR_SPACE_BOTTOM, vspace);
            } else {
                continue;
            }

            for (String attr : (List<String>) Misc.newList(ATTR_NORTH, ATTR_SOUTH, ATTR_EAST, ATTR_WEST)) {
                String kmlAttr = "kml." + attr;
                if (XmlUtil.hasAttribute(child, kmlAttr)) {
                    imageProps.put(attr, new Double(applyMacros(child, kmlAttr, 0.0)));
                }
            }

            ul[0] = Math.max(0, ul[0]);
            ul[1] = Math.max(0, ul[1]);

            lr[0] = Math.min(lr[0], imageWidth);
            lr[1] = Math.min(lr[1], imageHeight);

            newImage = ImageUtils.clip(image, ul, lr);
        } else if (tagName.equals(TAG_SPLIT)) {
            shouldIterateChildren = false;
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            int cols = applyMacros(child, ATTR_COLUMNS, 2);
            int rows = applyMacros(child, ATTR_ROWS, 2);
            String file = applyMacros(child, ATTR_FILE);
            int cnt = 0;
            int hSpace = width / cols;
            int vSpace = height / rows;
            for (int row = 0; row < rows; row++) {
                for (int col = 0; col < cols; col++) {
                    pushProperties();
                    Hashtable myprops = new Hashtable();
                    putProperty("row", new Integer(row));
                    putProperty("column", new Integer(col));
                    putProperty("count", new Integer(++cnt));
                    String realFile = applyMacros(file, myprops);
                    Image splitImage = image.getSubimage(hSpace * col, vSpace * row, hSpace, vSpace);
                    processImage(ImageUtils.toBufferedImage(splitImage), realFile, child, myprops, viewManager,
                            new Hashtable());
                    popProperties();
                }
            }
        } else if (tagName.equals(TAG_THUMBNAIL)) {
            shouldIterateChildren = false;
            BufferedImage thumbImage = ImageUtils.toBufferedImage(resize(image, child));
            String thumbFile = applyMacros(child, ATTR_FILE, (String) null);
            if (thumbFile == null) {
                thumbFile = IOUtil.stripExtension(filename) + "_thumb" + IOUtil.getFileExtension(filename);
            }
            processImage(thumbImage, thumbFile, child, null, viewManager, new Hashtable());
        } else if (tagName.equals(TAG_KML)) {
            //NOOP
        } else if (tagName.equals(TAG_KMZFILE)) {
            //NOOP
        } else if (tagName.equals(TAG_OVERLAY)) {
            double transparency = applyMacros(child, ATTR_TRANSPARENCY, 0.0);
            Graphics2D g = image.createGraphics();
            String imagePath = applyMacros(child, ATTR_IMAGE, (String) null);

            float scale = (float) applyMacros(child, ATTR_SCALE, 1.0);

            Rectangle imageRect = new Rectangle(0, 0, imageWidth, imageHeight);
            Point pp = ImageUtils.parsePoint(applyMacros(child, ATTR_PLACE, "lr,-10,-10"), imageRect);
            String text = applyMacros(child, ATTR_TEXT, (String) null);
            Color bg = applyMacros(child, ATTR_BACKGROUND, (Color) null);
            if (text != null) {
                double angle = Math.toRadians(applyMacros(child, ATTR_ANGLE, 0.0));
                text = applyMacros(text);
                Color c = applyMacros(child, ATTR_COLOR, Color.white);
                if ((c != null) && (transparency > 0)) {
                    c = new Color(c.getRed(), c.getGreen(), c.getBlue(), ImageUtils.toAlpha(transparency));
                }
                //Color bg = applyMacros(child, ATTR_BACKGROUND,
                //                       (Color) null);
                if ((bg != null) && (transparency > 0)) {
                    bg = new Color(bg.getRed(), bg.getGreen(), bg.getBlue(), ImageUtils.toAlpha(transparency));
                }
                setFont(g, child);
                FontMetrics fm = g.getFontMetrics();
                Rectangle2D rect = fm.getStringBounds(text, g);
                int width = (int) rect.getWidth();
                int height = (int) (rect.getHeight());

                Point ap = ImageUtils.parsePoint(applyMacros(child, ATTR_ANCHOR, "lr,-10,-10"),
                        new Rectangle(0, 0, width, height));

                g.rotate(angle);

                if (bg != null) {
                    g.setColor(bg);
                    g.fillRect(pp.x - ap.x - 1, pp.y - ap.y - 1, (int) width + 2, (int) height + 2);
                }
                g.setColor(c);
                g.drawString(text, pp.x - ap.x, pp.y - ap.y + height);
            }

            if (imagePath != null) {
                Image overlay = ImageUtils.readImage(imagePath);
                if (overlay != null) {
                    if (transparency > 0) {
                        overlay = ImageUtils.setAlpha(overlay, transparency);
                    }

                    int width = overlay.getWidth(null);
                    int height = overlay.getHeight(null);
                    int scaledWidth = Math.round(width * scale);
                    int scaledHeight = Math.round(height * scale);

                    Image scaled = getScaledImage(overlay, scaledWidth, scaledHeight);
                    Rectangle overlayRect = new Rectangle(0, 0, scaledWidth, scaledHeight);
                    Point ap = ImageUtils.parsePoint(applyMacros(child, ATTR_ANCHOR, "lr,-10,-10"),
                            overlayRect);
                    g.drawImage(scaled, pp.x - ap.x, pp.y - ap.y, bg, null);
                }
            }
        } else {
            error("Unknown tag:" + tagName);
        }
        if (newImage != null) {
            String newFileName = applyMacros(child, ATTR_FILE, (String) null);
            if (shouldIterateChildren) {
                logger.trace("newFileName='{}' viewManager={} newImage={}", newFileName, viewManager, newImage);
                newImage = processImage(newImage, newFileName, child, null, viewManager, new Hashtable());
                logger.trace("finished processImage; result: {}", newImage);
            }
            if (newFileName != null) {
                logger.trace("calling writeImageToFile...");
                ImageUtils.writeImageToFile(newImage, getImageFileName(newFileName));
                logger.trace("finished writeImageToFile");
                debug("Writing image:" + newFileName);
            }
            if (!applyMacros(child, ATTR_COPY, false)) {
                image = newImage;
            }
        }
    }

    if (filename != null) {
        float quality = (float) applyMacros(node, ATTR_QUALITY, 1.0);
        List<String> fileToks = StringUtil.split(filename, ",", true, true);
        for (String file : fileToks) {
            file = getImageFileName(file);
            debug("Writing image:" + file);
            if (file.endsWith(FileManager.SUFFIX_KMZ) || file.endsWith(FileManager.SUFFIX_KML)) {
                GeoLocationInfo bounds = null;
                if (viewManager != null) {
                    bounds = viewManager.getVisibleGeoBounds();
                    ImageSequenceGrabber.subsetBounds(bounds, imageProps);
                    String tmpImageFile = getOutputPath(file);
                    ImageUtils.writeImageToFile(image, tmpImageFile, quality);
                    ImageWrapper imageWrapper = new ImageWrapper(tmpImageFile, null, bounds, null);
                    imageWrapper.setProperties(imageProps);
                    new ImageSequenceGrabber(file, getIdv(), this, node,
                            (List<ImageWrapper>) Misc.newList(imageWrapper), null, 1);
                }
            } else {
                logger.trace("another writeImageToFile call...");
                ImageUtils.writeImageToFile(image, file, quality);
                logger.trace("and it's done.");
            }
        }
    }
    logger.trace("result: {}", image);
    return image;
}

From source file:tufts.vue.LWComponent.java

public void setFrame(Rectangle2D r) {
    setFrame((float) r.getX(), (float) r.getY(), (float) r.getWidth(), (float) r.getHeight());
}

From source file:tufts.vue.LWComponent.java

protected boolean doZoomingDoubleClick(MapMouseEvent e) {
    //   System.out.println("zooming double click");

    final MapViewer viewer = e.getViewer();

    if (viewer.getFocal() == this) {
        viewer.popFocal(MapViewer.POP_TO_TOP, MapViewer.ANIMATE);
        return true;
        //return false;
    }//from  ww  w  . j av a2s. co  m
    VUE.getActiveMap().setTempBounds(VUE.getActiveViewer().getVisibleMapBounds());
    final Rectangle2D viewerBounds = viewer.getVisibleMapBounds();
    final Rectangle2D mapBounds = getMapBounds();
    final Rectangle2D overlap = viewerBounds.createIntersection(mapBounds);
    final double overlapArea = overlap.getWidth() * overlap.getHeight();
    //final double viewerArea = viewerBounds.getWidth() * viewerBounds.getHeight();
    final double nodeArea = mapBounds.getWidth() * mapBounds.getHeight();
    final boolean clipped = overlapArea < nodeArea;

    final double overlapWidth = mapBounds.getWidth() / viewerBounds.getWidth();
    final double overlapHeight = mapBounds.getHeight() / viewerBounds.getHeight();

    final boolean focusNode; // otherwise, re-focus map

    // Note: this code is way more complicated than we're making use of right now --
    // we always fully load objects (slides) as the focal when we zoom to them.
    // This code permitted double-clicking through a slide-icon stack, where we'd
    // zoom to the slide icon, but retain the map focal.  The overlap herustics here
    // determined how much of the current view was occupied by the current clicked
    // on zoom-to object.  If mostly in view, assume we want to "de-focus" (zoom
    // back out to the map from our "virtual focal" zoomed-to node), but if mostly
    // not in view, re-center on this object.  When last tested, this was smart
    // enough to allow you to simply cycle through a stack of slide-icons with
    // double clicking on the exposed edge of the nearby slide icons (of course,
    // this code was on LWSlide back then...)

    if (DEBUG.Enabled) {
        outf(" overlapWidth %4.1f%%", overlapWidth * 100);
        outf("overlapHeight %4.1f%%", overlapHeight * 100);
        outf("clipped=" + clipped);
    }

    if (clipped) {
        focusNode = true;
    } else if (overlapWidth > 0.8 || overlapHeight > 0.8) {
        focusNode = false;
    } else
        focusNode = true;

    if (focusNode) {
        viewer.clearRollover();

        if (SwapFocalOnSlideZoom) {
            // loadfocal animate only currently works when popping (to a parent focal)
            //viewer.loadFocal(this, true, AnimateOnZoom);
            ZoomTool.setZoomFitRegion(viewer, mapBounds, 0, AnimateOnZoom);
            viewer.loadFocal(this);
        } else {
            ZoomTool.setZoomFitRegion(viewer, mapBounds, -LWPathway.PathBorderStrokeWidth / 2, AnimateOnZoom);
        }
    } else {
        // just re-fit to the map
        viewer.fitToFocal(AnimateOnZoom);
    }

    return true;
}

From source file:tufts.vue.LWComponent.java

/**
 * This will take the given zeroRect rectangle in local coordinates, and transform it
 * into map coordinates, setting mapRect and returning it.  If mapRect is null,
 * a new rectangle will be created and returned.
 *//*from   www. j  av  a  2  s .c  o  m*/
public Rectangle2D transformZeroToMapRect(Rectangle2D zeroRect, Rectangle2D mapRect) {
    final AffineTransform tx = getZeroTransform();
    final double[] points = new double[4];

    points[0] = zeroRect.getX();
    points[1] = zeroRect.getY();
    points[2] = points[0] + zeroRect.getWidth();
    points[3] = points[1] + zeroRect.getHeight();
    tx.transform(points, 0, points, 0, 2);

    if (mapRect == null)
        mapRect = new Rectangle2D.Float();

    mapRect.setRect(points[0], points[1], points[2] - points[0], points[3] - points[1]);

    return mapRect;

    // Non-rotating & non-transform using version:
    //         final double scale = getMapScale();
    //         // would this be right? scale the x/y first?
    //         if (scale != 1) {
    //             rect.x *= scale;
    //             rect.y *= scale;
    //             rect.width *= scale;
    //             rect.height *= scale;
    //         }
    //         if (this instanceof LWLink) {
    //             // todo: eventually rewrite this routine entirely to use the transformations
    //             // (will need that if ever want to handle rotation, as well as to skip this
    //             // special case for links).
    //             rect.x += getParent().getMapX();
    //             rect.y += getParent().getMapY();
    //         } else {
    //             rect.x += getMapX();
    //             rect.y += getMapY();
    //         }

}

From source file:tufts.vue.LWComponent.java

/**
 * @param mapRect -- incoming rectangle to transform to be relative to 0,0 of this component
 * @param zeroRect -- result is placed here -- will be created if is null
 * @return zeroRect//from  ww  w  .  jav a  2 s  .com
 *
 * E.g., if the incoming mapRect was from map coords 100,100->120,120, and this component was at 100,100,
 * the resulting zeroRect in this case would be 0,0->20,20 (assuming no scale or rotation).
 *
 */
//protected Rectangle2D transformMapToZeroRect(Rectangle2D mapRect, Rectangle2D zeroRect)
protected Rectangle2D transformMapToZeroRect(Rectangle2D mapRect) {
    //         if (zeroRect == null)
    //             zeroRect = (Rectangle2D) mapRect.clone(); // simpler than newInstace, tho we won't need the data-copy in the end
    Rectangle2D zeroRect = new Rectangle2D.Float();

    // If want to handle rotation, we'll need to transform each corner of the
    // rectangle separately, generating Polygon2D (which sun never implemented!)  or
    // a GeneralPath, in either case changing this method to return a Shape.  Better
    // would be to keep a cached rotated map Shape in each object, tho that means
    // solving the general problem of making sure we're updated any time our
    // ultimate map location/size/scale/rotation, etc, changes, which of course
    // changes if any of those values change on any ancestor.  If we did that, we'd
    // also be able to fully cache the _zeroTransform w/out having to recompute it
    // for each call just in case.  (Which would mean getting rid of this method
    // entirely and using the map shape in intersects, etc) Of course, crap, we
    // couldn't do all this for links, could we?  Tho maybe via special handing in an
    // override... tho that would only work for the transform, not the shape, as the
    // parent shape is useless to the link. FYI, currently, we only use this
    // for doing intersections of links and non-rectangular nodes

    //         final double[] points = new double[8];
    //         final double width = zeroRect.getWidth();
    //         final double height = zeroRect.getHeight();
    //         // UL
    //         points[0] = zeroRect.getX();
    //         points[1] = zeroRect.getY();
    //         // UR
    //         points[2] = points[0] + width;
    //         points[3] = points[1];
    //         // LL
    //         points[4] = points[0];
    //         points[5] = points[1] + height;
    //         // LR
    //         points[6] = points[0] + width;
    //         points[7] = points[1] + height;

    // Now that we know the below code can never handle rotation, we also might as
    // well toss out using the transform entirely and just use getMapScale /
    // getMapX/Y to mod a Rectangle2D.Float directly... Tho then our zoomed rollover
    // mod, which is in the transformDown code would stop working for rectangle
    // picking & clipping, tho we shouldn't need rect picking for zoomed rollovers,
    // (only point picking) and the zoomed rollover always draws no matter what (in
    // the MapViewer), so that may be moot, tho would need to fully test to be sure.
    // All of the this also applies to transformZeroToMapRect below.

    final AffineTransform tx = getZeroTransform();
    final double[] points = new double[4];
    points[0] = mapRect.getX();
    points[1] = mapRect.getY();
    points[2] = points[0] + mapRect.getWidth();
    points[3] = points[1] + mapRect.getHeight();
    try {
        tx.inverseTransform(points, 0, points, 0, 2);
    } catch (java.awt.geom.NoninvertibleTransformException e) {
        Util.printStackTrace(e);
    }

    zeroRect.setRect(points[0], points[1], points[2] - points[0], points[3] - points[1]);

    return zeroRect;

}