Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1 @@
7c24f365ec21e126847990e92c470fe0626a9124

View File

@@ -0,0 +1,452 @@
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.VolatileImage;
import java.awt.image.WritableRaster;
/**
* The <code>GraphicsConfiguration</code> class describes the
* characteristics of a graphics destination such as a printer or monitor.
* There can be many <code>GraphicsConfiguration</code> objects associated
* with a single graphics device, representing different drawing modes or
* capabilities. The corresponding native structure will vary from platform
* to platform. For example, on X11 windowing systems,
* each visual is a different <code>GraphicsConfiguration</code>.
* On Microsoft Windows, <code>GraphicsConfiguration</code>s represent
* PixelFormats available in the current resolution and color depth.
* <p>
* In a virtual device multi-screen environment in which the desktop
* area could span multiple physical screen devices, the bounds of the
* <code>GraphicsConfiguration</code> objects are relative to the
* virtual coordinate system. When setting the location of a
* component, use {@link #getBounds() getBounds} to get the bounds of
* the desired <code>GraphicsConfiguration</code> and offset the location
* with the coordinates of the <code>GraphicsConfiguration</code>,
* as the following code sample illustrates:
* </p>
*
* <pre>
* Frame f = new Frame(gc); // where gc is a GraphicsConfiguration
* Rectangle bounds = gc.getBounds();
* f.setLocation(10 + bounds.x, 10 + bounds.y); </pre>
*
* <p>
* To determine if your environment is a virtual device
* environment, call <code>getBounds</code> on all of the
* <code>GraphicsConfiguration</code> objects in your system. If
* any of the origins of the returned bounds is not (0,&nbsp;0),
* your environment is a virtual device environment.
*
* <p>
* You can also use <code>getBounds</code> to determine the bounds
* of the virtual device. To do this, first call <code>getBounds</code> on all
* of the <code>GraphicsConfiguration</code> objects in your
* system. Then calculate the union of all of the bounds returned
* from the calls to <code>getBounds</code>. The union is the
* bounds of the virtual device. The following code sample
* calculates the bounds of the virtual device.
*
* <pre>
* Rectangle virtualBounds = new Rectangle();
* GraphicsEnvironment ge = GraphicsEnvironment.
* getLocalGraphicsEnvironment();
* GraphicsDevice[] gs =
* ge.getScreenDevices();
* for (int j = 0; j < gs.length; j++) {
* GraphicsDevice gd = gs[j];
* GraphicsConfiguration[] gc =
* gd.getConfigurations();
* for (int i=0; i < gc.length; i++) {
* virtualBounds =
* virtualBounds.union(gc[i].getBounds());
* }
* } </pre>
*
* @see Window
* @see Frame
* @see GraphicsEnvironment
* @see GraphicsDevice
*/
/*
* REMIND: What to do about capabilities?
* The
* capabilities of the device can be determined by enumerating the possible
* capabilities and checking if the GraphicsConfiguration
* implements the interface for that capability.
*
*/
public abstract class GraphicsConfiguration {
private static BufferCapabilities defaultBufferCaps;
private static ImageCapabilities defaultImageCaps;
/**
* This is an abstract class that cannot be instantiated directly.
* Instances must be obtained from a suitable factory or query method.
*
* @see GraphicsDevice#getConfigurations
* @see GraphicsDevice#getDefaultConfiguration
* @see GraphicsDevice#getBestConfiguration
* @see Graphics2D#getDeviceConfiguration
*/
protected GraphicsConfiguration() {
}
/**
* Returns the {@link GraphicsDevice} associated with this
* <code>GraphicsConfiguration</code>.
* @return a <code>GraphicsDevice</code> object that is
* associated with this <code>GraphicsConfiguration</code>.
*/
public abstract GraphicsDevice getDevice();
/**
* Returns a {@link BufferedImage} with a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>. This
* method has nothing to do with memory-mapping
* a device. The returned <code>BufferedImage</code> has
* a layout and color model that is closest to this native device
* configuration and can therefore be optimally blitted to this
* device.
* @param width the width of the returned <code>BufferedImage</code>
* @param height the height of the returned <code>BufferedImage</code>
* @return a <code>BufferedImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>.
*/
public BufferedImage createCompatibleImage(int width, int height) {
ColorModel model = getColorModel();
WritableRaster raster =
model.createCompatibleWritableRaster(width, height);
return new BufferedImage(model, raster,
model.isAlphaPremultiplied(), null);
}
/**
* Returns a <code>BufferedImage</code> that supports the specified
* transparency and has a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>. This
* method has nothing to do with memory-mapping
* a device. The returned <code>BufferedImage</code> has a layout and
* color model that can be optimally blitted to a device
* with this <code>GraphicsConfiguration</code>.
* @param width the width of the returned <code>BufferedImage</code>
* @param height the height of the returned <code>BufferedImage</code>
* @param transparency the specified transparency mode
* @return a <code>BufferedImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>
* and also supports the specified transparency.
* @throws IllegalArgumentException if the transparency is not a valid value
* @see Transparency#OPAQUE
* @see Transparency#BITMASK
* @see Transparency#TRANSLUCENT
*/
public BufferedImage createCompatibleImage(int width, int height,
int transparency)
{
if (getColorModel().getTransparency() == transparency) {
return createCompatibleImage(width, height);
}
ColorModel cm = getColorModel(transparency);
if (cm == null) {
throw new IllegalArgumentException("Unknown transparency: " +
transparency);
}
WritableRaster wr = cm.createCompatibleWritableRaster(width, height);
return new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null);
}
/**
* Returns a {@link VolatileImage} with a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>.
* The returned <code>VolatileImage</code>
* may have data that is stored optimally for the underlying graphics
* device and may therefore benefit from platform-specific rendering
* acceleration.
* @param width the width of the returned <code>VolatileImage</code>
* @param height the height of the returned <code>VolatileImage</code>
* @return a <code>VolatileImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>.
* @see Component#createVolatileImage(int, int)
* @since 1.4
*/
public VolatileImage createCompatibleVolatileImage(int width, int height) {
VolatileImage vi = null;
try {
vi = createCompatibleVolatileImage(width, height,
null, Transparency.OPAQUE);
} catch (AWTException e) {
// shouldn't happen: we're passing in null caps
assert false;
}
return vi;
}
/**
* Returns a {@link VolatileImage} with a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>.
* The returned <code>VolatileImage</code>
* may have data that is stored optimally for the underlying graphics
* device and may therefore benefit from platform-specific rendering
* acceleration.
* @param width the width of the returned <code>VolatileImage</code>
* @param height the height of the returned <code>VolatileImage</code>
* @param transparency the specified transparency mode
* @return a <code>VolatileImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>.
* @throws IllegalArgumentException if the transparency is not a valid value
* @see Transparency#OPAQUE
* @see Transparency#BITMASK
* @see Transparency#TRANSLUCENT
* @see Component#createVolatileImage(int, int)
* @since 1.5
*/
public VolatileImage createCompatibleVolatileImage(int width, int height,
int transparency)
{
VolatileImage vi = null;
try {
vi = createCompatibleVolatileImage(width, height, null, transparency);
} catch (AWTException e) {
// shouldn't happen: we're passing in null caps
assert false;
}
return vi;
}
/**
* Returns a {@link VolatileImage} with a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>, using
* the specified image capabilities.
* If the <code>caps</code> parameter is null, it is effectively ignored
* and this method will create a VolatileImage without regard to
* <code>ImageCapabilities</code> constraints.
*
* The returned <code>VolatileImage</code> has
* a layout and color model that is closest to this native device
* configuration and can therefore be optimally blitted to this
* device.
* @return a <code>VolatileImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>.
* @param width the width of the returned <code>VolatileImage</code>
* @param height the height of the returned <code>VolatileImage</code>
* @param caps the image capabilities
* @exception AWTException if the supplied image capabilities could not
* be met by this graphics configuration
* @since 1.4
*/
public VolatileImage createCompatibleVolatileImage(int width, int height,
ImageCapabilities caps) throws AWTException
{
return createCompatibleVolatileImage(width, height, caps,
Transparency.OPAQUE);
}
/**
* Returns a {@link VolatileImage} with a data layout and color model
* compatible with this <code>GraphicsConfiguration</code>, using
* the specified image capabilities and transparency value.
* If the <code>caps</code> parameter is null, it is effectively ignored
* and this method will create a VolatileImage without regard to
* <code>ImageCapabilities</code> constraints.
*
* The returned <code>VolatileImage</code> has
* a layout and color model that is closest to this native device
* configuration and can therefore be optimally blitted to this
* device.
* @param width the width of the returned <code>VolatileImage</code>
* @param height the height of the returned <code>VolatileImage</code>
* @param caps the image capabilities
* @param transparency the specified transparency mode
* @return a <code>VolatileImage</code> whose data layout and color
* model is compatible with this <code>GraphicsConfiguration</code>.
* @see Transparency#OPAQUE
* @see Transparency#BITMASK
* @see Transparency#TRANSLUCENT
* @throws IllegalArgumentException if the transparency is not a valid value
* @exception AWTException if the supplied image capabilities could not
* be met by this graphics configuration
* @see Component#createVolatileImage(int, int)
* @since 1.5
*/
public VolatileImage createCompatibleVolatileImage(int width, int height,
ImageCapabilities caps, int transparency) throws AWTException
{
VolatileImage vi =
new Container().createVolatileImage(width, height, caps);
if (caps != null && caps.isAccelerated() &&
!vi.getCapabilities().isAccelerated())
{
throw new AWTException("Supplied image capabilities could not " +
"be met by this graphics configuration.");
}
return vi;
}
/**
* Returns the {@link ColorModel} associated with this
* <code>GraphicsConfiguration</code>.
* @return a <code>ColorModel</code> object that is associated with
* this <code>GraphicsConfiguration</code>.
*/
public abstract ColorModel getColorModel();
/**
* Returns the <code>ColorModel</code> associated with this
* <code>GraphicsConfiguration</code> that supports the specified
* transparency.
* @param transparency the specified transparency mode
* @return a <code>ColorModel</code> object that is associated with
* this <code>GraphicsConfiguration</code> and supports the
* specified transparency or null if the transparency is not a valid
* value.
* @see Transparency#OPAQUE
* @see Transparency#BITMASK
* @see Transparency#TRANSLUCENT
*/
public abstract ColorModel getColorModel(int transparency);
/**
* Returns the default {@link AffineTransform} for this
* <code>GraphicsConfiguration</code>. This
* <code>AffineTransform</code> is typically the Identity transform
* for most normal screens. The default <code>AffineTransform</code>
* maps coordinates onto the device such that 72 user space
* coordinate units measure approximately 1 inch in device
* space. The normalizing transform can be used to make
* this mapping more exact. Coordinates in the coordinate space
* defined by the default <code>AffineTransform</code> for screen and
* printer devices have the origin in the upper left-hand corner of
* the target region of the device, with X coordinates
* increasing to the right and Y coordinates increasing downwards.
* For image buffers not associated with a device, such as those not
* created by <code>createCompatibleImage</code>,
* this <code>AffineTransform</code> is the Identity transform.
* @return the default <code>AffineTransform</code> for this
* <code>GraphicsConfiguration</code>.
*/
public abstract AffineTransform getDefaultTransform();
/**
*
* Returns a <code>AffineTransform</code> that can be concatenated
* with the default <code>AffineTransform</code>
* of a <code>GraphicsConfiguration</code> so that 72 units in user
* space equals 1 inch in device space.
* <p>
* For a particular {@link Graphics2D}, g, one
* can reset the transformation to create
* such a mapping by using the following pseudocode:
* <pre>
* GraphicsConfiguration gc = g.getDeviceConfiguration();
*
* g.setTransform(gc.getDefaultTransform());
* g.transform(gc.getNormalizingTransform());
* </pre>
* Note that sometimes this <code>AffineTransform</code> is identity,
* such as for printers or metafile output, and that this
* <code>AffineTransform</code> is only as accurate as the information
* supplied by the underlying system. For image buffers not
* associated with a device, such as those not created by
* <code>createCompatibleImage</code>, this
* <code>AffineTransform</code> is the Identity transform
* since there is no valid distance measurement.
* @return an <code>AffineTransform</code> to concatenate to the
* default <code>AffineTransform</code> so that 72 units in user
* space is mapped to 1 inch in device space.
*/
public abstract AffineTransform getNormalizingTransform();
/**
* Returns the bounds of the <code>GraphicsConfiguration</code>
* in the device coordinates. In a multi-screen environment
* with a virtual device, the bounds can have negative X
* or Y origins.
* @return the bounds of the area covered by this
* <code>GraphicsConfiguration</code>.
* @since 1.3
*/
public abstract Rectangle getBounds();
private static class DefaultBufferCapabilities extends BufferCapabilities {
public DefaultBufferCapabilities(ImageCapabilities imageCaps) {
super(imageCaps, imageCaps, null);
}
}
/**
* Returns the buffering capabilities of this
* <code>GraphicsConfiguration</code>.
* @return the buffering capabilities of this graphics
* configuration object
* @since 1.4
*/
public BufferCapabilities getBufferCapabilities() {
if (defaultBufferCaps == null) {
defaultBufferCaps = new DefaultBufferCapabilities(
getImageCapabilities());
}
return defaultBufferCaps;
}
/**
* Returns the image capabilities of this
* <code>GraphicsConfiguration</code>.
* @return the image capabilities of this graphics
* configuration object
* @since 1.4
*/
public ImageCapabilities getImageCapabilities() {
if (defaultImageCaps == null) {
defaultImageCaps = new ImageCapabilities(false);
}
return defaultImageCaps;
}
/**
* Returns whether this {@code GraphicsConfiguration} supports
* the {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
* PERPIXEL_TRANSLUCENT} kind of translucency.
*
* @return whether the given GraphicsConfiguration supports
* the translucency effects.
*
* @see Window#setBackground(Color)
*
* @since 1.7
*/
public boolean isTranslucencyCapable() {
// Overridden in subclasses
return false;
}
}

