/* @(#) Scroll.java 1.1 99/01/11
 * Copyright (c) 1999 Lawrence Rodrigues
 */
package com.vistech.imageviewer;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.awt.geom.*;
/** Scrolls an image displayed on a canvas.
  * The canvas object must implement the ImageManipulator interface.
  * @version 1.0  1 Nov 1999
  * @author Lawrence Rodrigues
  **/
public class Scroll implements ScrollController, Serializable {
   protected AffineTransform atx = new AffineTransform();
   //Pan variables
   protected Point panOffset = new Point(0,0);
   private Point diff = new Point(0,0);
   private Point scrollAnchor  = new Point(0,0);
   protected ImageManipulator imageCanvas;

   public Scroll() {}

   /** @param imagecanvas the component on which the image is drawn.
   */
   public Scroll(ImageManipulator imageCanvas) {
      this.imageCanvas = imageCanvas;
   }
   /** @param imagecanvas the component on which the image is drawn.
   */
   public void setImageManipulator(ImageManipulator imageCanvas){
      this.imageCanvas = imageCanvas;
   }

   public void setPanOffset(Point panOffset){
      this.panOffset = panOffset;
      imageCanvas.setPanOffset(panOffset);
   }

   public Point getPanOffset(){return panOffset; }

   public void translateIncr(double incrx, double incry) {
      atx.translate(incrx, incry);
      imageCanvas.applyTransform(atx);
   }

   public void translate(double diffx, double diffy) {
      double dx = diffx -panOffset.x;
      double dy = diffy -panOffset.y;
      panOffset.x = (int)diffx;
      panOffset.y = (int)diffy;
      translateIncr(dx,dy);
   }

   public void resetAndTranslate(int dx, int dy) {
      atx.setToTranslation((double)dx, (double)dy);
      imageCanvas.applyTransform(atx);
  }

   public void scroll(int x, int y){
      if((x <0 )|| (y<0)) return;
      try {
          Point2D xy = null;
          xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy);
          double ix  = (xy.getX()-scrollAnchor.x);
          double iy =  (xy.getY()-scrollAnchor.y);
          translateIncr(ix,iy);
      }catch(Exception e) {System.out.println(e);}
   }

   public void startScroll(int x, int y){
      atx = imageCanvas.getTransform();
      //Create a new anchor point so that everytime mouse button is clicked,
      //the image does not move instead the anchor point moves.
      try {
          Point2D xy = null;
          xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy);
          scrollAnchor = new Point((int)(xy.getX()),(int)(xy.getY()));
          imageCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
       }catch(Exception e) {System.out.println(e);}
   }

   public void stopScroll(){ imageCanvas.setCursor(Cursor.getDefaultCursor());}

   public void reset() {
      scrollAnchor = new Point(0,0);
      diff = new Point(0,0);
  }
}