/**
 * class PanZoomTest
 *
 * @author hill
 * Date: Oct 2, 2001
 * Time: 3:39:36 PM
 *
 * This version uses the following trick/technique
 *
 * The image is always drawn with the origin translated to the middle of the
 * display area. The image is then panned by using
 *
 * g2.setTransform(atx); // set origin, zoom, and rotation
 *
 * drawImage(image, panX, panY, this);
 *
 * Big Question: is there some way to add the panX and panY into the affineTransform
 * so that all info can be packed into the atx. Because currently, the atx gets
 * passed to the ROIs etc for drawing. Perhaps we can add in the panX and panY
 * as the very last operation when building the transform.
 *
 *
 * A test class that
 * 1. creates a BufferedImage
 * 2. displays it with pan, zoom, and rotate capabilities
 *
 * To zoom, drag left mouse button up or down
 * To pan, drag right mouse button
 * To rotate, drag right mouse button with CTRL down
 *
 */
package panzoom;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.BasicStroke;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.BufferedImage;


public class PanZoomTest4 extends JPanel
{
    private BufferedImage bufferedImage = null;
    final private int     imageWidth    = 256;
    final private int     imageHeight   = 256;

    // initial distance between edges of image an outer edges of panel
    final private int     imageMargin   = 24;

    final private int     panelWidth  = imageWidth  + (imageMargin * 2);
    final private int     panelHeight = imageHeight + (imageMargin * 2);

    // use these to center the origin of the drawing area at center of panel
    final private int     halfPanelWidth  = panelWidth  / 2;
    final private int     halfPanelHeight = panelHeight / 2;

    // state variables for pan and zoom

    // last position of mouse
    int lastX;
    int lastY;

    // difference between last position and current position
    int deltaX;
    int deltaY;

    // true if zooming
    boolean bZooming;

    // pan state offsets, initially set just to center the image
    // these are used as arguments to drawImage, not atx.translate(x, y);
    int panX =  -(imageWidth/2);
    int panY =  -(imageHeight/2);

    // translated versions of panX and panY, see below
    double xPrime = panX;
    double yPrime = panY;

    // initially no zoom
    double zoomFactor = 1.0;

    // initially no rotation
    double rotationDegrees = 0.0;


    public PanZoomTest4( )
    {
        super( );

        // set panel to be a little larger than the image
        setPreferredSize(new Dimension(panelWidth, panelHeight));

        bufferedImage = makeBufferedImage( );

        setBorder(BorderFactory.createLineBorder(Color.red));

        addMouseListener( new PanelMouseListener( ));
        addMouseMotionListener( new PanelMouseMotionListener( ));
    }

    private BufferedImage makeBufferedImage( )
    {
        BufferedImage bi = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D    g2 = bi.createGraphics( );

        g2.setPaint(Color.black);
        g2.setStroke(new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

        // draw a big rect with a big X in it
        g2.drawRect(2, 2,               imageWidth - 4, imageHeight - 4);
        g2.drawLine(2, 2,               imageWidth - 4, imageHeight - 4);
        g2.drawLine(2, imageHeight - 4, imageWidth - 4, 2);

        // draw four smaller + marks, each in a different color
        Point2D topCenterPt    = new Point2D.Double(imageWidth * 0.5,  imageHeight * 0.25);
        Point2D leftCenterPt   = new Point2D.Double(imageWidth * 0.25, imageHeight * 0.5);
        Point2D rightCenterPt  = new Point2D.Double(imageWidth * 0.75, imageHeight * 0.5);
        Point2D bottomCenterPt = new Point2D.Double(imageWidth * 0.5,  imageHeight * 0.75);

        drawPlusSign(g2, topCenterPt,    Color.red);
        drawPlusSign(g2, leftCenterPt,   Color.green.brighter());
        drawPlusSign(g2, rightCenterPt,  Color.blue.brighter());
        drawPlusSign(g2, bottomCenterPt, Color.orange.brighter());

        return bi;
    }

    /**
     * Draw a plus sign centered on pt in the specified color
     */
    private void drawPlusSign(Graphics2D g2, Point2D pt, Color color)
    {
        double delta = (imageWidth / 4) - 4;

        double x = pt.getX();
        double y = pt.getY();

        g2.setPaint(color);
        g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));


