view flys-client/src/main/java/de/intevation/flys/client/client/ui/chart/ChartOutputTab.java @ 555:33b86f5b1168

Don't crash if there is no transformer. flys-client/trunk@2078 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Wed, 08 Jun 2011 10:57:28 +0000
parents 6050d49eaba3
children 460b8e0f0563
line wrap: on
line source
package de.intevation.flys.client.client.ui.chart;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Img;

import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

import com.smartgwt.client.widgets.events.ResizedEvent;
import com.smartgwt.client.widgets.events.ResizedHandler;

import de.intevation.flys.client.shared.Transform2D;
import de.intevation.flys.client.shared.model.Axis;
import de.intevation.flys.client.shared.model.ChartInfo;
import de.intevation.flys.client.shared.model.Collection;
import de.intevation.flys.client.shared.model.OutputMode;
import de.intevation.flys.client.client.Config;
import de.intevation.flys.client.client.event.OutputParameterChangeEvent;
import de.intevation.flys.client.client.event.OutputParameterChangeHandler;
import de.intevation.flys.client.client.event.PanEvent;
import de.intevation.flys.client.client.event.PanHandler;
import de.intevation.flys.client.client.event.ZoomEvent;
import de.intevation.flys.client.client.event.ZoomHandler;
import de.intevation.flys.client.client.services.ChartInfoService;
import de.intevation.flys.client.client.services.ChartInfoServiceAsync;
import de.intevation.flys.client.client.ui.CollectionView;
import de.intevation.flys.client.client.ui.OutputTab;


/**
 * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
 */
