(*******************************************************************
This file was generated automatically by the Mathematica front end.
It contains Initialization cells from a Notebook file, which
typically will have the same name as this file except ending in
".nb" instead of ".m".

This file is intended to be loaded into the Mathematica kernel using
the package loading commands Get or Needs.  Doing so is equivalent
to using the Evaluate Initialization Cells menu command in the front
end.

DO NOT EDIT THIS FILE.  This entire file is regenerated
automatically each time the parent Notebook file is saved in the
Mathematica front end.  Any changes you make to this file will be
overwritten.
***********************************************************************)









(* :Title: JavaPhotoEditor *)
(* :Context: JLinkProgramming`JavaPhotoEditor`JavaPhotoEditor` *)
(* :Author: Junzo SATO *)
(* :Summary: The entrypoint of the Java Photo Editor program.*)
(* :Package Version: 1.1.4 *)
(* :Release Note: 
        Ver 1.0 Reproduced with Mathematica 4.1 in Jul 2001 
      Ver 1.1 Fixed for multiplatform.
          Ver 1.1.1 Imporoved tools implementation. 
          Ver 1.1.2 Modified for Forte and MacOS X.
          
          Ver 1.1.3 Revised for JLink2.0.1 and new Java Photo Editor \
structure. 
          
          Ver 1.1.4 Revised for new JavaPhotoEditor application and \
ImageProcessing`BufferedImage` package.*)
(* :Mathematica Version: 4.1 *)
(* :Copyright: Copyright \[Copyright] 2000-2002, 
  Junzo SATO. All rights reserved. *)
(* :History: Ver Alpha Sep 2000 by Junzo SATO.
          Ver 1.0 Apr 2001 
    Ver 1.1 Oct 2001 
    Ver 1.1.1 Oct 2001 
    Ver 1.1.2 Feb 2002 
    Ver 1.1.3 Sep 2002 
    Ver 1.1.4 Nov 2002*)
(* :Keywords: Java, JavaGraphics, JavaPhotoEditor, DigitalImageProcessing *)
(* :Reference: *)
(* :Limitation: *)
(* :Discussion: *)



Print["Welcome to the Java Photo Editor!"]
Print["Loading JavaPhotoEditor..."]

Off[Needs::nocont]



BeginPackage["JLinkProgramming`JavaPhotoEditor`JavaPhotoEditor`",{"JLink`"}]

InstallJava[]

LoadJav aClass["java.awt.GridLayout"];

LoadJavaClass["java.awt.image.PixelGrabber"];

LoadJavaClass["java.awt.image.CropImageFilter"];
LoadJavaClass["java.awt.image.ReplicateScaleFilter"];
LoadJavaClass["java.awt.image.AreaAveragingScaleFilter"];

LoadJavaClass["java.awt.Toolkit"];

Unprotect[Evaluate[$Context<>"*"]]





$JavaPhotoEditorMaterial:=StringJoin[
    Switch[$OperatingSystem,
      "Unix",
      $TopDirectory,
      "MacOS",
      StringJoin["/",StringReplace[$TopDirectory,":"\[Rule]"/"]],
      "MacOSX",
      StringJoin[$InitialDirectory,"/Library/Mathematica/",
        ToString[$VersionNumber]],
      _,
      If[StringMatchQ[$OperatingSystem,"Windows*"],
        StringReplace[$TopDirectory,{"C:\\"\[Rule]"/","\\"->"/"}],
        $TopDirectory]
      ],
    "/AddOns/Applications/JLinkProgramming/JavaPhotoEditor/Material/"]



EvaluateInNewNotebook::usage=
    "EvaluateInNewNotebook[command,close] creates a new Notebook to evaluate \
input command. If the argument close is set to True, the Notebook is closed \
after evaluation.";

GrabPixels::usage=
    "GrabPixels[javaImage,x,y,width,height] grabs pixels from javaImage. \
Pixels, whose top left corner is {x,y} and size is specified by width and \
height, are returned as a matrix of {R,G,B} colors. Each color component is 8 \
bit integer.";

GrabPixelsARGB::usage=
    "GrabPixels[javaImage,x,y,width,height] grabs pixels from javaImage. \
Pixels, whose top left corner is {x,y} and size is specified by width and \
height, are returned as a matrix of {A,R,G,B} colors. Each color component is \
8 bit integer.";

ShowJavaImage::usage=
    "ShowJavaImage[javaImage,x,y,width,height] shows a rectangular area of \
the javaImage specified by the top left corner {x,y} and size {width, \
height}. The result Graphics is constructed using RasterArray[].";

ToJavaImage::usage=
    "ToJavaImage[g,width,height(,dpi,useFE)] creates Java Image object from \
the Graphics g which is constructed using RasterArray[] or Raster[]. The Java \
Image's size is defined by width and height. Image's resolution dpi and \
renderer useFE are options. ToJavaImage[] uses JLink's evaluteToImage() \
method. Refer JLink's guide for detail. \
ToJavaImage[command,width,height(,dpi,useFE)] creates Java Image object by \
evaluating Mathematica command.";

GetMarqueeBounds::usage=
    "GetMarqueeBounds[frame] returns a rectangular area selected by the \
marquee tool. The list {x, y, width, height} is returned.";

GetAreaSelection::usage=
    "GetAreaSelection[frame] returns selected area as java.awt.Polygon \
object.";

GetAreaSelectionBounds::usage=
    "GetSelectionBounds[frame] returns selected area's bounds in {top, left, \
width, height} format on the image coordinate.";

GetPointsAsList::usage=
    "GetPointsAsList[frame] returns selected area's edge points in \
{{x1,x2,...,xn},{y1,y2,...,yn}} format on the image coordinate.";

GetAreaSelectionAsPolygon::usage=
    "GetAreaSelectionAsPolygon[frame] returns selected area as Polygon[] \
object.";



CropImage::usage="nothing";
ReplicateScale::usage="nothing";
AreaAveragingScale::usage="nothing";



Begin["`Private`"]



EvaluateInNewNotebook[command_:"Plot[Sin[x],{x,0,2Pi}]",close_:False]:=
  Module[
    {nb},
    nb=NotebookCreate[];
    NotebookApply[nb,command];
    SelectionMove[nb,All,Cell];
    SelectionEvaluate[nb];
    If[close,NotebookClose[nb]];
    ]



toUINT32[sint_]:=If[sint<0,sint+4294967296,sint];
toSINT32[uint_]:=If[uint>2147483647,uint-4294967296,uint];

alpha[uint_]:=BitAnd[Floor[uint/16777216],255];
red[uint_]:=BitAnd[Floor[uint/65536],255];
green[uint_]:=BitAnd[Floor[uint/256],255];
blue[uint_]:=BitAnd[uint,255];

toRGB[javapix_]:=Module[
    {uint},
    uint=toUINT32[javapix];
    {red[uint],green[uint],blue[uint]}
    ]

GrabPixels[img_,x_,y_,w_,h_]:=Module[
    {px=Null,pg},
    JavaBlock[pg=JavaNew["java.awt.image.PixelGrabber",
          img,
          Round[x],Round[y],Round[w],Round[h],
          True];
      If[pg@grabPixels[],
        px=pg@getPixels[];
        px=Map[toRGB,px];
        px=Partition[px,w];
        ];
      ];
    Return[px]
    ]

toARGB[javapix_]:=Module[
    {uint},
    uint=toUINT32[javapix];
    {alpha[uint],red[uint],green[uint],blue[uint]}
    ]

GrabPixelsARGB[img_,x_,y_,w_,h_]:=Module[
    {px=Null,pg},
    JavaBlock[pg=JavaNew["java.awt.image.PixelGrabber",
          img,
          Round[x],Round[y],Round[w],Round[h],True];
      If[pg@grabPixels[],
        px=pg@getPixels[];
        px=Map[toARGB,px];
        px=Partition[px,w];
        ];
      ];
    Return[px]
    ]



From8bit=Compile[{{x,_Real,2}},Map[ (1/255.#)&,x]]

From24bitRGBColors[colors_List]:=Module[{rgbList={}},
    rgbList=Map[From8bit,colors];
    Map[Apply[RGBColor,#]&,rgbList,{2}]]

From24bitRGBColorsToRasterArray[colors_List]:=
  RasterArray[From24bitRGBColors[colors]]

ShowJavaImage[img_,x_:0,y_:0,w_:0,h_:0]:=JavaBlock[Module[
      {pixels,d,width=w,height=h},
      If[img===Null,Return[]];
      If[width\[LessEqual]0,width=img@getWidth[]];
      If[height\[LessEqual]0,height=img@getHeight[]];
      pixels=GrabPixels[img,x,y,width,height];
      d=Dimensions[pixels];
      Show[Graphics[
          From24bitRGBColorsToRasterArray[Reverse[pixels]],
          AspectRatio\[Rule]N[d[[1]]/d[[2]]]
          ]]
      ]]



ToJavaImage[gr_Graphics,width_,height_,dpi_:0,useFE_:True]:=Module[
    {e,ml,byteArray,tk},
    If[Head[gr[[1]]]===RasterArray||Head[gr[[1]]]===Raster,
      e=MakeJavaExpr[gr];
      If[e=!=Null&&True===InstanceOf[e,"com.wolfram.jlink.Expr"],
        LoadJavaClass["com.wolfram.jlink.StdLink"];
        ml=StdLink`getLink[];
        If[ml===Null,Return[Null]];
        If[dpi>0,
          
          byteArray=
            ReturnAsJavaObject[ml@evaluageToImage[e,width,height,dpi,useFE]],
          byteArray=ReturnAsJavaObject[ml@evaluateToImage[e,width,height]]
          ];
        LoadJavaClass["java.awt.Toolkit"];
        tk=Toolkit`getDefaultToolkit[];
        If[tk===Null,Return[Null]];
        Return[tk@createImage[byteArray]],
        Return[Null]
        ],
      Return[Null]
      ]
    ]

ToJavaImage[command_String,width_,height_,dpi_:0,useFE_:True]:=Module[
    {ml,byteArray,tk},
    LoadJavaClass["com.wolfram.jlink.StdLink"];
    ml=StdLink`getLink[];
    If[ml===Null,Return[Null]];
    If[dpi>0,
      byteArray=
        ReturnAsJavaObject[
          ml@evaluateToImage[command,width,height,dpi,useFE]],
      byteArray=ReturnAsJavaObject[ml@evaluateToImage[command,width,height]]
      ];
    LoadJavaClass["java.awt.Toolkit"];
    tk=Toolkit`getDefaultToolkit[];
    If[tk===Null,Return[Null]];
    Return[tk@createImage[byteArray]]
    ]



GetMarqueeBounds[frame_]:=Module[
    {toolManager,tool,rect},
    toolManager=frame@getToolManager[];
    tool=toolManager@getCurrentTool[];
    If[tool===Null,Return[Null]];
    If[tool@getClass[]@getName[]==="javaphotoeditor.DraggingToolMarqueeRect",
      rect=toolManager@getMarqueeRect[];
      Return[{rect@x,rect@y,rect@width,rect@height}]
      ]
    ]



GetAreaSelection[frame_]:=Module[
    {toolManager,tool,poly},
    toolManager=frame@getToolManager[];
    tool=toolManager@getCurrentTool[];
    If[tool===Null,Return[Null]];
    If[tool@getClass[]@getName[]===
        "javaphotoeditor.DraggingToolAreaSelection",
      poly=toolManager@getAreaSelection[];
      Return[poly]
      ]
    ]

GetAreaSelectionBounds[frame_]:=Module[
    {poly,bnds},
    poly=GetAreaSelection[frame];
    If[poly===Null,Return[Null]];
    bnds=poly@getBounds[];
    Return[{bnds@x,bnds@y,bnds@width,bnds@height}]
    ]

GetPointsAsList[frame_]:=Module[
    {toolManager},
    toolManager=frame@getToolManager[];
    Return[toolManager@getPointsAsList[]]
    ]

zero2one[{x_,y_}]:={If[x===0,1,x],If[y===0,1,y]}

GetAreaSelectionAsPolygon[frame_]:=Module[
    {rct,width,height,pts,xmin,ymin},
    rct=GetAreaSelectionBounds[frame];
    If[rct===Null||rct==={0,0,0,0},Return[Null]];
    (**)
    width=rct[[3]];
    height=rct[[4]];
    pts=GetPointsAsList[frame];
    If[pts===Null,Return[Null]];
    pts=Transpose[pts];
    xmin=Min[Transpose[pts][[1]]];
    ymin=Min[Transpose[pts][[2]]];
    pts=Table[{pts[[k,1]]-xmin,pts[[k,2]]-ymin},{k,1,Length[pts]}];
    pts=Table[{pts[[k,1]],height-pts[[k,2]]},{k,1,Length[pts]}];
    pts=Map[zero2one,pts];
    pts=Transpose[RotateRight[Transpose[pts]]];
    (**)
    Return[Polygon[pts]]
    ]





CropImage[producer_,srcImg_,x_,y_,w_,h_,throwawaysrc_:False]:=Module[
    {filter,dstImg=Null},
    filter=JavaNew["java.awt.image.CropImageFilter",x,y,w,h];
    dstImg=producer@createImage[
          JavaNew["java.awt.image.FilteredImageSource",
            srcImg@getSource[],
            filter]
          ];
    If[throwawaysrc,ReleaseObject[srcImg]];
    Return[dstImg]
    ]



ReplicateScale[producer_,srcImg_,newWidth_,newHeight_,throwawaysrc_:False]:=
  Module[
    {filter,dstImg=Null},
    filter=JavaNew["java.awt.image.ReplicateScaleFilter",
        Round[newWidth],Round[newHeight]];
    dstImg=producer@createImage[
          JavaNew["java.awt.image.FilteredImageSource",
            srcImg@getSource[],
            filter]
          ];
    If[throwawaysrc,ReleaseObject[srcImg]];
    Return[dstImg]
    ]



AreaAveragingScale[producer_,srcImg_,newWidth_,newHeight_,
    throwawaysrc_:False]:=Module[
    {filter,dstImg=Null},
    filter=JavaNew["java.awt.image.AreaAveragingScaleFilter",
        Round[newWidth],Round[newHeight]];
    dstImg=producer@createImage[
          JavaNew["java.awt.image.FilteredImageSource",
            srcImg@getSource[],
            filter]
          ];
    If[throwawaysrc,ReleaseObject[srcImg]];
    Return[dstImg]
    ]



End[]



EndPackage[]

On[Needs::nocont]

Print["Finished loading JavaPhotoEditor"]