        g2.drawLine((int)(x - delta), (int) y , (int)(x + delta), (int) y);
        g2.drawLine((int)x, (int)(y - delta) , (int)x, (int)(y + delta));
    }

    private double degreesToRadians(double degrees)
    {
        return degrees * Math.PI / 180.0;
    }

    private AffineTransform getLocalTransform( )
    {
        AffineTransform atx = new AffineTransform( );

        final double zoomDelta = 0.1;


        if(bZooming)
        {
            if(deltaY > 0)
            {   // zooming down ==> smaller image

                if(zoomFactor >= 0.3)  // don't go below this
                {
                    zoomFactor -= zoomDelta;
                }
            }
            else if(deltaY < 0)  //  ==> bigger image
            {
                if(zoomFactor < 4.0)  // don' go above this
                {
                    zoomFactor += zoomDelta;
                }
            }
        }

        // move origin to center of panel
        atx.translate(halfPanelWidth, halfPanelHeight);

        // rotate and scale about the center
        atx.rotate(degreesToRadians(rotationDegrees));
        atx.scale(zoomFactor, zoomFactor);

        // move origin to center or pan the image
        atx.translate(xPrime, yPrime);

        return atx;
    }

    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        AffineTransform oldAtx = g2.getTransform();

        AffineTransform atx = getLocalTransform( );

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_DITHERING,
                            RenderingHints.VALUE_DITHER_ENABLE);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING,
                            RenderingHints.VALUE_RENDER_QUALITY);

        g2.setTransform(atx);

        g2.drawImage(bufferedImage, 0, 0, this);

        // put back old transform
        g2.setTransform(oldAtx);
    }


    static void centerOnScreen(Component component)
    {
        Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
        Dimension size       = component.getSize( );

        screenSize.height = screenSize.height / 2;
        screenSize.width  = screenSize.width  / 2;

        size.height = size.height / 2;
        size.width  = size.width  / 2;

        int y = screenSize.height - size.height;
        int x = screenSize.width  - size.width;

        component.setLocation(x, y);
    }

    class PanelMouseListener extends MouseAdapter
    {
        /** record the mouse down point */
        public void mousePressed(MouseEvent e)
        {
            super.mousePressed(e);

            lastX = e.getX();
            lastY = e.getY();
        }
    }

    class PanelMouseMotionListener extends MouseMotionAdapter
    {
        /** user is zooming or panning */
        public void mouseDragged(MouseEvent e)
        {
            super.mouseDragged(e);

            deltaX = e.getX() - lastX;
            deltaY = e.getY() - lastY;

            // right mouse does pan and rotate
            if(SwingUtilities.isRightMouseButton(e))
            {
                bZooming = false;

                if(e.isControlDown())  // rotating
                {
                    rotationDegrees += deltaX;
                }
                else       // panning
                {
                    // need to adjust the delta values depending on the current
                    // zoom factor. If don't do this panning goes 'too fast' when
                    // zoomed up and 'too slow' when zoomed down.
                    panX += deltaX * (1/zoomFactor);
                    panY += deltaY * (1/zoomFactor);

                    // adjust the pan translation so that even when
                    // axes are rotated, will still pan in direction of
                    // mouse movement
                    double radians    = degreesToRadians(rotationDegrees);
                    double sinRadians = Math.sin(radians);
                    double cosRadians = Math.cos(radians);

                    xPrime =  (panX * cosRadians) + (panY * sinRadians);
                    yPrime =  (panY * cosRadians) - (panX * sinRadians);
                }
           }
            else
            {
                bZooming = true;
            }

            lastX = e.getX();
            lastY = e.getY();

            repaint();
        }
    }

    public static void main(String[ ] args)
    {
        JFrame frame = new JFrame("Pan Zoom Test 4 Panel");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        frame.getContentPane( ).add(new PanZoomTest4( ), BorderLayout.CENTER);
        frame.pack( );
        centerOnScreen(frame);
        frame.setVisible(true);
    }
}
