/*
 * @(#)JAIView.java  1.1.1  2002-02-05
 *
 * Copyright (c) 1999-2002 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package ch.randelshofer.view;

import org.monte.media.gui.ImagePanel;

import java.awt.*;

import java.awt.image.*;

import java.io.InputStream;
import java.io.IOException;

import java.util.Hashtable;

import javax.activation.CommandObject;
import javax.activation.DataHandler;

import com.sun.media.jai.codec.MemoryCacheSeekableStream;
import com.sun.media.jai.codec.ImageCodec;

/**
 * This viewer uses the JAI (Java Advanced Imaging API) to decode images.
 *
 * @author  Werner Randelshofer, Hausmatt 10, CH-6405 Immensee, Switzerland
 * @version 1.1.1 2002-02-05 Workaround for Mac OS X 10.1.2 added.
 * <br> 1.1 2001-02-11 Improved error handling when JAI is not installed.
 * <br> 1.0.1   2000-10-05 Instance variables in ImageView have been renamed.
 * <br> 1.0  1999-10-19
 */
public class JAIView extends ImageView {
    private String decoderName;
    private static boolean isJAIInstalled;

    /** Sets the command context for the bean. The receiver loads
     * the image data provided by the data handler and displays it.
     */
    public void setCommandContext(String verb, DataHandler dh)
    throws IOException {
        if (!isJAIInstalled) {
            throw new IOException("Advanced Imaging API is not installed");
        }
        try {
            dispose();
            if (dh != null) {
                MemoryCacheSeekableStream in = null;

                in = new MemoryCacheSeekableStream(dh.getInputStream());

                String[] decoderNames = ImageCodec.getDecoderNames(in);

                if (decoderNames == null || decoderNames.length == 0) {
                    imagePanel.setMessage("Could not find decoder.");
                } else {
                    decoderName = decoderNames[0];
                    RenderedImage rendered = ImageCodec.createImageDecoder(decoderName, in, null).decodeAsRenderedImage();

                    Hashtable properties = new Hashtable();
                    String[] propertyNames = rendered.getPropertyNames();
                    if (propertyNames != null) {
                        for (int i=0; i < propertyNames.length; i++) {
                            properties.put(propertyNames[i], rendered.getProperty(propertyNames[i]));
                        }
                    }

                    BufferedImage image = new BufferedImage(
                        rendered.getColorModel(),
                        rendered.copyData(null),
                        rendered.getColorModel().isAlphaPremultiplied(),
                        properties
                    );
                    
                    // Convert the image data to make it displayable on Mac OS X 10.1.2
                    int[] pixels = new int[image.getWidth() * image.getHeight()];                 
                    image.getRGB(image.getMinX(),image.getMinY(),image.getWidth(),image.getHeight(),pixels,0,image.getWidth());

                    Image image2 = createImage(
                        new MemoryImageSource(image.getWidth(), image.getHeight(), new DirectColorModel(24,0xff0000,0x00ff00,0x0000ff), pixels, 0, image.getWidth())
                    );
                    imagePanel.setImage(image2);
                    MediaTracker mt = new MediaTracker(this);
                    mt.addImage(image2,0);
                    try { mt.waitForID(0); }
                    catch (InterruptedException e) {}
/*                   
                    imagePanel.setImage(image);

                    MediaTracker mt = new MediaTracker(this);
                    mt.addImage(image,0);
                    try { mt.waitForID(0); }
                    catch (InterruptedException e) {}
*/                }
                in.close();
            }
        } catch (IOException e) {
            throw e;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new IOException(e.getMessage());
        }
    }

    protected String getViewName() {
        return "Java Advanced Imaging View (JAI)";
    }
    
    public String toString() {
        String s = super.toString();
        return s + "\n  Decoder: "+decoderName;
        }

    public void dispose() {
        super.dispose();
        decoderName = "";
    }

    static {
        try {
            Class.forName("com.sun.media.jai.codec.ImageCodec");
            isJAIInstalled = true;
        } catch (Throwable e) {
            isJAIInstalled = false;
        }
    }
}