View File

@@ -0,0 +1,353 @@
/*
* Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.ImageProducer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.ReplicateScaleFilter;
//import sun.awt.image.SurfaceManager;
/**
* The abstract class <code>Image</code> is the superclass of all
* classes that represent graphical images. The image must be
* obtained in a platform-specific manner.
*
* @author Sami Shaio
* @author Arthur van Hoff
* @since JDK1.0
*/
public abstract class Image {
/**
* convenience object; we can use this single static object for
* all images that do not create their own image caps; it holds the
* default (unaccelerated) properties.
*/
private static ImageCapabilities defaultImageCaps =
new ImageCapabilities(false);
/**
* Priority for accelerating this image. Subclasses are free to
* set different default priorities and applications are free to
* set the priority for specific images via the
* <code>setAccelerationPriority(float)</code> method.
* @since 1.5
*/
protected float accelerationPriority = .5f;
/**
* Determines the width of the image. If the width is not yet known,
* this method returns <code>-1</code> and the specified
* <code>ImageObserver</code> object is notified later.
* @param observer an object waiting for the image to be loaded.
* @return the width of this image, or <code>-1</code>
* if the width is not yet known.
* @see java.awt.Image#getHeight
* @see java.awt.image.ImageObserver
*/
public abstract int getWidth(ImageObserver observer);
/**
* Determines the height of the image. If the height is not yet known,
* this method returns <code>-1</code> and the specified
* <code>ImageObserver</code> object is notified later.
* @param observer an object waiting for the image to be loaded.
* @return the height of this image, or <code>-1</code>
* if the height is not yet known.
* @see java.awt.Image#getWidth
* @see java.awt.image.ImageObserver
*/
public abstract int getHeight(ImageObserver observer);
/**
* Gets the object that produces the pixels for the image.
* This method is called by the image filtering classes and by
* methods that perform image conversion and scaling.
* @return the image producer that produces the pixels
* for this image.
* @see java.awt.image.ImageProducer
*/
public abstract ImageProducer getSource();
/**
* Creates a graphics context for drawing to an off-screen image.
* This method can only be called for off-screen images.
* @return a graphics context to draw to the off-screen image.
* @exception UnsupportedOperationException if called for a
* non-off-screen image.
* @see java.awt.Graphics
* @see java.awt.Component#createImage(int, int)
*/
public abstract Graphics getGraphics();
/**
* Gets a property of this image by name.
* <p>
* Individual property names are defined by the various image
* formats. If a property is not defined for a particular image, this
* method returns the <code>UndefinedProperty</code> object.
* <p>
* If the properties for this image are not yet known, this method
* returns <code>null</code>, and the <code>ImageObserver</code>
* object is notified later.
* <p>
* The property name <code>"comment"</code> should be used to store
* an optional comment which can be presented to the application as a
* description of the image, its source, or its author.
* @param name a property name.
* @param observer an object waiting for this image to be loaded.
* @return the value of the named property.
* @throws <code>NullPointerException</code> if the property name is null.
* @see java.awt.image.ImageObserver
* @see java.awt.Image#UndefinedProperty
*/
public abstract Object getProperty(String name, ImageObserver observer);
/**
* The <code>UndefinedProperty</code> object should be returned whenever a
* property which was not defined for a particular image is fetched.
*/
public static final Object UndefinedProperty = new Object();
/**
* Creates a scaled version of this image.
* A new <code>Image</code> object is returned which will render
* the image at the specified <code>width</code> and
* <code>height</code> by default. The new <code>Image</code> object
* may be loaded asynchronously even if the original source image
* has already been loaded completely.
*
* <p>
*
* If either <code>width</code>
* or <code>height</code> is a negative number then a value is
* substituted to maintain the aspect ratio of the original image
* dimensions. If both <code>width</code> and <code>height</code>
* are negative, then the original image dimensions are used.
*
* @param width the width to which to scale the image.
* @param height the height to which to scale the image.
* @param hints flags to indicate the type of algorithm to use
* for image resampling.
* @return a scaled version of the image.
* @exception IllegalArgumentException if <code>width</code>
* or <code>height</code> is zero.
* @see java.awt.Image#SCALE_DEFAULT
* @see java.awt.Image#SCALE_FAST
* @see java.awt.Image#SCALE_SMOOTH
* @see java.awt.Image#SCALE_REPLICATE
* @see java.awt.Image#SCALE_AREA_AVERAGING
* @since JDK1.1
*/
public Image getScaledInstance(int width, int height, int hints) {
ImageFilter filter;
if ((hints & (SCALE_SMOOTH | SCALE_AREA_AVERAGING)) != 0) {
filter = new AreaAveragingScaleFilter(width, height);
} else {
filter = new ReplicateScaleFilter(width, height);
}
ImageProducer prod;
prod = new FilteredImageSource(getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(prod);
}
/**
* Use the default image-scaling algorithm.
* @since JDK1.1
*/
public static final int SCALE_DEFAULT = 1;
/**
* Choose an image-scaling algorithm that gives higher priority
* to scaling speed than smoothness of the scaled image.
* @since JDK1.1
*/
public static final int SCALE_FAST = 2;
/**
* Choose an image-scaling algorithm that gives higher priority
* to image smoothness than scaling speed.
* @since JDK1.1
*/
public static final int SCALE_SMOOTH = 4;
/**
* Use the image scaling algorithm embodied in the
* <code>ReplicateScaleFilter</code> class.
* The <code>Image</code> object is free to substitute a different filter
* that performs the same algorithm yet integrates more efficiently
* into the imaging infrastructure supplied by the toolkit.
* @see java.awt.image.ReplicateScaleFilter
* @since JDK1.1
*/
public static final int SCALE_REPLICATE = 8;
/**
* Use the Area Averaging image scaling algorithm. The
* image object is free to substitute a different filter that
* performs the same algorithm yet integrates more efficiently
* into the image infrastructure supplied by the toolkit.
* @see java.awt.image.AreaAveragingScaleFilter
* @since JDK1.1
*/
public static final int SCALE_AREA_AVERAGING = 16;
/**
* Flushes all reconstructable resources being used by this Image object.
* This includes any pixel data that is being cached for rendering to
* the screen as well as any system resources that are being used
* to store data or pixels for the image if they can be recreated.
* The image is reset to a state similar to when it was first created
* so that if it is again rendered, the image data will have to be
* recreated or fetched again from its source.
* <p>
* Examples of how this method affects specific types of Image object:
* <ul>
* <li>
* BufferedImage objects leave the primary Raster which stores their
* pixels untouched, but flush any information cached about those
* pixels such as copies uploaded to the display hardware for
* accelerated blits.
* <li>
* Image objects created by the Component methods which take a
* width and height leave their primary buffer of pixels untouched,
* but have all cached information released much like is done for
* BufferedImage objects.
* <li>
* VolatileImage objects release all of their pixel resources
* including their primary copy which is typically stored on
* the display hardware where resources are scarce.
* These objects can later be restored using their
* {@link java.awt.image.VolatileImage#validate validate}
* method.
* <li>
* Image objects created by the Toolkit and Component classes which are
* loaded from files, URLs or produced by an {@link ImageProducer}
* are unloaded and all local resources are released.
* These objects can later be reloaded from their original source
* as needed when they are rendered, just as when they were first
* created.
* </ul>
*/
public void flush() {
// if (surfaceManager != null) {
// surfaceManager.flush();
// }
}
/**
* Returns an ImageCapabilities object which can be
* inquired as to the capabilities of this
* Image on the specified GraphicsConfiguration.
* This allows programmers to find
* out more runtime information on the specific Image
* object that they have created. For example, the user
* might create a BufferedImage but the system may have
* no video memory left for creating an image of that
* size on the given GraphicsConfiguration, so although the object
* may be acceleratable in general, it
* does not have that capability on this GraphicsConfiguration.
* @param gc a <code>GraphicsConfiguration</code> object. A value of null
* for this parameter will result in getting the image capabilities
* for the default <code>GraphicsConfiguration</code>.
* @return an <code>ImageCapabilities</code> object that contains
* the capabilities of this <code>Image</code> on the specified
* GraphicsConfiguration.
* @see java.awt.image.VolatileImage#getCapabilities()
* VolatileImage.getCapabilities()
* @since 1.5
*/
public ImageCapabilities getCapabilities(GraphicsConfiguration gc) {
// if (surfaceManager != null) {
// return surfaceManager.getCapabilities(gc);
// }
// Note: this is just a default object that gets returned in the
// absence of any more specific information from a surfaceManager.
// Subclasses of Image should either override this method or
// make sure that they always have a non-null SurfaceManager
// to return an ImageCapabilities object that is appropriate
// for their given subclass type.
return defaultImageCaps;
}
/**
* Sets a hint for this image about how important acceleration is.
* This priority hint is used to compare to the priorities of other
* Image objects when determining how to use scarce acceleration
* resources such as video memory. When and if it is possible to
* accelerate this Image, if there are not enough resources available
* to provide that acceleration but enough can be freed up by
* de-accelerating some other image of lower priority, then that other
* Image may be de-accelerated in deference to this one. Images
* that have the same priority take up resources on a first-come,
* first-served basis.
* @param priority a value between 0 and 1, inclusive, where higher
* values indicate more importance for acceleration. A value of 0
* means that this Image should never be accelerated. Other values
* are used simply to determine acceleration priority relative to other
* Images.
* @throws IllegalArgumentException if <code>priority</code> is less
* than zero or greater than 1.
* @since 1.5
*/
public void setAccelerationPriority(float priority) {
if (priority < 0 || priority > 1) {
throw new IllegalArgumentException("Priority must be a value " +
"between 0 and 1, inclusive");
}
accelerationPriority = priority;
// if (surfaceManager != null) {
// surfaceManager.setAccelerationPriority(accelerationPriority);
// }
}
/**
* Returns the current value of the acceleration priority hint.
* @see #setAccelerationPriority(float priority) setAccelerationPriority
* @return value between 0 and 1, inclusive, which represents the current
* priority value
* @since 1.5
*/
public float getAccelerationPriority() {
return accelerationPriority;
}
// SurfaceManager surfaceManager;
//
// static {
// SurfaceManager.setImageAccessor(new SurfaceManager.ImageAccessor() {
// public SurfaceManager getSurfaceManager(Image img) {
// return img.surfaceManager;
// }
// public void setSurfaceManager(Image img, SurfaceManager mgr) {
// img.surfaceManager = mgr;
// }
// });
// }
}

View File

@@ -0,0 +1,295 @@
/* ICC_ColorSpace.java -- the canonical color space implementation
Copyright (C) 2000, 2002, 2004 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt.color;
import gnu.java.awt.color.CieXyzConverter;
import gnu.java.awt.color.ClutProfileConverter;
import gnu.java.awt.color.ColorSpaceConverter;
import gnu.java.awt.color.GrayProfileConverter;
import gnu.java.awt.color.GrayScaleConverter;
import gnu.java.awt.color.RgbProfileConverter;
import gnu.java.awt.color.SrgbConverter;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* ICC_ColorSpace - an implementation of ColorSpace
*
* While an ICC_Profile class abstracts the data in an ICC profile file
* an ICC_ColorSpace performs the color space conversions defined by
* an ICC_Profile instance.
*
* Typically, an ICC_Profile will either be created using getInstance,
* either from the built-in colorspaces, or from an ICC profile file.
* Then a ICC_Colorspace will be used to perform transforms from the
* device colorspace to and from the profile color space.
*
* The PCS used by ColorSpace is CIE XYZ relative a D50 white point.
* (Profiles using a CIE Lab PCS will have their input and output converted
* to D50 CIE XYZ accordingly.
*
* Note that a valid profile may not contain transforms in both directions,
* in which case the output may be undefined.
* All built-in colorspaces have bidirectional transforms, but developers
* using an ICC profile file may want to check the profile class using
* the ICC_Profile.getProfileClass() method. Input class profiles are
* guaranteed to have transforms to the PCS, output class profiles are
* guaranteed to have transforms from the PCS to device space.
*
* @author Sven de Marothy
* @author Rolf W. Rasmussen (rolfwr@ii.uib.no)
* @since 1.2
*/
public class ICC_ColorSpace extends ColorSpace
{
/**
* Compatible with JDK 1.2+.
*/
private static final long serialVersionUID = 3455889114070431483L;
/**
* @serial
*/
private ICC_Profile thisProfile;
/**
* @serial
*/
private float[] minVal;
/**
* @serial
*/
private float[] maxVal;
/**
* @serial
*/
private float[] diffMinMax;
/**
* @serial
*/
private float[] invDiffMinMax;
/**
* @serial
*/
private boolean needScaleInit;
/**
* Tells us if the PCS is CIE LAB (must be CIEXYZ otherwise)
*/
private transient int type;
private transient int nComponents;
private transient ColorSpaceConverter converter;
/**
* Constructs a new ICC_ColorSpace from an ICC_Profile object.
*
* @exception IllegalArgumentException If profile is inappropriate for
* representing a ColorSpace.
*/
public ICC_ColorSpace(ICC_Profile profile)
{
super(profile.getColorSpaceType(), profile.getNumComponents());
converter = getConverter(profile);
thisProfile = profile;
nComponents = profile.getNumComponents();
type = profile.getColorSpaceType();
makeArrays();
}
/**
* Return the profile
*/
public ICC_Profile getProfile()
{
return thisProfile;
}
/**
* Transforms a color value assumed to be in this ColorSpace into a value in
* the default CS_sRGB color space.
*
* @exception ArrayIndexOutOfBoundsException If array length is not at least
* the number of components in this ColorSpace.
*/
public float[] toRGB(float[] colorvalue)
{
return converter.toRGB(colorvalue);
}
/**
* Transforms a color value assumed to be in the default CS_sRGB color space
* into this ColorSpace.
*
* @exception ArrayIndexOutOfBoundsException If array length is not at
* least 3.
*/
public float[] fromRGB(float[] rgbvalue)
{
return converter.fromRGB(rgbvalue);
}
/**
* Transforms a color value assumed to be in this ColorSpace into the
* CS_CIEXYZ conversion color space.
*
* @exception ArrayIndexOutOfBoundsException If array length is not at
* least the number of components in this ColorSpace.
*/
public float[] toCIEXYZ(float[] colorvalue)
{
return converter.toCIEXYZ(colorvalue);
}
/**
* Transforms a color value assumed to be in the CS_CIEXYZ conversion color
* space into this ColorSpace.
*
* @exception ArrayIndexOutOfBoundsException If array length is not at
* least 3.
*/
public float[] fromCIEXYZ(float[] colorvalue)
{
return converter.fromCIEXYZ(colorvalue);
}
/**
* Returns the minimum normalized color component value for the specified
* component.
*
* @exception IllegalArgumentException If component is less than 0 or greater
* than numComponents - 1.
*
* @since 1.4
*/
public float getMinValue(int idx)
{
// FIXME: Not 100% certain of this.
if (type == ColorSpace.TYPE_Lab && (idx == 1 || idx == 2))
return -128f;
if (idx < 0 || idx >= nComponents)
throw new IllegalArgumentException();
return 0;
}
/**
* Returns the maximum normalized color component value for the specified
* component.
*
* @exception IllegalArgumentException If component is less than 0 or greater
* than numComponents - 1.
*
* @since 1.4
*/
public float getMaxValue(int idx)
{
if (type == ColorSpace.TYPE_XYZ && idx >= 0 && idx <= 2)
return 1 + 32767 / 32768f;
else if (type == ColorSpace.TYPE_Lab)
{
if (idx == 0)
return 100;
if (idx == 1 || idx == 2)
return 127;
}
if (idx < 0 || idx >= nComponents)
throw new IllegalArgumentException();
return 1;
}
/**
* Returns a colorspace converter suitable for a given profile
*/
private ColorSpaceConverter getConverter(ICC_Profile profile)
{
ColorSpaceConverter converter;
switch (profile.getColorSpaceType())
{
case TYPE_XYZ:
converter = new CieXyzConverter();
break;
default:
if (profile instanceof ICC_ProfileRGB)
converter = new RgbProfileConverter((ICC_ProfileRGB) profile);
else if (profile instanceof ICC_ProfileGray)
converter = new GrayProfileConverter((ICC_ProfileGray) profile);
else
converter = new ClutProfileConverter(profile);
break;
}
return converter;
}
/**
* Serialization compatibility requires these variable to be set,
* although we don't use them. Perhaps we should?
*/
private void makeArrays()
{
minVal = new float[nComponents];
maxVal = new float[nComponents];
invDiffMinMax = diffMinMax = null;
for (int i = 0; i < nComponents; i++)
{
minVal[i] = getMinValue(i);
maxVal[i] = getMaxValue(i);
}
needScaleInit = true;
}
/**
* Deserializes the object
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
// set up objects
converter = getConverter(thisProfile);
nComponents = thisProfile.getNumComponents();
type = thisProfile.getColorSpaceType();
}
} // class ICC_ColorSpace

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,218 @@
/* BandCombineOp.java - perform a combination on the bands of a raster
Copyright (C) 2004, 2006 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt.image;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
/**
* Filter Raster pixels by applying a matrix.
*
* BandCombineOp applies a matrix to each pixel to produce new pixel values.
* The width of the matrix must be the same or one more than the number of
* bands in the source Raster. If one more, the pixels in the source are
* assumed to contain an implicit 1.0 at the end.
*
* The rows of the matrix are multiplied by the pixel to produce the values
* for the destination. Therefore the destination Raster must contain the
* same number of bands as the number of rows in the filter matrix.
*
* This Op assumes that samples are integers; floating point sample types will
* be rounded to their nearest integer value during filtering.
*
* @author Jerry Quinn (jlquinn@optonline.net)
*/
public class BandCombineOp implements RasterOp
{
private RenderingHints hints;
private float[][] matrix;
/**
* Construct a BandCombineOp.
*
* @param matrix The matrix to filter pixels with.
* @param hints Rendering hints to apply. Ignored.
* @throws ArrayIndexOutOfBoundsException if the matrix is invalid
*/
public BandCombineOp(float[][] matrix, RenderingHints hints)
{
this.matrix = new float[matrix.length][];
int width = matrix[0].length;
for (int i = 0; i < matrix.length; i++)
{
this.matrix[i] = new float[width + 1];
for (int j = 0; j < width; j++)
this.matrix[i][j] = matrix[i][j];
// The reference implementation pads the array with a trailing zero...
this.matrix[i][width] = 0;
}
this.hints = hints;
}
/**
* Filter Raster pixels through a matrix. Applies the Op matrix to source
* pixes to produce dest pixels. Each row of the matrix is multiplied by the
* src pixel components to produce the dest pixel. If matrix is one more than
* the number of bands in the src, the last element is implicitly multiplied
* by 1, i.e. added to the sum for that dest component. If dest is null, a
* suitable Raster is created. This implementation uses
* createCompatibleDestRaster.
*
* @param src The source Raster.
* @param dest The destination Raster, or null.
* @throws IllegalArgumentException if the destination raster is incompatible
* with the source raster.
* @return The filtered Raster.
* @see java.awt.image.RasterOp#filter(java.awt.image.Raster,
* java.awt.image.WritableRaster)
*/
public WritableRaster filter(Raster src, WritableRaster dest) {
if (dest == null)
dest = createCompatibleDestRaster(src);
else if (dest.getNumBands() != src.getNumBands()
|| dest.getTransferType() != src.getTransferType())
throw new IllegalArgumentException("Destination raster is incompatible with source raster");
// Filter the pixels
int[] spix = new int[matrix[0].length - 1];
int[] spix2 = new int[matrix[0].length - 1];
int[] dpix = new int[matrix.length];
for (int y = src.getMinY(); y < src.getHeight() + src.getMinY(); y++)
for (int x = src.getMinX(); x < src.getWidth() + src.getMinX(); x++)
{
// In case matrix rows have implicit translation
spix[spix.length - 1] = 1;
src.getPixel(x, y, spix);
// Do not re-calculate if pixel is identical to the last one
// (ie, blocks of the same colour)
if (!Arrays.equals(spix, spix2))
{
System.arraycopy(spix, 0, spix2, 0, spix.length);
for (int i = 0; i < matrix.length; i++)
{
dpix[i] = 0;
for (int j = 0; j < matrix[0].length - 1; j++)
dpix[i] += spix[j] * (int)matrix[i][j];
}
}
dest.setPixel(x, y, dpix);
}
return dest;
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getBounds2D(java.awt.image.Raster)
*/
public final Rectangle2D getBounds2D(Raster src)
{
return src.getBounds();
}
/**
* Creates a new WritableRaster that can be used as the destination for this
* Op. The number of bands in the source raster must equal the number of rows
* in the op matrix, which must also be equal to either the number of columns
* or (columns - 1) in the matrix.
*
* @param src The source raster.
* @return A compatible raster.
* @see java.awt.image.RasterOp#createCompatibleDestRaster(java.awt.image.Raster)
* @throws IllegalArgumentException if the raster is incompatible with the
* matrix.
*/
public WritableRaster createCompatibleDestRaster(Raster src)
{
// Destination raster must have same number of bands as source
if (src.getNumBands() != matrix.length)
throw new IllegalArgumentException("Number of rows in matrix specifies an "
+ "incompatible number of bands");
// We use -1 and -2 because we previously padded the rows with a trailing 0
if (src.getNumBands() != matrix[0].length - 1
&& src.getNumBands() != matrix[0].length - 2)
throw new IllegalArgumentException("Incompatible number of bands: "
+ "the number of bands in the raster must equal the number of "
+ "columns in the matrix, optionally minus one");
return src.createCompatibleWritableRaster();
}
/**
* Return corresponding destination point for source point. Because this is
* not a geometric operation, it simply returns a copy of the source.
*
* @param src The source point.
* @param dst The destination point.
* @return dst The destination point.
* @see java.awt.image.RasterOp#getPoint2D(java.awt.geom.Point2D,
*java.awt.geom.Point2D)
*/
public final Point2D getPoint2D(Point2D src, Point2D dst)
{
if (dst == null)
return (Point2D)src.clone();
dst.setLocation(src);
return dst;
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getRenderingHints()
*/
public final RenderingHints getRenderingHints()
{
return hints;
}
/**
* Return the matrix used in this operation.
*
* @return The matrix used in this operation.
*/
public final float[][] getMatrix()
{
return matrix;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,380 @@
/* ConvolveOp.java --
Copyright (C) 2004, 2005, 2006, Free Software Foundation -- ConvolveOp
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt.image;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* Convolution filter.
*
* ConvolveOp convolves the source image with a Kernel to generate a
* destination image. This involves multiplying each pixel and its neighbors
* with elements in the kernel to compute a new pixel.
*
* Each band in a Raster is convolved and copied to the destination Raster.
* For BufferedImages, convolution is applied to all components. Color
* conversion will be applied if needed.
*
* Note that this filter ignores whether the source or destination is alpha
* premultiplied. The reference spec states that data will be premultiplied
* prior to convolving and divided back out afterwards (if needed), but testing
* has shown that this is not the case with their implementation.
*
* @author jlquinn@optonline.net
*/
public class ConvolveOp implements BufferedImageOp, RasterOp
{
/** Edge pixels are set to 0. */
public static final int EDGE_ZERO_FILL = 0;
/** Edge pixels are copied from the source. */
public static final int EDGE_NO_OP = 1;
private Kernel kernel;
private int edge;
private RenderingHints hints;
/**
* Construct a ConvolveOp.
*
* The edge condition specifies that pixels outside the area that can be
* filtered are either set to 0 or copied from the source image.
*
* @param kernel The kernel to convolve with.
* @param edgeCondition Either EDGE_ZERO_FILL or EDGE_NO_OP.
* @param hints Rendering hints for color conversion, or null.
*/
public ConvolveOp(Kernel kernel,
int edgeCondition,
RenderingHints hints)
{
this.kernel = kernel;
edge = edgeCondition;
this.hints = hints;
}
/**
* Construct a ConvolveOp.
*
* The edge condition defaults to EDGE_ZERO_FILL.
*
* @param kernel The kernel to convolve with.
*/
public ConvolveOp(Kernel kernel)
{
this.kernel = kernel;
edge = EDGE_ZERO_FILL;
hints = null;
}
/**
* Converts the source image using the kernel specified in the
* constructor. The resulting image is stored in the destination image if one
* is provided; otherwise a new BufferedImage is created and returned.
*
* The source and destination BufferedImage (if one is supplied) must have
* the same dimensions.
*
* @param src The source image.
* @param dst The destination image.
* @throws IllegalArgumentException if the rasters and/or color spaces are
* incompatible.
* @return The convolved image.
*/
public final BufferedImage filter(BufferedImage src, BufferedImage dst)
{
if (src == dst)
throw new IllegalArgumentException("Source and destination images " +
"cannot be the same.");
if (dst == null)
dst = createCompatibleDestImage(src, src.getColorModel());
// Make sure source image is premultiplied
BufferedImage src1 = src;
// The spec says we should do this, but mauve testing shows that Sun's
// implementation does not check this.
/*
if (!src.isAlphaPremultiplied())
{
src1 = createCompatibleDestImage(src, src.getColorModel());
src.copyData(src1.getRaster());
src1.coerceData(true);
}
*/
BufferedImage dst1 = dst;
if (src1.getColorModel().getColorSpace().getType() != dst.getColorModel().getColorSpace().getType())
dst1 = createCompatibleDestImage(src, src.getColorModel());
filter(src1.getRaster(), dst1.getRaster());
// Since we don't coerceData above, we don't need to divide it back out.
// This is wrong (one mauve test specifically tests converting a non-
// premultiplied image to a premultiplied image, and it shows that Sun
// simply ignores the premultipled flag, contrary to the spec), but we
// mimic it for compatibility.
/*
if (! dst.isAlphaPremultiplied())
dst1.coerceData(false);
*/
// Convert between color models if needed
if (dst1 != dst)
new ColorConvertOp(hints).filter(dst1, dst);
return dst;
}
/**
* Creates an empty BufferedImage with the size equal to the source and the
* correct number of bands. The new image is created with the specified
* ColorModel, or if no ColorModel is supplied, an appropriate one is chosen.
*
* @param src The source image.
* @param dstCM A color model for the destination image (may be null).
* @return The new compatible destination image.
*/
public BufferedImage createCompatibleDestImage(BufferedImage src,
ColorModel dstCM)
{
if (dstCM != null)
return new BufferedImage(dstCM,
src.getRaster().createCompatibleWritableRaster(),
src.isAlphaPremultiplied(), null);
return new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getRenderingHints()
*/
public final RenderingHints getRenderingHints()
{
return hints;
}
/**
* Get the edge condition for this Op.
*
* @return The edge condition.
*/
public int getEdgeCondition()
{
return edge;
}
/**
* Returns (a clone of) the convolution kernel.
*
* @return The convolution kernel.
*/
public final Kernel getKernel()
{
return (Kernel) kernel.clone();
}
/**
* Converts the source raster using the kernel specified in the constructor.
* The resulting raster is stored in the destination raster if one is
* provided; otherwise a new WritableRaster is created and returned.
*
* If the convolved value for a sample is outside the range of [0-255], it
* will be clipped.
*
* The source and destination raster (if one is supplied) cannot be the same,
* and must also have the same dimensions.
*
* @param src The source raster.
* @param dest The destination raster.
* @throws IllegalArgumentException if the rasters identical.
* @throws ImagingOpException if the convolution is not possible.
* @return The transformed raster.
*/
public final WritableRaster filter(Raster src, WritableRaster dest)
{
if (src == dest)
throw new IllegalArgumentException("src == dest is not allowed.");
if (kernel.getWidth() > src.getWidth()
|| kernel.getHeight() > src.getHeight())
throw new ImagingOpException("The kernel is too large.");
if (dest == null)
dest = createCompatibleDestRaster(src);
else if (src.getNumBands() != dest.getNumBands())
throw new ImagingOpException("src and dest have different band counts.");
// calculate the borders that the op can't reach...
int kWidth = kernel.getWidth();
int kHeight = kernel.getHeight();
int left = kernel.getXOrigin();
int right = Math.max(kWidth - left - 1, 0);
int top = kernel.getYOrigin();
int bottom = Math.max(kHeight - top - 1, 0);
// Calculate max sample values for clipping
int[] maxValue = src.getSampleModel().getSampleSize();
for (int i = 0; i < maxValue.length; i++)
maxValue[i] = (int)Math.pow(2, maxValue[i]) - 1;
// process the region that is reachable...
int regionW = src.width - left - right;
int regionH = src.height - top - bottom;
float[] kvals = kernel.getKernelData(null);
float[] tmp = new float[kWidth * kHeight];
for (int x = 0; x < regionW; x++)
{
for (int y = 0; y < regionH; y++)
{
// FIXME: This needs a much more efficient implementation
for (int b = 0; b < src.getNumBands(); b++)
{
float v = 0;
src.getSamples(x, y, kWidth, kHeight, b, tmp);
for (int i = 0; i < tmp.length; i++)
v += tmp[tmp.length - i - 1] * kvals[i];
// FIXME: in the above line, I've had to reverse the order of
// the samples array to make the tests pass. I haven't worked
// out why this is necessary.
// This clipping is is undocumented, but determined by testing.
if (v > maxValue[b])
v = maxValue[b];
else if (v < 0)
v = 0;
dest.setSample(x + kernel.getXOrigin(), y + kernel.getYOrigin(),
b, v);
}
}
}
// fill in the top border
fillEdge(src, dest, 0, 0, src.width, top, edge);
// fill in the bottom border
fillEdge(src, dest, 0, src.height - bottom, src.width, bottom, edge);
// fill in the left border
fillEdge(src, dest, 0, top, left, regionH, edge);
// fill in the right border
fillEdge(src, dest, src.width - right, top, right, regionH, edge);
return dest;
}
/**
* Fills a range of pixels (typically at the edge of a raster) with either
* zero values (if <code>edgeOp</code> is <code>EDGE_ZERO_FILL</code>) or the
* corresponding pixel values from the source raster (if <code>edgeOp</code>
* is <code>EDGE_NO_OP</code>). This utility method is called by the
* {@link #fillEdge(Raster, WritableRaster, int, int, int, int, int)} method.
*
* @param src the source raster.
* @param dest the destination raster.
* @param x the x-coordinate of the top left pixel in the range.
* @param y the y-coordinate of the top left pixel in the range.
* @param w the width of the pixel range.
* @param h the height of the pixel range.
* @param edgeOp indicates how to determine the values for the range
* (either {@link #EDGE_ZERO_FILL} or {@link #EDGE_NO_OP}).
*/
private void fillEdge(Raster src, WritableRaster dest, int x, int y, int w,
int h, int edgeOp)
{
if (w <= 0)
return;
if (h <= 0)
return;
if (edgeOp == EDGE_ZERO_FILL) // fill region with zeroes
{
float[] zeros = new float[src.getNumBands() * w * h];
dest.setPixels(x, y, w, h, zeros);
}
else // copy pixels from source
{
float[] pixels = new float[src.getNumBands() * w * h];
src.getPixels(x, y, w, h, pixels);
dest.setPixels(x, y, w, h, pixels);
}
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#createCompatibleDestRaster(java.awt.image.Raster)
*/
public WritableRaster createCompatibleDestRaster(Raster src)
{
return src.createCompatibleWritableRaster();
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#getBounds2D(java.awt.image.BufferedImage)
*/
public final Rectangle2D getBounds2D(BufferedImage src)
{
return src.getRaster().getBounds();
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getBounds2D(java.awt.image.Raster)
*/
public final Rectangle2D getBounds2D(Raster src)
{
return src.getBounds();
}
/**
* Returns the corresponding destination point for a source point. Because
* this is not a geometric operation, the destination and source points will
* be identical.
*
* @param src The source point.
* @param dst The transformed destination point.
* @return The transformed destination point.
*/
public final Point2D getPoint2D(Point2D src, Point2D dst)
{
if (dst == null) return (Point2D)src.clone();
dst.setLocation(src);
return dst;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,307 @@
/* LookupOp.java -- Filter that converts each pixel using a lookup table.
Copyright (C) 2004 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt.image;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* LookupOp is a filter that converts each pixel using a lookup table.
*
* For filtering Rasters, the lookup table must have either one component
* that is applied to all bands, or one component for every band in the
* Rasters.
*
* For BufferedImages, the lookup table may apply to both color and alpha
* components. If the lookup table contains one component, or if there are
* the same number of components as color components in the source, the table
* applies to all color components. Otherwise the table applies to all
* components including alpha. Alpha premultiplication is ignored during the
* lookup filtering.
*
* After filtering, if color conversion is necessary, the conversion happens,
* taking alpha premultiplication into account.
*
* @author jlquinn
*/
public class LookupOp implements BufferedImageOp, RasterOp
{
private LookupTable lut;
private RenderingHints hints;
/**
* Construct a new LookupOp using the given LookupTable.
*
* @param lookup LookupTable to use.
* @param hints Rendering hints (can be null).
*/
public LookupOp(LookupTable lookup, RenderingHints hints)
{
lut = lookup;
this.hints = hints;
}
/**
* Converts the source image using the lookup table specified in the
* constructor. The resulting image is stored in the destination image if one
* is provided; otherwise a new BufferedImage is created and returned.
*
* The source image cannot use an IndexColorModel, and the destination image
* (if one is provided) must have the same size.
*
* @param src The source image.
* @param dst The destination image.
* @throws IllegalArgumentException if the rasters and/or color spaces are
* incompatible.
* @throws ArrayIndexOutOfBoundsException if a pixel in the source is not
* contained in the LookupTable.
* @return The convolved image.
*/
public final BufferedImage filter(BufferedImage src, BufferedImage dst)
{
if (src.getColorModel() instanceof IndexColorModel)
throw new IllegalArgumentException("LookupOp.filter: IndexColorModel "
+ "not allowed");
if (lut.getNumComponents() != 1
&& lut.getNumComponents() != src.getColorModel().getNumComponents()
&& lut.getNumComponents() != src.getColorModel().getNumColorComponents())
throw new IllegalArgumentException("LookupOp.filter: Incompatible " +
"lookup table and source image");
if (dst == null)
dst = createCompatibleDestImage(src, null);
else if (src.getHeight() != dst.getHeight() || src.getWidth() != dst.getWidth())
throw new IllegalArgumentException("Source and destination images are " +
"different sizes.");
// Set up for potential colormodel mismatch
BufferedImage tgt;
if (dst.getColorModel().equals(src.getColorModel()))
tgt = dst;
else
tgt = createCompatibleDestImage(src, src.getColorModel());
Raster sr = src.getRaster();
WritableRaster dr = tgt.getRaster();
if (src.getColorModel().hasAlpha() &&
(lut.getNumComponents() == 1 ||
lut.getNumComponents() == src.getColorModel().getNumColorComponents()))
{
// Need to ignore alpha for lookup
int[] dbuf = new int[src.getColorModel().getNumComponents()];
int tmpBands = src.getColorModel().getNumColorComponents();
int[] tmp = new int[tmpBands];
// Filter the pixels
for (int y = src.getMinY(); y < src.getHeight() + src.getMinY(); y++)
for (int x = src.getMinX(); x < src.getWidth() + src.getMinX(); x++)
{
// Filter only color components, but also copy alpha
sr.getPixel(x, y, dbuf);
System.arraycopy(dbuf, 0, tmp, 0, tmpBands);
dr.setPixel(x, y, lut.lookupPixel(tmp, dbuf));
/* The reference implementation does not use LookupTable.lookupPixel,
* but rather it seems to copy the table into a native array. The
* effect of this (a probable bug in their implementation) is that
* an out-of-bounds lookup on a ByteLookupTable will *not* throw an
* out of bounds exception, but will instead return random garbage.
* A bad lookup on a ShortLookupTable, however, will throw an
* exception.
*
* Instead of mimicing this behaviour, we always throw an
* ArrayOutofBoundsException by virtue of using
* LookupTable.lookupPixle.
*/
}
}
else
{
// No alpha to ignore
int[] dbuf = new int[src.getColorModel().getNumComponents()];
// Filter the pixels
for (int y = src.getMinY(); y < src.getHeight() + src.getMinY(); y++)
for (int x = src.getMinX(); x < src.getWidth() + src.getMinX(); x++)
dr.setPixel(x, y, lut.lookupPixel(sr.getPixel(x, y, dbuf), dbuf));
}
if (tgt != dst)
new ColorConvertOp(hints).filter(tgt, dst);
return dst;
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#getBounds2D(java.awt.image.BufferedImage)
*/
public final Rectangle2D getBounds2D(BufferedImage src)
{
return src.getRaster().getBounds();
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel)
*/
public BufferedImage createCompatibleDestImage(BufferedImage src,
ColorModel dstCM)
{
if (dstCM != null)
return new BufferedImage(dstCM,
src.getRaster().createCompatibleWritableRaster(),
src.isAlphaPremultiplied(), null);
// This is a strange exception, done for compatibility with the reference
// (as demonstrated by a mauve testcase)
int imgType = src.getType();
if (imgType == BufferedImage.TYPE_USHORT_GRAY)
imgType = BufferedImage.TYPE_BYTE_GRAY;
return new BufferedImage(src.getWidth(), src.getHeight(), imgType);
}
/**
* Returns the corresponding destination point for a given source point.
*
* This Op will return the source point unchanged.
*
* @param src The source point.
* @param dst The destination point.
*/
public final Point2D getPoint2D(Point2D src, Point2D dst)
{
if (dst == null)
return (Point2D) src.clone();
dst.setLocation(src);
return dst;
}
/**
* Return the LookupTable for this op.
*
* @return The lookup table.
*/
public final LookupTable getTable()
{
return lut;
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getRenderingHints()
*/
public final RenderingHints getRenderingHints()
{
return hints;
}
/**
* Filter a raster through a lookup table.
*
* Applies the lookup table for this Rasterop to each pixel of src and
* puts the results in dest. If dest is null, a new Raster is created and
* returned.
*
* @param src The source raster.
* @param dest The destination raster.
* @return The WritableRaster with the filtered pixels.
* @throws IllegalArgumentException if lookup table has more than one
* component but not the same as src and dest.
* @throws ArrayIndexOutOfBoundsException if a pixel in the source is not
* contained in the LookupTable.
*/
public final WritableRaster filter(Raster src, WritableRaster dest)
{
if (dest == null)
// Allocate a raster if needed
dest = createCompatibleDestRaster(src);
else
if (src.getNumBands() != dest.getNumBands())
throw new IllegalArgumentException("Source and destination rasters " +
"are incompatible.");
if (lut.getNumComponents() != 1
&& lut.getNumComponents() != src.getNumBands())
throw new IllegalArgumentException("Lookup table is incompatible with " +
"this raster.");
// Allocate pixel storage.
int[] tmp = new int[src.getNumBands()];
// Filter the pixels
for (int y = src.getMinY(); y < src.getHeight() + src.getMinY(); y++)
for (int x = src.getMinX(); x < src.getWidth() + src.getMinX(); x++)
dest.setPixel(x, y, lut.lookupPixel(src.getPixel(x, y, tmp), tmp));
/* The reference implementation does not use LookupTable.lookupPixel,
* but rather it seems to copy the table into a native array. The
* effect of this (a probable bug in their implementation) is that
* an out-of-bounds lookup on a ByteLookupTable will *not* throw an
* out of bounds exception, but will instead return random garbage.
* A bad lookup on a ShortLookupTable, however, will throw an
* exception.
*
* Instead of mimicing this behaviour, we always throw an
* ArrayOutofBoundsException by virtue of using
* LookupTable.lookupPixle.
*/
return dest;
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getBounds2D(java.awt.image.Raster)
*/
public final Rectangle2D getBounds2D(Raster src)
{
return src.getBounds();
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#createCompatibleDestRaster(java.awt.image.Raster)
*/
public WritableRaster createCompatibleDestRaster(Raster src)
{
return src.createCompatibleWritableRaster();
}
}

View File

@@ -0,0 +1,385 @@
/* Copyright (C) 2004, 2006 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt.image;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
/**
* RescaleOp is a filter that changes each pixel by a scaling factor and offset.
*
* For filtering Rasters, either one scaling factor and offset can be specified,
* which will be applied to all bands; or a scaling factor and offset can be
* specified for each band.
*
* For BufferedImages, the scaling may apply to both color and alpha components.
* If only one scaling factor is provided, or if the number of factors provided
* equals the number of color components, the scaling is performed on all color
* components. Otherwise, the scaling is performed on all components including
* alpha. Alpha premultiplication is ignored.
*
* After filtering, if color conversion is necessary, the conversion happens,
* taking alpha premultiplication into account.
*
* @author Jerry Quinn (jlquinn@optonline.net)
* @author Francis Kung (fkung@redhat.com)
*/
public class RescaleOp implements BufferedImageOp, RasterOp
{
private float[] scale;
private float[] offsets;
private RenderingHints hints = null;
/**
* Create a new RescaleOp object using the given scale factors and offsets.
*
* The length of the arrays must be equal to the number of bands (or number of
* data or color components) of the raster/image that this Op will be used on,
* otherwise an IllegalArgumentException will be thrown when calling the
* filter method.
*
* @param scaleFactors an array of scale factors.
* @param offsets an array of offsets.
* @param hints any rendering hints to use (can be null).
* @throws NullPointerException if the scaleFactors or offsets array is null.
*/
public RescaleOp(float[] scaleFactors,
float[] offsets,
RenderingHints hints)
{
int length = Math.min(scaleFactors.length, offsets.length);
scale = new float[length];
System.arraycopy(scaleFactors, 0, this.scale, 0, length);
this.offsets = new float[length];
System.arraycopy(offsets, 0, this.offsets, 0, length);
this.hints = hints;
}
/**
* Create a new RescaleOp object using the given scale factor and offset.
*
* The same scale factor and offset will be used on all bands/components.
*
* @param scaleFactor the scale factor to use.
* @param offset the offset to use.
* @param hints any rendering hints to use (can be null).
*/
public RescaleOp(float scaleFactor,
float offset,
RenderingHints hints)
{
scale = new float[]{ scaleFactor };
offsets = new float[]{offset};
this.hints = hints;
}
/**
* Returns the scaling factors. This method accepts an optional array, which
* will be used to store the factors if not null (this avoids allocating a
* new array). If this array is too small to hold all the scaling factors,
* the array will be filled and the remaining factors discarded.
*
* @param scaleFactors array to store the scaling factors in (can be null).
* @return an array of scaling factors.
*/
public final float[] getScaleFactors(float[] scaleFactors)
{
if (scaleFactors == null)
scaleFactors = new float[scale.length];
System.arraycopy(scale, 0, scaleFactors, 0, Math.min(scale.length,
scaleFactors.length));
return scaleFactors;
}
/**
* Returns the offsets. This method accepts an optional array, which
* will be used to store the offsets if not null (this avoids allocating a
* new array). If this array is too small to hold all the offsets, the array
* will be filled and the remaining factors discarded.
*
* @param offsets array to store the offsets in (can be null).
* @return an array of offsets.
*/
public final float[] getOffsets(float[] offsets)
{
if (offsets == null)
offsets = new float[this.offsets.length];
System.arraycopy(this.offsets, 0, offsets, 0, Math.min(this.offsets.length,
offsets.length));
return offsets;
}
/**
* Returns the number of scaling factors / offsets.
*
* @return the number of scaling factors / offsets.
*/
public final int getNumFactors()
{
return scale.length;
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#getRenderingHints()
*/
public final RenderingHints getRenderingHints()
{
return hints;
}
/**
* Converts the source image using the scale factors and offsets specified in
* the constructor. The resulting image is stored in the destination image if
* one is provided; otherwise a new BufferedImage is created and returned.
*
* The source image cannot use an IndexColorModel, and the destination image
* (if one is provided) must have the same size.
*
* If the final value of a sample is beyond the range of the color model, it
* will be clipped to the appropriate maximum / minimum.
*
* @param src The source image.
* @param dst The destination image.
* @throws IllegalArgumentException if the rasters and/or color spaces are
* incompatible.
* @return The rescaled image.
*/
public final BufferedImage filter(BufferedImage src, BufferedImage dst)
{
// Initial checks
if (scale.length != 1
&& scale.length != src.getColorModel().getNumComponents()
&& (scale.length != src.getColorModel().getNumColorComponents()))
throw new IllegalArgumentException("Source image has wrong number of "
+ "bands for these scaling factors.");
if (dst == null)
dst = createCompatibleDestImage(src, null);
else if (src.getHeight() != dst.getHeight()
|| src.getWidth() != dst.getWidth())
throw new IllegalArgumentException("Source and destination images are "
+ "different sizes.");
// Prepare for possible colorspace conversion
BufferedImage dst2 = dst;
if (dst.getColorModel().getColorSpace().getType() != src.getColorModel().getColorSpace().getType())
dst2 = createCompatibleDestImage(src, src.getColorModel());
// Figure out how many bands to scale
int numBands = scale.length;
if (scale.length == 1)
numBands = src.getColorModel().getNumColorComponents();
boolean[] bands = new boolean[numBands];
// this assumes the alpha, if present, is the last band
Arrays.fill(bands, true);
// Perform rescaling
filter(src.getRaster(), dst2.getRaster(), bands);
// Copy alpha band if needed (ie if it exists and wasn't scaled)
// NOTE: This assumes the alpha component is the last band!
if (src.getColorModel().hasAlpha()
&& numBands == src.getColorModel().getNumColorComponents())
{
dst2.getRaster().setSamples(0, 0, src.getWidth(), src.getHeight(),
numBands,
src.getRaster().getSamples(0, 0,
src.getWidth(),
src.getHeight(),
numBands,
(int[]) null));
}
// Perform colorspace conversion if needed
if (dst != dst2)
new ColorConvertOp(hints).filter(dst2, dst);
return dst;
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#filter(java.awt.image.Raster, java.awt.image.WritableRaster)
*/
public final WritableRaster filter(Raster src, WritableRaster dest)
{
// Required sanity checks
if (scale.length != 1 && scale.length != src.numBands)
throw new IllegalArgumentException("Number of rasters is incompatible "
+ "with the number of scaling "
+ "factors provided.");
if (dest == null)
dest = src.createCompatibleWritableRaster();
else if (src.getHeight() != dest.getHeight()
|| src.getWidth() != dest.getWidth())
throw new IllegalArgumentException("Source and destination rasters are "
+ "different sizes.");
else if (src.numBands != dest.numBands)
throw new IllegalArgumentException("Source and destination rasters "
+ "are incompatible.");
// Filter all bands
boolean[] bands = new boolean[src.getNumBands()];
Arrays.fill(bands, true);
return filter(src, dest, bands);
}
/**
* Perform raster-based filtering on a selected number of bands.
*
* The length of the bands array should equal the number of bands; a true
* element indicates filtering should happen on the corresponding band, while
* a false element will skip the band.
*
* The rasters are assumed to be compatible and non-null.
*
* @param src the source raster.
* @param dest the destination raster.
* @param bands an array indicating which bands to filter.
* @throws NullPointerException if any parameter is null.
* @throws ArrayIndexOutOfBoundsException if the bands array is too small.
* @return the destination raster.
*/
private WritableRaster filter(Raster src, WritableRaster dest, boolean[] bands)
{
int[] values = new int[src.getHeight() * src.getWidth()];
float scaleFactor, offset;
// Find max sample value, to be used for clipping later
int[] maxValue = src.getSampleModel().getSampleSize();
for (int i = 0; i < maxValue.length; i++)
maxValue[i] = (int)Math.pow(2, maxValue[i]) - 1;
// TODO: can this be optimized further?
// Filter all samples of all requested bands
for (int band = 0; band < bands.length; band++)
if (bands[band])
{
values = src.getSamples(src.getMinX(), src.getMinY(), src.getWidth(),
src.getHeight(), band, values);
if (scale.length == 1)
{
scaleFactor = scale[0];
offset = offsets[0];
}
else
{
scaleFactor = scale[band];
offset = offsets[band];
}
for (int i = 0; i < values.length; i++)
{
values[i] = (int) (values[i] * scaleFactor + offset);
// Clip if needed
if (values[i] < 0)
values[i] = 0;
if (values[i] > maxValue[band])
values[i] = maxValue[band];
}
dest.setSamples(dest.getMinX(), dest.getMinY(), dest.getWidth(),
dest.getHeight(), band, values);
}
return dest;
}
/*
* (non-Javadoc)
*
* @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage,
* java.awt.image.ColorModel)
*/
public BufferedImage createCompatibleDestImage(BufferedImage src,
ColorModel dstCM)
{
if (dstCM == null)
return new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
return new BufferedImage(dstCM,
src.getRaster().createCompatibleWritableRaster(),
src.isAlphaPremultiplied(), null);
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#createCompatibleDestRaster(java.awt.image.Raster)
*/
public WritableRaster createCompatibleDestRaster(Raster src)
{
return src.createCompatibleWritableRaster();
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#getBounds2D(java.awt.image.BufferedImage)
*/
public final Rectangle2D getBounds2D(BufferedImage src)
{
return src.getRaster().getBounds();
}
/* (non-Javadoc)
* @see java.awt.image.RasterOp#getBounds2D(java.awt.image.Raster)
*/
public final Rectangle2D getBounds2D(Raster src)
{
return src.getBounds();
}
/* (non-Javadoc)
* @see java.awt.image.BufferedImageOp#getPoint2D(java.awt.geom.Point2D, java.awt.geom.Point2D)
*/
public final Point2D getPoint2D(Point2D src, Point2D dst)
{
if (dst == null)
dst = (Point2D) src.clone();
else
dst.setLocation(src);
return dst;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,451 @@
/*
* Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
import sun.misc.IoTrace;
/**
* A <code>FileInputStream</code> obtains input bytes
* from a file in a file system. What files
* are available depends on the host environment.
*
* <p><code>FileInputStream</code> is meant for reading streams of raw bytes
* such as image data. For reading streams of characters, consider using
* <code>FileReader</code>.
*
* @author Arthur van Hoff
* @see java.io.File
* @see java.io.FileDescriptor
* @see java.io.FileOutputStream
* @see java.nio.file.Files#newInputStream
* @since JDK1.0
*/
public
class FileInputStream extends InputStream
{
/* File Descriptor - handle to the open file */
private final FileDescriptor fd;
/* The path of the referenced file (null if the stream is created with a file descriptor) */
private final String path;
private FileChannel channel = null;
private final Object closeLock = new Object();
private volatile boolean closed = false;
private static final ThreadLocal<Boolean> runningFinalize =
new ThreadLocal<>();
private static boolean isRunningFinalize() {
Boolean val;
if ((val = runningFinalize.get()) != null)
return val.booleanValue();
return false;
}
/**
* Creates a <code>FileInputStream</code> by
* opening a connection to an actual file,
* the file named by the path name <code>name</code>
* in the file system. A new <code>FileDescriptor</code>
* object is created to represent this file
* connection.
* <p>
* First, if there is a security
* manager, its <code>checkRead</code> method
* is called with the <code>name</code> argument
* as its argument.
* <p>
* If the named file does not exist, is a directory rather than a regular
* file, or for some other reason cannot be opened for reading then a
* <code>FileNotFoundException</code> is thrown.
*
* @param name the system-dependent file name.
* @exception FileNotFoundException if the file does not exist,
* is a directory rather than a regular file,
* or for some other reason cannot be opened for
* reading.
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access
* to the file.
* @see java.lang.SecurityManager#checkRead(java.lang.String)
*/
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
/**
* Creates a <code>FileInputStream</code> by
* opening a connection to an actual file,
* the file named by the <code>File</code>
* object <code>file</code> in the file system.
* A new <code>FileDescriptor</code> object
* is created to represent this file connection.
* <p>
* First, if there is a security manager,
* its <code>checkRead</code> method is called
* with the path represented by the <code>file</code>
* argument as its argument.
* <p>
* If the named file does not exist, is a directory rather than a regular
* file, or for some other reason cannot be opened for reading then a
* <code>FileNotFoundException</code> is thrown.
*
* @param file the file to be opened for reading.
* @exception FileNotFoundException if the file does not exist,
* is a directory rather than a regular file,
* or for some other reason cannot be opened for
* reading.
* @exception SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the file.
* @see java.io.File#getPath()
* @see java.lang.SecurityManager#checkRead(java.lang.String)
*/
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
/*
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
*/
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.path = name;
open(name);
}
/**
* Creates a <code>FileInputStream</code> by using the file descriptor
* <code>fdObj</code>, which represents an existing connection to an
* actual file in the file system.
* <p>
* If there is a security manager, its <code>checkRead</code> method is
* called with the file descriptor <code>fdObj</code> as its argument to
* see if it's ok to read the file descriptor. If read access is denied
* to the file descriptor a <code>SecurityException</code> is thrown.
* <p>
* If <code>fdObj</code> is null then a <code>NullPointerException</code>
* is thrown.
* <p>
* This constructor does not throw an exception if <code>fdObj</code>
* is {@link java.io.FileDescriptor#valid() invalid}.
* However, if the methods are invoked on the resulting stream to attempt
* I/O on the stream, an <code>IOException</code> is thrown.
*
* @param fdObj the file descriptor to be opened for reading.
* @throws SecurityException if a security manager exists and its
* <code>checkRead</code> method denies read access to the
* file descriptor.
* @see SecurityManager#checkRead(java.io.FileDescriptor)
*/
public FileInputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
security.checkRead(fdObj);
}
fd = fdObj;
path = null;
/*
* FileDescriptor is being shared by streams.
* Ensure that it's GC'ed only when all the streams/channels are done
* using it.
*/
fd.incrementAndGetUseCount();
}
/**
* Opens the specified file for reading.
* @param name the name of the file
*/
private void open(String name) throws FileNotFoundException
{
fd.openReadOnly(name);
}
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
*/
public int read() throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int b = 0;
try {
b = fd.read();
} finally {
IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);
}
return b;
}
/**
* Reads a subarray as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @exception IOException If an I/O error has occurred.
*/
private int readBytes(byte b[], int off, int len) throws IOException
{
return fd.readBytes(b, off, len);
}
/**
* Reads up to <code>b.length</code> bytes of data from this input
* stream into an array of bytes. This method blocks until some input
* is available.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[]) throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int bytesRead = 0;
try {
bytesRead = readBytes(b, 0, b.length);
} finally {
IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
}
return bytesRead;
}
/**
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes. If <code>len</code> is not zero, the method
* blocks until some input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
*
* @param b the buffer into which the data is read.
* @param off the start offset in the destination array <code>b</code>
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[], int off, int len) throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int bytesRead = 0;
try {
bytesRead = readBytes(b, off, len);
} finally {
IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
}
return bytesRead;
}
/**
* Skips over and discards <code>n</code> bytes of data from the
* input stream.
*
* <p>The <code>skip</code> method may, for a variety of
* reasons, end up skipping over some smaller number of bytes,
* possibly <code>0</code>. If <code>n</code> is negative, an
* <code>IOException</code> is thrown, even though the <code>skip</code>
* method of the {@link InputStream} superclass does nothing in this case.
* The actual number of bytes skipped is returned.
*
* <p>This method may skip more bytes than are remaining in the backing
* file. This produces no exception and the number of bytes skipped
* may include some number of bytes that were beyond the EOF of the
* backing file. Attempting to read from the stream after skipping past
* the end will result in -1 indicating the end of the file.
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException if n is negative, if the stream does not
* support seek, or if an I/O error occurs.
*/
public long skip(long n) throws IOException
{
return fd.skip(n);
}
/**
* Returns an estimate of the number of remaining bytes that can be read (or
* skipped over) from this input stream without blocking by the next
* invocation of a method for this input stream. The next invocation might be
* the same thread or another thread. A single read or skip of this
* many bytes will not block, but may read or skip fewer bytes.
*
* <p> In some cases, a non-blocking read (or skip) may appear to be
* blocked when it is merely slow, for example when reading large
* files over slow networks.
*
* @return an estimate of the number of remaining bytes that can be read
* (or skipped over) from this input stream without blocking.
* @exception IOException if this file input stream has been closed by calling
* {@code close} or an I/O error occurs.
*/
public int available() throws IOException
{
return fd.available();
}
/**
* Closes this file input stream and releases any system resources
* associated with the stream.
*
* <p> If this stream has an associated channel then the channel is closed
* as well.
*
* @exception IOException if an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
/*
* Decrement the FD use count associated with the channel
* The use count is incremented whenever a new channel
* is obtained from this stream.
*/
fd.decrementAndGetUseCount();
channel.close();
}
/*
* Decrement the FD use count associated with this stream
*/
int useCount = fd.decrementAndGetUseCount();
/*
* If FileDescriptor is still in use by another stream, the finalizer
* will not close it.
*/
if ((useCount <= 0) || !isRunningFinalize()) {
close0();
}
}
/**
* Returns the <code>FileDescriptor</code>
* object that represents the connection to
* the actual file in the file system being
* used by this <code>FileInputStream</code>.
*
* @return the file descriptor object associated with this stream.
* @exception IOException if an I/O error occurs.
* @see java.io.FileDescriptor
*/
public final FileDescriptor getFD() throws IOException {
if (fd != null) return fd;
throw new IOException();
}
/**
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
* object associated with this file input stream.
*
* <p> The initial {@link java.nio.channels.FileChannel#position()
* </code>position<code>} of the returned channel will be equal to the
* number of bytes read from the file so far. Reading bytes from this
* stream will increment the channel's position. Changing the channel's
* position, either explicitly or by reading, will change this stream's
* file position.
*
* @return the file channel associated with this file input stream
*
* @since 1.4
* @spec JSR-51
*/
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, path, true, false, this);
/*
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
private void close0() throws IOException
{
fd.close();
}
/**
* Ensures that the <code>close</code> method of this file input stream is
* called when there are no more references to it.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileInputStream#close()
*/
protected void finalize() throws IOException {
if ((fd != null) && (fd != FileDescriptor.in)) {
/*
* Finalizer should not release the FileDescriptor if another
* stream is still using it. If the user directly invokes
* close() then the FileDescriptor is also released.
*/
runningFinalize.set(Boolean.TRUE);
try {
close();
} finally {
runningFinalize.set(Boolean.FALSE);
}
}
}
}

View File

@@ -0,0 +1,491 @@
/*
* Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
import sun.misc.IoTrace;
/**
* A file output stream is an output stream for writing data to a
* <code>File</code> or to a <code>FileDescriptor</code>. Whether or not
* a file is available or may be created depends upon the underlying
* platform. Some platforms, in particular, allow a file to be opened
* for writing by only one <tt>FileOutputStream</tt> (or other
* file-writing object) at a time. In such situations the constructors in
* this class will fail if the file involved is already open.
*
* <p><code>FileOutputStream</code> is meant for writing streams of raw bytes
* such as image data. For writing streams of characters, consider using
* <code>FileWriter</code>.
*
* @author Arthur van Hoff
* @see java.io.File
* @see java.io.FileDescriptor
* @see java.io.FileInputStream
* @see java.nio.file.Files#newOutputStream
* @since JDK1.0
*/
public
class FileOutputStream extends OutputStream
{
/**
* The system dependent file descriptor.
*/
private final FileDescriptor fd;
/**
* The path of the referenced file (null if the stream is created with a file descriptor)
*/
private final String path;
/**
* True if the file is opened for append.
*/
private final boolean append;
/**
* The associated channel, initalized lazily.
*/
private FileChannel channel;
private final Object closeLock = new Object();
private volatile boolean closed = false;
private static final ThreadLocal<Boolean> runningFinalize =
new ThreadLocal<>();
private static boolean isRunningFinalize() {
Boolean val;
if ((val = runningFinalize.get()) != null)
return val.booleanValue();
return false;
}
/**
* Creates a file output stream to write to the file with the
* specified name. A new <code>FileDescriptor</code> object is
* created to represent this file connection.
* <p>
* First, if there is a security manager, its <code>checkWrite</code>
* method is called with <code>name</code> as its argument.
* <p>
* If the file exists but is a directory rather than a regular file, does
* not exist but cannot be created, or cannot be opened for any other
* reason then a <code>FileNotFoundException</code> is thrown.
*
* @param name the system-dependent filename
* @exception FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason
* @exception SecurityException if a security manager exists and its
* <code>checkWrite</code> method denies write access
* to the file.
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
*/
public FileOutputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null, false);
}
/**
* Creates a file output stream to write to the file with the specified
* name. If the second argument is <code>true</code>, then
* bytes will be written to the end of the file rather than the beginning.
* A new <code>FileDescriptor</code> object is created to represent this
* file connection.
* <p>
* First, if there is a security manager, its <code>checkWrite</code>
* method is called with <code>name</code> as its argument.
* <p>
* If the file exists but is a directory rather than a regular file, does
* not exist but cannot be created, or cannot be opened for any other
* reason then a <code>FileNotFoundException</code> is thrown.
*
* @param name the system-dependent file name
* @param append if <code>true</code>, then bytes will be written
* to the end of the file rather than the beginning
* @exception FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason.
* @exception SecurityException if a security manager exists and its
* <code>checkWrite</code> method denies write access
* to the file.
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
* @since JDK1.1
*/
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
{
this(name != null ? new File(name) : null, append);
}
/**
* Creates a file output stream to write to the file represented by
* the specified <code>File</code> object. A new
* <code>FileDescriptor</code> object is created to represent this
* file connection.
* <p>
* First, if there is a security manager, its <code>checkWrite</code>
* method is called with the path represented by the <code>file</code>
* argument as its argument.
* <p>
* If the file exists but is a directory rather than a regular file, does
* not exist but cannot be created, or cannot be opened for any other
* reason then a <code>FileNotFoundException</code> is thrown.
*
* @param file the file to be opened for writing.
* @exception FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason
* @exception SecurityException if a security manager exists and its
* <code>checkWrite</code> method denies write access
* to the file.
* @see java.io.File#getPath()
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
*/
public FileOutputStream(File file) throws FileNotFoundException {
this(file, false);
}
/**
* Creates a file output stream to write to the file represented by
* the specified <code>File</code> object. If the second argument is
* <code>true</code>, then bytes will be written to the end of the file
* rather than the beginning. A new <code>FileDescriptor</code> object is
* created to represent this file connection.
* <p>
* First, if there is a security manager, its <code>checkWrite</code>
* method is called with the path represented by the <code>file</code>
* argument as its argument.
* <p>
* If the file exists but is a directory rather than a regular file, does
* not exist but cannot be created, or cannot be opened for any other
* reason then a <code>FileNotFoundException</code> is thrown.
*
* @param file the file to be opened for writing.
* @param append if <code>true</code>, then bytes will be written
* to the end of the file rather than the beginning
* @exception FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason
* @exception SecurityException if a security manager exists and its
* <code>checkWrite</code> method denies write access
* to the file.
* @see java.io.File#getPath()
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkWrite(java.lang.String)
* @since 1.4
*/
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
/*
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
*/
this.fd = new FileDescriptor();
this.append = append;
this.path = name;
fd.incrementAndGetUseCount();
open(name, append);
}
/**
* Creates a file output stream to write to the specified file
* descriptor, which represents an existing connection to an actual
* file in the file system.
* <p>
* First, if there is a security manager, its <code>checkWrite</code>
* method is called with the file descriptor <code>fdObj</code>
* argument as its argument.
* <p>
* If <code>fdObj</code> is null then a <code>NullPointerException</code>
* is thrown.
* <p>
* This constructor does not throw an exception if <code>fdObj</code>
* is {@link java.io.FileDescriptor#valid() invalid}.
* However, if the methods are invoked on the resulting stream to attempt
* I/O on the stream, an <code>IOException</code> is thrown.
*
* @param fdObj the file descriptor to be opened for writing
* @exception SecurityException if a security manager exists and its
* <code>checkWrite</code> method denies
* write access to the file descriptor
* @see java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)
*/
public FileOutputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
security.checkWrite(fdObj);
}
this.fd = fdObj;
this.path = null;
this.append = false;
/*
* FileDescriptor is being shared by streams.
* Ensure that it's GC'ed only when all the streams/channels are done
* using it.
*/
fd.incrementAndGetUseCount();
}
/**
* Opens a file, with the specified name, for overwriting or appending.
* @param name name of file to be opened
* @param append whether the file is to be opened in append mode
*/
private void open(String name, boolean append)
throws FileNotFoundException {
if (append) {
fd.openAppend(name);
} else {
fd.openWriteOnly(name);
}
}
/**
* Writes the specified byte to this file output stream.
*
* @param b the byte to be written.
* @param append {@code true} if the write operation first
* advances the position to the end of file
*/
private void write(int b, boolean append) throws IOException {
fd.write(b);
}
/**
* Writes the specified byte to this file output stream. Implements
* the <code>write</code> method of <code>OutputStream</code>.
*
* @param b the byte to be written.
* @exception IOException if an I/O error occurs.
*/
public void write(int b) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
try {
write(b, append);
bytesWritten = 1;
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
}
}
/**
* Writes a sub array as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @param append {@code true} to first advance the position to the
* end of file
* @exception IOException If an I/O error has occurred.
*/
private void writeBytes(byte b[], int off, int len, boolean append)
throws IOException {
fd.writeBytes(b, off, len);
}
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this file output stream.
*
* @param b the data.
* @exception IOException if an I/O error occurs.
*/
public void write(byte b[]) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
try {
writeBytes(b, 0, b.length, append);
bytesWritten = b.length;
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
}
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this file output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
public void write(byte b[], int off, int len) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
try {
writeBytes(b, off, len, append);
bytesWritten = len;
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
}
}
/**
* Closes this file output stream and releases any system resources
* associated with this stream. This file output stream may no longer
* be used for writing bytes.
*
* <p> If this stream has an associated channel then the channel is closed
* as well.
*
* @exception IOException if an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
/*
* Decrement FD use count associated with the channel
* The use count is incremented whenever a new channel
* is obtained from this stream.
*/
fd.decrementAndGetUseCount();
channel.close();
}
/*
* Decrement FD use count associated with this stream
*/
int useCount = fd.decrementAndGetUseCount();
/*
* If FileDescriptor is still in use by another stream, the finalizer
* will not close it.
*/
if ((useCount <= 0) || !isRunningFinalize()) {
close0();
}
}
/**
* Returns the file descriptor associated with this stream.
*
* @return the <code>FileDescriptor</code> object that represents
* the connection to the file in the file system being used
* by this <code>FileOutputStream</code> object.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileDescriptor
*/
public final FileDescriptor getFD() throws IOException {
if (fd != null) return fd;
throw new IOException();
}
/**
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
* object associated with this file output stream. </p>
*
* <p> The initial {@link java.nio.channels.FileChannel#position()
* </code>position<code>} of the returned channel will be equal to the
* number of bytes written to the file so far unless this stream is in
* append mode, in which case it will be equal to the size of the file.
* Writing bytes to this stream will increment the channel's position
* accordingly. Changing the channel's position, either explicitly or by
* writing, will change this stream's file position.
*
* @return the file channel associated with this file output stream
*
* @since 1.4
* @spec JSR-51
*/
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, path, false, true, append, this);
/*
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
/**
* Cleans up the connection to the file, and ensures that the
* <code>close</code> method of this file output stream is
* called when there are no more references to this stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileInputStream#close()
*/
protected void finalize() throws IOException {
if (fd != null) {
if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
flush();
} else {
/*
* Finalizer should not release the FileDescriptor if another
* stream is still using it. If the user directly invokes
* close() then the FileDescriptor is also released.
*/
runningFinalize.set(Boolean.TRUE);
try {
close();
} finally {
runningFinalize.set(Boolean.FALSE);
}
}
}
}
private void close0() throws IOException
{
fd.close();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,335 @@
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.lang.reflect.Field;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.reflect.misc.ReflectUtil;
/**
* A description of a Serializable field from a Serializable class. An array
* of ObjectStreamFields is used to declare the Serializable fields of a class.
*
* @author Mike Warres
* @author Roger Riggs
* @see ObjectStreamClass
* @since 1.2
*/
public class ObjectStreamField
implements Comparable<Object>
{
/** field name */
private final String name;
/** canonical JVM signature of field type */
private String signature;
/** field type (Object.class if unknown non-primitive type) */
private final Class<?> type;
/** whether or not to (de)serialize field values as unshared */
private final boolean unshared;
/** corresponding reflective field object, if any */
private final Field field;
/** offset of field value in enclosing field group */
private int offset = 0;
/**
* Create a Serializable field with the specified type. This field should
* be documented with a <code>serialField</code> tag.
*
* @param name the name of the serializable field
* @param type the <code>Class</code> object of the serializable field
*/
public ObjectStreamField(String name, Class<?> type) {
this(name, type, false);
}
/**
* Creates an ObjectStreamField representing a serializable field with the
* given name and type. If unshared is false, values of the represented
* field are serialized and deserialized in the default manner--if the
* field is non-primitive, object values are serialized and deserialized as
* if they had been written and read by calls to writeObject and
* readObject. If unshared is true, values of the represented field are
* serialized and deserialized as if they had been written and read by
* calls to writeUnshared and readUnshared.
*
* @param name field name
* @param type field type
* @param unshared if false, write/read field values in the same manner
* as writeObject/readObject; if true, write/read in the same
* manner as writeUnshared/readUnshared
* @since 1.4
*/
public ObjectStreamField(String name, Class<?> type, boolean unshared) {
if (name == null || type == null) {
throw new NullPointerException();
}
this.name = name;
this.type = type;
this.unshared = unshared;
field = null;
}
// [IKVM] added lazy signature computation, to avoid the reflection hit, unless we really need it
private void lazyInitSignature() {
if (signature == null) {
signature = getClassSignature(type).intern();
}
}
/**
* Creates an ObjectStreamField representing a field with the given name,
* signature and unshared setting.
*/
ObjectStreamField(String name, String signature, boolean unshared) {
if (name == null) {
throw new NullPointerException();
}
this.name = name;
this.signature = signature.intern();
this.unshared = unshared;
field = null;
switch (signature.charAt(0)) {
case 'Z': type = Boolean.TYPE; break;
case 'B': type = Byte.TYPE; break;
case 'C': type = Character.TYPE; break;
case 'S': type = Short.TYPE; break;
case 'I': type = Integer.TYPE; break;
case 'J': type = Long.TYPE; break;
case 'F': type = Float.TYPE; break;
case 'D': type = Double.TYPE; break;
case 'L':
case '[': type = Object.class; break;
default: throw new IllegalArgumentException("illegal signature");
}
}
/**
* Creates an ObjectStreamField representing the given field with the
* specified unshared setting. For compatibility with the behavior of
* earlier serialization implementations, a "showType" parameter is
* necessary to govern whether or not a getType() call on this
* ObjectStreamField (if non-primitive) will return Object.class (as
* opposed to a more specific reference type).
*/
ObjectStreamField(Field field, boolean unshared, boolean showType) {
this.field = field;
this.unshared = unshared;
name = field.getName();
Class<?> ftype = field.getType();
type = (showType || ftype.isPrimitive()) ? ftype : Object.class;
signature = getClassSignature(ftype).intern();
}
/**
* Get the name of this field.
*
* @return a <code>String</code> representing the name of the serializable
* field
*/
public String getName() {
return name;
}
/**
* Get the type of the field. If the type is non-primitive and this
* <code>ObjectStreamField</code> was obtained from a deserialized {@link
* ObjectStreamClass} instance, then <code>Object.class</code> is returned.
* Otherwise, the <code>Class</code> object for the type of the field is
* returned.
*
* @return a <code>Class</code> object representing the type of the
* serializable field
*/
@CallerSensitive
public Class<?> getType() {
if (System.getSecurityManager() != null) {
Class<?> caller = Reflection.getCallerClass();
if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), type.getClassLoader())) {
ReflectUtil.checkPackageAccess(type);
}
}
return type;
}
/**
* Returns character encoding of field type. The encoding is as follows:
* <blockquote><pre>
* B byte
* C char
* D double
* F float
* I int
* J long
* L class or interface
* S short
* Z boolean
* [ array
* </pre></blockquote>
*
* @return the typecode of the serializable field
*/
// REMIND: deprecate?
public char getTypeCode() {
lazyInitSignature();
return signature.charAt(0);
}
/**
* Return the JVM type signature.
*
* @return null if this field has a primitive type.
*/
// REMIND: deprecate?
public String getTypeString() {
lazyInitSignature();
return isPrimitive() ? null : signature;
}
/**
* Offset of field within instance data.
*
* @return the offset of this field
* @see #setOffset
*/
// REMIND: deprecate?
public int getOffset() {
return offset;
}
/**
* Offset within instance data.
*
* @param offset the offset of the field
* @see #getOffset
*/
// REMIND: deprecate?
protected void setOffset(int offset) {
this.offset = offset;
}
/**
* Return true if this field has a primitive type.
*
* @return true if and only if this field corresponds to a primitive type
*/
// REMIND: deprecate?
public boolean isPrimitive() {
lazyInitSignature();
char tcode = signature.charAt(0);
return ((tcode != 'L') && (tcode != '['));
}
/**
* Returns boolean value indicating whether or not the serializable field
* represented by this ObjectStreamField instance is unshared.
*
* @since 1.4
*/
public boolean isUnshared() {
return unshared;
}
/**
* Compare this field with another <code>ObjectStreamField</code>. Return
* -1 if this is smaller, 0 if equal, 1 if greater. Types that are
* primitives are "smaller" than object types. If equal, the field names
* are compared.
*/
// REMIND: deprecate?
public int compareTo(Object obj) {
ObjectStreamField other = (ObjectStreamField) obj;
boolean isPrim = isPrimitive();
if (isPrim != other.isPrimitive()) {
return isPrim ? -1 : 1;
}
return name.compareTo(other.name);
}
/**
* Return a string that describes this field.
*/
public String toString() {
lazyInitSignature();
return signature + ' ' + name;
}
/**
* Returns field represented by this ObjectStreamField, or null if
* ObjectStreamField is not associated with an actual field.
*/
Field getField() {
return field;
}
/**
* Returns JVM type signature of field (similar to getTypeString, except
* that signature strings are returned for primitive fields as well).
*/
String getSignature() {
lazyInitSignature();
return signature;
}
/**
* Returns JVM type signature for given class.
*/
private static String getClassSignature(Class<?> cl) {
StringBuilder sbuf = new StringBuilder();
while (cl.isArray()) {
sbuf.append('[');
cl = cl.getComponentType();
}
if (cl.isPrimitive()) {
if (cl == Integer.TYPE) {
sbuf.append('I');
} else if (cl == Byte.TYPE) {
sbuf.append('B');
} else if (cl == Long.TYPE) {
sbuf.append('J');
} else if (cl == Float.TYPE) {
sbuf.append('F');
} else if (cl == Double.TYPE) {
sbuf.append('D');
} else if (cl == Short.TYPE) {
sbuf.append('S');
} else if (cl == Character.TYPE) {
sbuf.append('C');
} else if (cl == Boolean.TYPE) {
sbuf.append('Z');
} else if (cl == Void.TYPE) {
sbuf.append('V');
} else {
throw new InternalError();
}
} else {
sbuf.append('L' + cl.getName().replace('.', '/') + ';');
}
return sbuf.toString();
}
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More