/**  PlanarImageViewer Class
   * @version 1.0  12 June 2000
   * @author Lawrence Rodrigues
   **/
package app;
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import com.sun.image.codec.jpeg.*;
import com.vistech.rmi.*;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import com.sun.media.jai.codec.*;

/** An RMI client application that lists and displays planar images loaded
  * by an RMI server.
  * @version 1.0 12 june 2000
  * @author Lawrence Rodrigues
  **/
public class PlanarImageViewer extends AWTImageViewer{

   public PlanarImageViewer(){
      setTitle("Planar Image Viewer");
   }

   protected JPanel createImageCanvas() {
      return new PlanarImagePanel();
   }

   public void load(String filename) throws RemoteException{
      byte[] buffer = loader.loadImageAsBytes(filename);
      ByteArrayInputStream bis = new   ByteArrayInputStream(buffer);
      PlanarImage img =  readAsPlanarImage(bis);
      if(img == null) {return; }
      ((PlanarImagePanel)imCanvas).setImage(img);
      ((PlanarImagePanel)imCanvas).repaint();
   }

   public static PlanarImage readAsPlanarImage(InputStream is) {
      try {
      SeekableStream ss = SeekableStream.wrapInputStream(is,true);
      return JAI.create("stream", ss, null);
      } catch (Exception e){return null;}
   }

   public static void main(String args[]){
      PlanarImageViewer fc = new PlanarImageViewer();
   }
}

class PlanarImagePanel extends ImagePanel{
   PlanarImage plimage;
   int viewerWid = 400;
   int viewerHt = 600;
   int imageWidth;
   int imageHeight;
   public void setImage(PlanarImage img){
      plimage = img;
      imageWidth = img.getWidth();
      imageHeight = img.getHeight();
      repaint();
   }

   public void paintComponent(Graphics gc){
      Graphics2D g = (Graphics2D)gc;
      Rectangle rect = this.getBounds();
      if((viewerWid != rect.width) || (viewerHt != rect.height)){
         viewerWid = rect.width;
         viewerHt = rect.height;
      }
      double magx = rect.width/(double)imageWidth ;
      double magy = rect.height/(double)imageHeight ;
      g.setColor(Color.black);
      g.fillRect(0,0,rect.width, rect.height);
      AffineTransform atx =  AffineTransform.getScaleInstance(magx, magy);
      if(plimage != null) g.drawRenderedImage(plimage, atx);
   }
}