public class ChartOutputTab
extends      OutputTab
implements   ResizedHandler, OutputParameterChangeHandler, ZoomHandler,
             PanHandler
{
    public static final int DEFAULT_CHART_WIDTH  = 600;
    public static final int DEFAULT_CHART_HEIGHT = 500;

    public static final int THEMEPANEL_MIN_WIDTH = 200;


    /** The service that is used to fetch chart information.*/
    protected ChartInfoServiceAsync info = GWT.create(ChartInfoService.class);


    /** The ChartInfo object that provides information about the current
     * chart.*/
    protected ChartInfo chartInfo;

    /** The transformer used to transform image pixels into chart coordinates.*/
    protected Transform2D transformer;

    /** The collection view.*/
    protected CollectionView view;


    /** The canvas that wraps the chart toolbar.*/
    protected Canvas tbarPanel;

    /** The canvas that wraps the theme editor.*/
    protected Canvas left;

    /** The canvas that wraps the chart.*/
    protected Canvas right;


    /** Chart zoom options.*/
    protected double[] xrange;
    protected double[] yrange;


    /**
     * The default constructor to create a new ChartOutputTab.
     *
     * @param title The title of this tab.
     * @param collection The Collection which this chart belongs to.
     * @param mode The OutputMode.
     */
    public ChartOutputTab(
        String         title, 
        Collection     collection,
        OutputMode     mode,
        CollectionView collectionView
    ){
        super(title, collection, mode);

        view      = collectionView;
        left      = new Canvas();
        right     = new Canvas();
        tbarPanel = new ChartToolbar(collectionView, this);
        xrange    = new double[2];
        yrange    = new double[2];

        left.setBorder("1px solid black");
        left.setWidth(THEMEPANEL_MIN_WIDTH);
        left.setMinWidth(THEMEPANEL_MIN_WIDTH);
        right.setWidth("*");

        VLayout vLayout = new VLayout();
        vLayout.setMembersMargin(2);

        HLayout hLayout = new HLayout();
        hLayout.setWidth100();
        hLayout.setHeight100();
        hLayout.setMembersMargin(10);

        hLayout.addMember(left);
        hLayout.addMember(right);

        ChartThemePanel ctp = new ChartThemePanel(collection, mode);
        ctp.addOutputParameterChangeHandler(this);

        right.addChild(createChartPanel());
        left.addChild(ctp);

        vLayout.addMember(tbarPanel);
        vLayout.addMember(hLayout);

        setPane(vLayout);

        right.addResizedHandler(this);
    }


    /**
     * This method is called after the chart panel has resized. It removes the
     * chart - if existing - and requests a new one with adjusted size.
     *
     * @param event The resize event.
     */
    public void onResized(ResizedEvent event) {
        updateChartPanel();
        updateTransformer();
    }


    /**
     * Listens to change event in the chart them panel and updates chart after
     * receiving such an event.
     *
     * @param event The OutputParameterChangeEvent.
     */
    public void onOutputParameterChanged(OutputParameterChangeEvent event) {
        updateChartPanel();
    }


    /**
     * Listens to zoom events and refreshes the current chart in such case.
     *
     * @param evt The ZoomEvent that stores the coordinates for zooming.
     */
    public void onZoom(ZoomEvent evt) {
        if (transformer == null) {
            return;
        }
        double[] lower = transformer.transform(evt.getStartX(), evt.getStartY());
        double[] upper = transformer.transform(evt.getEndX(), evt.getEndY());

        xrange[0] = lower[0];
        xrange[1] = upper[0];
        yrange[0] = upper[1];
        yrange[1] = lower[1];

        updateTransformer();
        updateChartPanel();
    }


    public void onPan(PanEvent event) {
        if (transformer == null) {
            return;
        }
        int[] start = event.getStartPos();
        int[] end   = event.getEndPos();

        double[] startPos = transformer.transform(start[0], start[1]);
        double[] endPos   = transformer.transform(end[0], end[1]);

        double diffX = startPos[0] - endPos[0];
        double diffY = startPos[1] - endPos[1];

        panTo(diffX, diffY);
    }


    /**
     * This method pans to chart with a given factor.
     */
    public void panTo(double diffX, double diffY) {
        Axis xAxis = chartInfo.getXAxis(0);
        Axis yAxis = chartInfo.getYAxis(0);

        xrange[0] = xAxis.getFrom() + diffX;
        xrange[1] = xAxis.getTo() + diffX;
        yrange[0] = yAxis.getFrom() + diffY;
        yrange[1] = yAxis.getTo() + diffY;

        updateTransformer();
        updateChartPanel();
    }


    public void resetRanges() {
        xrange[0] = 0;
        xrange[1] = 0;
        yrange[0] = 0;
        yrange[1] = 0;

        updateTransformer();
        updateChartPanel();
    }


    /**
     * This method is used to zoom out.
     *
     * @param factor The factor should be between 0-100.
     */
    public void zoomOut(int factor) {
        if (factor < 0 || factor > 100 || xrange == null || yrange == null) {
            return;
        }

        double xadd = (xrange[1] - xrange[0]) / 100 * factor;
        double yadd = (yrange[1] - yrange[0]) / 100 * factor;

        xrange[0] -= xadd;
        xrange[1] += xadd;
        yrange[0] -= yadd;
        yrange[1] += yadd;

        updateTransformer();
        updateChartPanel();
    }


    /**
     * Updates the Transform2D object using the chart info service.
     */
    public void updateTransformer() {
        Config config = Config.getInstance();
        String url    = config.getServerUrl();
        String locale = config.getLocale();

        info.getChartInfo(
            view.getCollection(),
            url,
            locale,
            mode.getName(),
            getChartAttributes(),
            new AsyncCallback<ChartInfo>() {
                public void onFailure(Throwable caught) {
                    GWT.log("ERROR: " + caught.getMessage());
                }

                public void onSuccess(ChartInfo chartInfo) {
                    setChartInfo(chartInfo);
                }
            });
    }


    public void updateChartPanel() {
        Canvas[] children = right.getChildren();
        for (Canvas child: children) {
            right.removeChild(child);
        }

        right.addChild(createChartPanel(right.getWidth(), right.getHeight()));
    }


    /**
     * Returns the existing chart panel.
     *
     * @return the existing chart panel.
     */
    public Canvas getChartPanel() {
        Canvas[] children = right.getChildren();

        if (children == null || children.length == 0) {
            GWT.log("=> No chart image in the panel.");
            return right;
        }

        return children[0];
    }


    public ChartInfo getChartInfo() {
        return chartInfo;
    }


    protected void setChartInfo(ChartInfo chartInfo) {
        this.chartInfo = chartInfo;
        setTransformer(chartInfo.getTransformer());
    }


    /**
     * Returns the Transform2D object used to transform image coordinates into
     * chart coordinates.
     *
     * @return the Transform2D object.
     */
    public Transform2D getTransformer() {
        return transformer;
    }


    /**
     * Set a new Transform2D object for the chart. This should be the case, only
     * if the chart image size has changed.
     *
     * @param transformer The new Transform2D object.
     */
    protected void setTransformer(Transform2D transformer) {
        this.transformer = transformer;
    }


    /**
     * Creates a new chart panel with default size.
     *
     * @return the created chart panel.
     */
    protected Canvas createChartPanel() {
        return createChartPanel(DEFAULT_CHART_WIDTH, DEFAULT_CHART_HEIGHT);
    }


    /**
     * Creates a new chart panel with specified width and height.
     *
     * @param width The width for the chart panel.
     * @param height The height for the chart panel.
     *
     * @return the created chart panel.
     */
    protected Canvas createChartPanel(int width, int height) {
        Img chart  = getChartImg(width, height);
        chart.setWidth100();
        chart.setHeight100();

        return chart;
    }


    /**
     * Builds the chart image and returns it.
     *
     * @param width The chart width.
     * @param height The chart height.
     *
     * @return the chart image.
     */
    protected Img getChartImg(int width, int height) {
        return new Img(getImgUrl(width, height));
    }


    /**
     * Builds the URL that points to the chart image.
     *
     * @param width The width of the requested chart.
     * @param height The height of the requested chart.
     * @param xr Optional x range (used for zooming).
     * @param yr Optional y range (used for zooming).
     *
     * @return the URL to the chart image.
     */
    protected String getImgUrl(int width, int height) {
        Config config = Config.getInstance();

        String imgUrl = GWT.getModuleBaseURL();
        imgUrl += "chart";
        imgUrl += "?uuid=" + collection.identifier();
        imgUrl += "&type=" + mode.getName();
        imgUrl += "&server=" + config.getServerUrl();
        imgUrl += "&locale=" + config.getLocale();
        imgUrl += "&timestamp=" + new Date().getTime();
        imgUrl += "&width=" + Integer.toString(width);
        imgUrl += "&height=" + Integer.toString(height);

        if (xrange != null) {
            GWT.log("Zoom to xrange.");
            imgUrl += "&minx=" + Double.toString(xrange[0]);
            imgUrl += "&maxx=" + Double.toString(xrange[1]);
        }

        if (yrange != null) {
            GWT.log("Zoom to xrange.");
            imgUrl += "&miny=" + Double.toString(yrange[0]);
            imgUrl += "&maxy=" + Double.toString(yrange[1]);
        }

        return imgUrl;
    }


    public Map getChartAttributes() {
        Map<String, String> attr = new HashMap<String, String>();

        Canvas chart = getChartPanel();
        attr.put("width", chart.getWidth().toString());
        attr.put("height", chart.getHeight().toString());

        if (xrange != null) {
            attr.put("minx", Double.toString(xrange[0]));
            attr.put("maxx", Double.toString(xrange[1]));
        }

        if (yrange != null) {
            attr.put("miny", Double.toString(yrange[0]));
            attr.put("maxy", Double.toString(yrange[1]));
        }

        return attr;
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org