提交 cc465e7b 编写于 作者: C coffeys

Merge

......@@ -295,7 +295,14 @@ public class AquaIcon {
}
Image createImage() {
return AquaUtils.getCImageCreator().createSystemImageFromSelector(selector, getIconWidth(), getIconHeight());
int w = getIconWidth();
int h = getIconHeight();
return new AquaImageFactory.MultiResolutionIconImage(
AquaUtils.getCImageCreator().createSystemImageFromSelector(
selector, w, h),
AquaUtils.getCImageCreator().createSystemImageFromSelector(
selector, 2 * w, 2 * h)
);
}
}
}
......@@ -46,6 +46,9 @@ import com.apple.laf.AquaIcon.JRSUIControlSpec;
import com.apple.laf.AquaIcon.SystemIcon;
import com.apple.laf.AquaUtils.RecyclableObject;
import com.apple.laf.AquaUtils.RecyclableSingleton;
import java.util.Arrays;
import java.util.List;
import sun.awt.image.MultiResolutionImage;
public class AquaImageFactory {
public static IconUIResource getConfirmImageIcon() {
......@@ -120,28 +123,48 @@ public class AquaImageFactory {
private static final int kAlertIconSize = 64;
static IconUIResource getAppIconCompositedOn(final Image background) {
final double scaleFactor = 1.0; // revise for HiDPI
final int kAlertSubIconSize = (int)(kAlertIconSize * 0.5 * scaleFactor);
final int kAlertSubIconInset = (int)(kAlertIconSize * scaleFactor) - kAlertSubIconSize;
final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon(kAlertSubIconSize, kAlertSubIconSize) {
final BufferedImage iconImage = getAppIconImageCompositedOn(background, 1);
if (background instanceof MultiResolutionIconImage) {
BufferedImage background2x
= ((MultiResolutionIconImage) background).resolutionVariant;
BufferedImage icon2xImage = getAppIconImageCompositedOn(background2x, 2);
return new IconUIResource(new ImageIcon(
new MultiResolutionIconImage(iconImage, icon2xImage)));
}
return new IconUIResource(new ImageIcon(iconImage));
}
static BufferedImage getAppIconImageCompositedOn(final Image background, int scaleFactor) {
final int scaledAlertIconSize = kAlertIconSize * scaleFactor;
final int kAlertSubIconSize = (int) (scaledAlertIconSize * 0.5);
final int kAlertSubIconInset = scaledAlertIconSize - kAlertSubIconSize;
final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon(
kAlertSubIconSize, kAlertSubIconSize) {
Image createImage() {
return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize);
}
};
final BufferedImage image = new BufferedImage(kAlertIconSize, kAlertIconSize, BufferedImage.TYPE_INT_ARGB);
final BufferedImage image = new BufferedImage(scaledAlertIconSize,
scaledAlertIconSize, BufferedImage.TYPE_INT_ARGB);
final Graphics g = image.getGraphics();
g.drawImage(background, 0, 0, (int)(kAlertIconSize * scaleFactor), (int)(kAlertIconSize * scaleFactor), null);
g.drawImage(background, 0, 0,
scaledAlertIconSize, scaledAlertIconSize, null);
if (g instanceof Graphics2D) {
// improves icon rendering quality in Quartz
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
}
smallAppIconScaled.paintIcon(null, g, kAlertSubIconInset, kAlertSubIconInset);
smallAppIconScaled.paintIcon(null, g,
kAlertSubIconInset, kAlertSubIconInset);
g.dispose();
return new IconUIResource(new ImageIcon(image));
return image;
}
public static IconUIResource getTreeFolderIcon() {
......@@ -484,4 +507,29 @@ public class AquaImageFactory {
public static Color getSelectionInactiveForegroundColorUIResource() {
return new SystemColorProxy(LWCToolkit.getAppleColor(LWCToolkit.INACTIVE_SELECTION_FOREGROUND_COLOR));
}
static class MultiResolutionIconImage extends BufferedImage
implements MultiResolutionImage {
BufferedImage resolutionVariant;
public MultiResolutionIconImage(BufferedImage image, BufferedImage resolutionVariant) {
super(image.getWidth(), image.getHeight(), image.getType());
this.resolutionVariant = resolutionVariant;
Graphics g = getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
}
@Override
public Image getResolutionVariant(int width, int height) {
return ((width <= getWidth() && height <= getHeight()))
? this : resolutionVariant;
}
@Override
public List<Image> getResolutionVariants() {
return Arrays.asList(this, resolutionVariant);
}
}
}
......@@ -38,6 +38,8 @@ public class CCustomCursor extends Cursor {
Image fImage;
Point fHotspot;
int fWidth;
int fHeight;
public CCustomCursor(final Image cursor, final Point hotSpot, final String name) throws IndexOutOfBoundsException, HeadlessException {
super(name);
......@@ -50,6 +52,7 @@ public class CCustomCursor extends Cursor {
// Make sure image is fully loaded.
final Component c = new Canvas(); // for its imageUpdate method
final MediaTracker tracker = new MediaTracker(c);
// MediaTracker loads resolution variants from MultiResolution Toolkit image
tracker.addImage(fImage, 0);
try {
tracker.waitForAll();
......@@ -67,14 +70,14 @@ public class CCustomCursor extends Cursor {
width = height = 1;
fImage = createTransparentImage(width, height);
} else {
// Scale image to nearest supported size
// Get the nearest supported cursor size
final Dimension nativeSize = toolkit.getBestCursorSize(width, height);
if (nativeSize.width != width || nativeSize.height != height) {
fImage = fImage.getScaledInstance(nativeSize.width, nativeSize.height, Image.SCALE_DEFAULT);
width = nativeSize.width;
height = nativeSize.height;
}
}
fWidth = width;
fHeight = height;
// NOTE: this was removed for 3169146, but in 1.5 the JCK tests for an exception and fails if one isn't thrown.
// See what JBuilder does.
......@@ -138,6 +141,7 @@ public class CCustomCursor extends Cursor {
// failed to do its job. Return null to keep the cursor unchanged.
return 0L;
} else {
fCImage.resizeRepresentations(fWidth, fHeight);
return fCImage.ptr;
}
} catch (IllegalArgumentException iae) {
......
......@@ -31,6 +31,7 @@ import java.awt.image.*;
import java.util.Arrays;
import java.util.List;
import sun.awt.image.MultiResolutionImage;
import sun.awt.image.SunWritableRaster;
......@@ -44,6 +45,7 @@ public class CImage extends CFRetainedResource {
private static native void nativeCopyNSImageIntoArray(long image, int[] buffer, int w, int h);
private static native Dimension2D nativeGetNSImageSize(long image);
private static native void nativeSetNSImageSize(long image, double w, double h);
private static native void nativeResizeNSImageRepresentations(long image, double w, double h);
static Creator creator = new Creator();
static Creator getCreator() {
......@@ -145,6 +147,12 @@ public class CImage extends CFRetainedResource {
// This is used to create a CImage from a Image
public CImage createFromImage(final Image image) {
if (image instanceof MultiResolutionImage) {
List<Image> resolutionVariants
= ((MultiResolutionImage) image).getResolutionVariants();
return createFromImages(resolutionVariants);
}
int[] buffer = imageToArray(image, true);
if (buffer == null) {
return null;
......@@ -223,4 +231,8 @@ public class CImage extends CFRetainedResource {
if (ptr != 0) nativeSetNSImageSize(ptr, w, h);
return this;
}
void resizeRepresentations(double w, double h) {
if (ptr != 0) nativeResizeNSImageRepresentations(ptr, w, h);
}
}
......@@ -35,14 +35,17 @@ import java.awt.event.KeyEvent;
import java.awt.im.InputMethodHighlight;
import java.awt.peer.*;
import java.lang.reflect.*;
import java.net.URL;
import java.security.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.net.MalformedURLException;
import sun.awt.*;
import sun.lwawt.*;
import sun.lwawt.LWWindowPeer.PeerType;
import sun.security.action.GetBooleanAction;
import sun.awt.image.MultiResolutionImage;
import sun.util.CoreResourceBundleControl;
......@@ -489,11 +492,32 @@ public final class LWCToolkit extends LWToolkit {
@Override
public Image getImage(final String filename) {
final Image nsImage = checkForNSImage(filename);
if (nsImage != null) return nsImage;
if (nsImage != null) {
return nsImage;
}
if (imageCached(filename)) {
return super.getImage(filename);
}
String fileneame2x = getScaledImageName(filename);
return (imageExists(fileneame2x))
? getImageWithResolutionVariant(filename, fileneame2x)
: super.getImage(filename);
}
@Override
public Image getImage(URL url) {
if (imageCached(url)) {
return super.getImage(url);
}
URL url2x = getScaledImageURL(url);
return (imageExists(url2x))
? getImageWithResolutionVariant(url, url2x) : super.getImage(url);
}
static final String nsImagePrefix = "NSImage://";
protected Image checkForNSImage(final String imageName) {
if (imageName == null) return null;
......@@ -781,4 +805,36 @@ public final class LWCToolkit extends LWToolkit {
public boolean enableInputMethodsForTextComponent() {
return true;
}
private static URL getScaledImageURL(URL url) {
try {
String scaledImagePath = getScaledImageName(url.getPath());
return scaledImagePath == null ? null : new URL(url.getProtocol(),
url.getHost(), url.getPort(), scaledImagePath);
} catch (MalformedURLException e) {
return null;
}
}
private static String getScaledImageName(String path) {
if (!isValidPath(path)) {
return null;
}
int slash = path.lastIndexOf('/');
String name = (slash < 0) ? path : path.substring(slash + 1);
if (name.contains("@2x")) {
return null;
}
int dot = name.lastIndexOf('.');
String name2x = (dot < 0) ? name + "@2x"
: name.substring(0, dot) + "@2x" + name.substring(dot);
return (slash < 0) ? name2x : path.substring(0, slash + 1) + name2x;
}
private static boolean isValidPath(String path) {
return !path.isEmpty() && !path.endsWith("/") && !path.endsWith(".");
}
}
......@@ -320,3 +320,26 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CImage
* Method: nativeResizeNSImageRepresentations
* Signature: (JDD)V
*/
JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CImage_nativeResizeNSImageRepresentations
(JNIEnv *env, jclass clazz, jlong image, jdouble w, jdouble h)
{
if (!image) return;
NSImage *i = (NSImage *)jlong_to_ptr(image);
JNF_COCOA_ENTER(env);
NSImageRep *imageRep = nil;
NSArray *imageRepresentations = [i representations];
NSEnumerator *imageEnumerator = [imageRepresentations objectEnumerator];
while ((imageRep = [imageEnumerator nextObject]) != nil) {
[imageRep setSize:NSMakeSize(w, h)];
}
JNF_COCOA_EXIT(env);
}
......@@ -187,9 +187,8 @@ Java_sun_lwawt_macosx_CRobot_mouseEvent
// volatile, otherwise it warns that it might be clobbered by 'longjmp'
volatile CGPoint point;
// Translate the device relative point into a valid global CGPoint.
point.x = mouseLastX + globalDeviceBounds.origin.x;
point.y = mouseLastY + globalDeviceBounds.origin.y;
point.x = mouseLastX;
point.y = mouseLastY;
__block CGMouseButton button = kCGMouseButtonLeft;
__block CGEventType type = kCGEventMouseMoved;
......
......@@ -28,6 +28,7 @@ package java.awt;
import java.awt.Component;
import java.awt.Image;
import java.awt.image.ImageObserver;
import sun.awt.image.MultiResolutionToolkitImage;
/**
* The <code>MediaTracker</code> class is a utility class to track
......@@ -222,10 +223,17 @@ public class MediaTracker implements java.io.Serializable {
* @param h the height at which the image is rendered
*/
public synchronized void addImage(Image image, int id, int w, int h) {
addImageImpl(image, id, w, h);
Image rvImage = getResolutionVariant(image);
if (rvImage != null) {
addImageImpl(rvImage, id, 2 * w, 2 * h);
}
}
private void addImageImpl(Image image, int id, int w, int h) {
head = MediaEntry.insert(head,
new ImageMediaEntry(this, image, id, w, h));
}
/**
* Flag indicating that media is currently being loaded.
* @see java.awt.MediaTracker#statusAll
......@@ -719,6 +727,15 @@ public class MediaTracker implements java.io.Serializable {
* @since JDK1.1
*/
public synchronized void removeImage(Image image) {
removeImageImpl(image);
Image rvImage = getResolutionVariant(image);
if (rvImage != null) {
removeImageImpl(rvImage);
}
notifyAll(); // Notify in case remaining images are "done".
}
private void removeImageImpl(Image image) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
......@@ -735,7 +752,6 @@ public class MediaTracker implements java.io.Serializable {
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
/**
......@@ -750,6 +766,15 @@ public class MediaTracker implements java.io.Serializable {
* @since JDK1.1
*/
public synchronized void removeImage(Image image, int id) {
removeImageImpl(image, id);
Image rvImage = getResolutionVariant(image);
if (rvImage != null) {
removeImageImpl(rvImage, id);
}
notifyAll(); // Notify in case remaining images are "done".
}
private void removeImageImpl(Image image, int id) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
......@@ -766,7 +791,6 @@ public class MediaTracker implements java.io.Serializable {
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
/**
......@@ -783,6 +807,16 @@ public class MediaTracker implements java.io.Serializable {
*/
public synchronized void removeImage(Image image, int id,
int width, int height) {
removeImageImpl(image, id, width, height);
Image rvImage = getResolutionVariant(image);
if (rvImage != null) {
removeImageImpl(rvImage, id, 2 * width, 2 * height);
}
notifyAll(); // Notify in case remaining images are "done".
}
private void removeImageImpl(Image image, int id, int width, int height) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
......@@ -801,12 +835,18 @@ public class MediaTracker implements java.io.Serializable {
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
synchronized void setDone() {
notifyAll();
}
private static Image getResolutionVariant(Image image) {
if (image instanceof MultiResolutionToolkitImage) {
return ((MultiResolutionToolkitImage) image).getResolutionVariant();
}
return null;
}
}
abstract class MediaEntry {
......
/*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2014, 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
......@@ -72,9 +72,6 @@ public class Robot {
private int autoDelay = 0;
private static int LEGAL_BUTTON_MASK = 0;
// location of robot's GC, used in mouseMove(), getPixelColor() and captureScreenImage()
private Point gdLoc;
private DirectColorModel screenCapCM = null;
/**
......@@ -132,7 +129,6 @@ public class Robot {
private void init(GraphicsDevice screen) throws AWTException {
checkRobotAllowed();
gdLoc = screen.getDefaultConfiguration().getBounds().getLocation();
Toolkit toolkit = Toolkit.getDefaultToolkit();
if (toolkit instanceof ComponentFactory) {
peer = ((ComponentFactory)toolkit).createRobot(this, screen);
......@@ -200,7 +196,7 @@ public class Robot {
* @param y Y position
*/
public synchronized void mouseMove(int x, int y) {
peer.mouseMove(gdLoc.x + x, gdLoc.y + y);
peer.mouseMove(x, y);
afterEvent();
}
......@@ -395,7 +391,7 @@ public class Robot {
* @return Color of the pixel
*/
public synchronized Color getPixelColor(int x, int y) {
Color color = new Color(peer.getRGBPixel(gdLoc.x + x, gdLoc.y + y));
Color color = new Color(peer.getRGBPixel(x, y));
return color;
}
......@@ -412,10 +408,7 @@ public class Robot {
public synchronized BufferedImage createScreenCapture(Rectangle screenRect) {
checkScreenCaptureAllowed();
// according to the spec, screenRect is relative to robot's GD
Rectangle translatedRect = new Rectangle(screenRect);
translatedRect.translate(gdLoc.x, gdLoc.y);
checkValidRect(translatedRect);
checkValidRect(screenRect);
BufferedImage image;
DataBufferInt buffer;
......@@ -441,14 +434,14 @@ public class Robot {
int pixels[];
int[] bandmasks = new int[3];
pixels = peer.getRGBPixels(translatedRect);
pixels = peer.getRGBPixels(screenRect);
buffer = new DataBufferInt(pixels, pixels.length);
bandmasks[0] = screenCapCM.getRedMask();
bandmasks[1] = screenCapCM.getGreenMask();
bandmasks[2] = screenCapCM.getBlueMask();
raster = Raster.createPackedRaster(buffer, translatedRect.width, translatedRect.height, translatedRect.width, bandmasks, null);
raster = Raster.createPackedRaster(buffer, screenRect.width, screenRect.height, screenRect.width, bandmasks, null);
SunWritableRaster.makeTrackable(buffer);
image = new BufferedImage(screenCapCM, raster, false, null);
......
......@@ -172,7 +172,7 @@ public class SunHints {
}
}
private static final int NUM_KEYS = 9;
private static final int NUM_KEYS = 10;
private static final int VALS_PER_KEY = 8;
/**
......@@ -252,6 +252,13 @@ public class SunHints {
@Native public static final int INTVAL_STROKE_NORMALIZE = 1;
@Native public static final int INTVAL_STROKE_PURE = 2;
/**
* Image scaling hint key and values
*/
@Native public static final int INTKEY_RESOLUTION_VARIANT = 9;
@Native public static final int INTVAL_RESOLUTION_VARIANT_DEFAULT = 0;
@Native public static final int INTVAL_RESOLUTION_VARIANT_OFF = 1;
@Native public static final int INTVAL_RESOLUTION_VARIANT_ON = 2;
/**
* LCD text contrast control hint key.
* Value is "100" to make discontiguous with the others which
......@@ -450,6 +457,24 @@ public class SunHints {
SunHints.INTVAL_STROKE_PURE,
"Pure stroke conversion for accurate paths");
/**
* Image resolution variant hint key and value objects
*/
public static final Key KEY_RESOLUTION_VARIANT =
new SunHints.Key(SunHints.INTKEY_RESOLUTION_VARIANT,
"Global image resolution variant key");
public static final Object VALUE_RESOLUTION_VARIANT_DEFAULT =
new SunHints.Value(KEY_RESOLUTION_VARIANT,
SunHints.INTVAL_RESOLUTION_VARIANT_DEFAULT,
"Choose image resolutions based on a default heuristic");
public static final Object VALUE_RESOLUTION_VARIANT_OFF =
new SunHints.Value(KEY_RESOLUTION_VARIANT,
SunHints.INTVAL_RESOLUTION_VARIANT_OFF,
"Use only the standard resolution of an image");
public static final Object VALUE_RESOLUTION_VARIANT_ON =
new SunHints.Value(KEY_RESOLUTION_VARIANT,
SunHints.INTVAL_RESOLUTION_VARIANT_ON,
"Always use resolution-specific variants of images");
public static class LCDContrastKey extends Key {
......
......@@ -36,6 +36,9 @@ import java.awt.image.*;
import java.awt.TrayIcon;
import java.awt.SystemTray;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
......@@ -715,33 +718,7 @@ public abstract class SunToolkit extends Toolkit
static final SoftCache imgCache = new SoftCache();
static Image getImageFromHash(Toolkit tk, URL url) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
java.security.Permission perm =
url.openConnection().getPermission();
if (perm != null) {
try {
sm.checkPermission(perm);
} catch (SecurityException se) {
// fallback to checkRead/checkConnect for pre 1.2
// security managers
if ((perm instanceof java.io.FilePermission) &&
perm.getActions().indexOf("read") != -1) {
sm.checkRead(perm.getName());
} else if ((perm instanceof
java.net.SocketPermission) &&
perm.getActions().indexOf("connect") != -1) {
sm.checkConnect(url.getHost(), url.getPort());
} else {
throw se;
}
}
}
} catch (java.io.IOException ioe) {
sm.checkConnect(url.getHost(), url.getPort());
}
}
checkPermissions(url);
synchronized (imgCache) {
Image img = (Image)imgCache.get(url);
if (img == null) {
......@@ -757,10 +734,7 @@ public abstract class SunToolkit extends Toolkit
static Image getImageFromHash(Toolkit tk,
String filename) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(filename);
}
checkPermissions(filename);
synchronized (imgCache) {
Image img = (Image)imgCache.get(filename);
if (img == null) {
......@@ -782,42 +756,42 @@ public abstract class SunToolkit extends Toolkit
return getImageFromHash(this, url);
}
public Image createImage(String filename) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(filename);
protected Image getImageWithResolutionVariant(String fileName,
String resolutionVariantName) {
synchronized (imgCache) {
Image image = getImageFromHash(this, fileName);
if (image instanceof MultiResolutionImage) {
return image;
}
return createImage(new FileImageSource(filename));
Image resolutionVariant = getImageFromHash(this, resolutionVariantName);
image = createImageWithResolutionVariant(image, resolutionVariant);
imgCache.put(fileName, image);
return image;
}
public Image createImage(URL url) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
java.security.Permission perm =
url.openConnection().getPermission();
if (perm != null) {
try {
sm.checkPermission(perm);
} catch (SecurityException se) {
// fallback to checkRead/checkConnect for pre 1.2
// security managers
if ((perm instanceof java.io.FilePermission) &&
perm.getActions().indexOf("read") != -1) {
sm.checkRead(perm.getName());
} else if ((perm instanceof
java.net.SocketPermission) &&
perm.getActions().indexOf("connect") != -1) {
sm.checkConnect(url.getHost(), url.getPort());
} else {
throw se;
}
protected Image getImageWithResolutionVariant(URL url,
URL resolutionVariantURL) {
synchronized (imgCache) {
Image image = getImageFromHash(this, url);
if (image instanceof MultiResolutionImage) {
return image;
}
Image resolutionVariant = getImageFromHash(this, resolutionVariantURL);
image = createImageWithResolutionVariant(image, resolutionVariant);
imgCache.put(url, image);
return image;
}
} catch (java.io.IOException ioe) {
sm.checkConnect(url.getHost(), url.getPort());
}
public Image createImage(String filename) {
checkPermissions(filename);
return createImage(new FileImageSource(filename));
}
public Image createImage(URL url) {
checkPermissions(url);
return createImage(new URLImageSource(url));
}
......@@ -829,6 +803,11 @@ public abstract class SunToolkit extends Toolkit
return new ToolkitImage(producer);
}
public static Image createImageWithResolutionVariant(Image image,
Image resolutionVariant) {
return new MultiResolutionToolkitImage(image, resolutionVariant);
}
public int checkImage(Image img, int w, int h, ImageObserver o) {
if (!(img instanceof ToolkitImage)) {
return ImageObserver.ALLBITS;
......@@ -841,7 +820,7 @@ public abstract class SunToolkit extends Toolkit
} else {
repbits = tkimg.getImageRep().check(o);
}
return tkimg.check(o) | repbits;
return (tkimg.check(o) | repbits) & checkResolutionVariant(img, w, h, o);
}
public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
......@@ -863,7 +842,97 @@ public abstract class SunToolkit extends Toolkit
return false;
}
ImageRepresentation ir = tkimg.getImageRep();
return ir.prepare(o);
return ir.prepare(o) & prepareResolutionVariant(img, w, h, o);
}
private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) {
ToolkitImage rvImage = getResolutionVariant(img);
// Ignore the resolution variant in case of error
return (rvImage == null || rvImage.hasError()) ? 0xFFFF :
checkImage(rvImage, 2 * w, 2 * h, MultiResolutionToolkitImage.
getResolutionVariantObserver(
img, o, w, h, 2 * w, 2 * h));
}
private boolean prepareResolutionVariant(Image img, int w, int h,
ImageObserver o) {
ToolkitImage rvImage = getResolutionVariant(img);
// Ignore the resolution variant in case of error
return rvImage == null || rvImage.hasError() || prepareImage(
rvImage, 2 * w, 2 * h,
MultiResolutionToolkitImage.getResolutionVariantObserver(
img, o, w, h, 2 * w, 2 * h));
}
private static ToolkitImage getResolutionVariant(Image image) {
if (image instanceof MultiResolutionToolkitImage) {
Image resolutionVariant = ((MultiResolutionToolkitImage) image).
getResolutionVariant();
if (resolutionVariant instanceof ToolkitImage) {
return (ToolkitImage) resolutionVariant;
}
}
return null;
}
protected static boolean imageCached(Object key) {
return imgCache.containsKey(key);
}
protected static boolean imageExists(String filename) {
checkPermissions(filename);
return filename != null && new File(filename).exists();
}
@SuppressWarnings("try")
protected static boolean imageExists(URL url) {
checkPermissions(url);
if (url != null) {
try (InputStream is = url.openStream()) {
return true;
}catch(IOException e){
return false;
}
}
return false;
}
private static void checkPermissions(String filename) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(filename);
}
}
private static void checkPermissions(URL url) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
java.security.Permission perm =
url.openConnection().getPermission();
if (perm != null) {
try {
sm.checkPermission(perm);
} catch (SecurityException se) {
// fallback to checkRead/checkConnect for pre 1.2
// security managers
if ((perm instanceof java.io.FilePermission) &&
perm.getActions().indexOf("read") != -1) {
sm.checkRead(perm.getName());
} else if ((perm instanceof
java.net.SocketPermission) &&
perm.getActions().indexOf("connect") != -1) {
sm.checkConnect(url.getHost(), url.getPort());
} else {
throw se;
}
}
}
} catch (java.io.IOException ioe) {
sm.checkConnect(url.getHost(), url.getPort());
}
}
}
/**
......
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 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.
* 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
......@@ -20,66 +22,62 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.image;
/*
import java.awt.Image;
import java.util.List;
/**
* This interface is designed to provide a set of images at various resolutions.
*
* The <code>MultiResolutionImage</code> interface should be implemented by any
* class whose instances are intended to provide image resolution variants
* according to the given image width and height.
*
* For example,
* <pre>
* {@code
* public class ScaledImage extends BufferedImage
* implements MultiResolutionImage {
*
* @Override
* public Image getResolutionVariant(int width, int height) {
* return ((width <= getWidth() && height <= getHeight()))
* ? this : highResolutionImage;
* }
*
* @summary This class is used to synchronize execution of two threads.
* @author Swamy Venkataramanappa
* @Override
* public List<Image> getResolutionVariants() {
* return Arrays.asList(this, highResolutionImage);
* }
* }
* }</pre>
*
* It is recommended to cache image variants for performance reasons.
*
* <b>WARNING</b>: This class is an implementation detail. This API may change
* between update release, and it may even be removed or be moved in some other
* package(s)/class(es).
*/
public interface MultiResolutionImage {
import java.util.concurrent.Semaphore;
public class ThreadExecutionSynchronizer {
private volatile boolean waiting;
private final Semaphore semaphore;
public ThreadExecutionSynchronizer() {
semaphore = new Semaphore(1);
waiting = false;
}
// Synchronizes two threads execution points.
// Basically any thread could get scheduled to run and
// it is not possible to know which thread reaches expected
// execution point. So whichever thread reaches a execution
// point first wait for the second thread. When the second thread
// reaches the expected execution point will wake up
// the thread which is waiting here.
void stopOrGo() {
semaphore.acquireUninterruptibly(); // Thread can get blocked.
if (!waiting) {
waiting = true;
// Wait for second thread to enter this method.
while(!semaphore.hasQueuedThreads()) {
try {
Thread.sleep(20);
} catch (InterruptedException xx) {}
}
semaphore.release();
} else {
waiting = false;
semaphore.release();
}
}
// Wrapper function just for code readability.
void waitForSignal() {
stopOrGo();
goSleep(50);
}
void signal() {
stopOrGo();
goSleep(50);
}
/**
* Provides an image with necessary resolution which best fits to the given
* image width and height.
*
* @param width the desired image resolution width.
* @param height the desired image resolution height.
* @return image resolution variant.
*
* @since JDK1.8
*/
public Image getResolutionVariant(int width, int height);
private static void goSleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Unexpected exception.");
}
}
/**
* Gets list of all resolution variants including the base image
*
* @return list of resolution variants.
* @since JDK1.8
*/
public List<Image> getResolutionVariants();
}
/*
* Copyright (c) 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 sun.awt.image;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.util.Arrays;
import java.util.List;
import sun.misc.SoftCache;
public class MultiResolutionToolkitImage extends ToolkitImage implements MultiResolutionImage {
Image resolutionVariant;
public MultiResolutionToolkitImage(Image lowResolutionImage, Image resolutionVariant) {
super(lowResolutionImage.getSource());
this.resolutionVariant = resolutionVariant;
}
@Override
public Image getResolutionVariant(int width, int height) {
return ((width <= getWidth() && height <= getHeight()))
? this : resolutionVariant;
}
public Image getResolutionVariant() {
return resolutionVariant;
}
@Override
public List<Image> getResolutionVariants() {
return Arrays.<Image>asList(this, resolutionVariant);
}
private static final int BITS_INFO = ImageObserver.SOMEBITS
| ImageObserver.FRAMEBITS | ImageObserver.ALLBITS;
private static class ObserverCache {
static final SoftCache INSTANCE = new SoftCache();
}
public static ImageObserver getResolutionVariantObserver(
final Image image, final ImageObserver observer,
final int imgWidth, final int imgHeight,
final int rvWidth, final int rvHeight) {
if (observer == null) {
return null;
}
synchronized (ObserverCache.INSTANCE) {
ImageObserver o = (ImageObserver) ObserverCache.INSTANCE.get(image);
if (o == null) {
o = (Image resolutionVariant, int flags,
int x, int y, int width, int height) -> {
if ((flags & (ImageObserver.WIDTH | BITS_INFO)) != 0) {
width = (width + 1) / 2;
}
if ((flags & (ImageObserver.HEIGHT | BITS_INFO)) != 0) {
height = (height + 1) / 2;
}
if ((flags & BITS_INFO) != 0) {
x /= 2;
y /= 2;
}
return observer.imageUpdate(
image, flags, x, y, width, height);
};
ObserverCache.INSTANCE.put(image, o);
}
return o;
}
}
}
......@@ -61,6 +61,7 @@ import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.text.AttributedCharacterIterator;
import java.awt.Font;
import java.awt.Point;
import java.awt.image.ImageObserver;
import java.awt.Transparency;
import java.awt.font.GlyphVector;
......@@ -93,6 +94,13 @@ import java.util.Iterator;
import sun.misc.PerformanceLogger;
import java.lang.annotation.Native;
import sun.awt.image.MultiResolutionImage;
import static java.awt.geom.AffineTransform.TYPE_FLIP;
import static java.awt.geom.AffineTransform.TYPE_MASK_SCALE;
import static java.awt.geom.AffineTransform.TYPE_TRANSLATION;
import sun.awt.image.MultiResolutionToolkitImage;
import sun.awt.image.ToolkitImage;
/**
* This is a the master Graphics2D superclass for all of the Sun
......@@ -237,6 +245,7 @@ public final class SunGraphics2D
protected Region devClip; // Actual physical drawable in pixels
private final int devScale; // Actual physical scale factor
private int resolutionVariantHint;
// cached state for text rendering
private boolean validFontInfo;
......@@ -274,6 +283,7 @@ public final class SunGraphics2D
lcdTextContrast = lcdTextContrastDefaultValue;
interpolationHint = -1;
strokeHint = SunHints.INTVAL_STROKE_DEFAULT;
resolutionVariantHint = SunHints.INTVAL_RESOLUTION_VARIANT_DEFAULT;
interpolationType = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
......@@ -1249,6 +1259,10 @@ public final class SunGraphics2D
stateChanged = (strokeHint != newHint);
strokeHint = newHint;
break;
case SunHints.INTKEY_RESOLUTION_VARIANT:
stateChanged = (resolutionVariantHint != newHint);
resolutionVariantHint = newHint;
break;
default:
recognized = false;
stateChanged = false;
......@@ -1322,6 +1336,9 @@ public final class SunGraphics2D
case SunHints.INTKEY_STROKE_CONTROL:
return SunHints.Value.get(SunHints.INTKEY_STROKE_CONTROL,
strokeHint);
case SunHints.INTKEY_RESOLUTION_VARIANT:
return SunHints.Value.get(SunHints.INTKEY_RESOLUTION_VARIANT,
resolutionVariantHint);
}
return null;
}
......@@ -3050,18 +3067,58 @@ public final class SunGraphics2D
}
// end of text rendering methods
private static boolean isHiDPIImage(final Image img) {
return SurfaceManager.getImageScale(img) != 1;
private boolean isHiDPIImage(final Image img) {
return (SurfaceManager.getImageScale(img) != 1) ||
(resolutionVariantHint != SunHints.INTVAL_RESOLUTION_VARIANT_OFF
&& img instanceof MultiResolutionImage);
}
private boolean drawHiDPIImage(Image img, int dx1, int dy1, int dx2,
int dy2, int sx1, int sy1, int sx2, int sy2,
Color bgcolor, ImageObserver observer) {
if (SurfaceManager.getImageScale(img) != 1) { // Volatile Image
final int scale = SurfaceManager.getImageScale(img);
sx1 = Region.clipScale(sx1, scale);
sx2 = Region.clipScale(sx2, scale);
sy1 = Region.clipScale(sy1, scale);
sy2 = Region.clipScale(sy2, scale);
} else if (img instanceof MultiResolutionImage) {
// get scaled destination image size
int width = img.getWidth(observer);
int height = img.getHeight(observer);
Image resolutionVariant = getResolutionVariant(
(MultiResolutionImage) img, width, height,
dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
if (resolutionVariant != img && resolutionVariant != null) {
// recalculate source region for the resolution variant
ImageObserver rvObserver = MultiResolutionToolkitImage.
getResolutionVariantObserver(img, observer,
width, height, -1, -1);
int rvWidth = resolutionVariant.getWidth(rvObserver);
int rvHeight = resolutionVariant.getHeight(rvObserver);
if (0 < width && 0 < height && 0 < rvWidth && 0 < rvHeight) {
float widthScale = ((float) rvWidth) / width;
float heightScale = ((float) rvHeight) / height;
sx1 = Region.clipScale(sx1, widthScale);
sy1 = Region.clipScale(sy1, heightScale);
sx2 = Region.clipScale(sx2, widthScale);
sy2 = Region.clipScale(sy2, heightScale);
observer = rvObserver;
img = resolutionVariant;
}
}
}
try {
return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1, sy1,
sx2, sy2, bgcolor, observer);
......@@ -3081,6 +3138,54 @@ public final class SunGraphics2D
}
}
private Image getResolutionVariant(MultiResolutionImage img,
int srcWidth, int srcHeight, int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2) {
if (srcWidth <= 0 || srcHeight <= 0) {
return null;
}
int sw = sx2 - sx1;
int sh = sy2 - sy1;
if (sw == 0 || sh == 0) {
return null;
}
int type = transform.getType();
int dw = dx2 - dx1;
int dh = dy2 - dy1;
double destRegionWidth;
double destRegionHeight;
if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP)) == 0) {
destRegionWidth = dw;
destRegionHeight = dh;
} else if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP | TYPE_MASK_SCALE)) == 0) {
destRegionWidth = dw * transform.getScaleX();
destRegionHeight = dh * transform.getScaleY();
} else {
destRegionWidth = dw * Math.hypot(
transform.getScaleX(), transform.getShearY());
destRegionHeight = dh * Math.hypot(
transform.getShearX(), transform.getScaleY());
}
int destImageWidth = (int) Math.abs(srcWidth * destRegionWidth / sw);
int destImageHeight = (int) Math.abs(srcHeight * destRegionHeight / sh);
Image resolutionVariant
= img.getResolutionVariant(destImageWidth, destImageHeight);
if (resolutionVariant instanceof ToolkitImage
&& ((ToolkitImage) resolutionVariant).hasError()) {
return null;
}
return resolutionVariant;
}
/**
* Draws an image scaled to x,y,w,h in nonblocking mode with a
* callback object.
......
/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2014, 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
......@@ -73,8 +73,9 @@ inline uint jar::get_crc32(uint c, uchar *ptr, uint len) { return crc32(c, ptr,
SWAP_BYTES(a & 0xFFFF)
#define GET_INT_HI(a) \
SWAP_BYTES((a >> 16) & 0xFFFF);
SWAP_BYTES((a >> 16) & 0xFFFF)
static const ushort jarmagic[2] = { SWAP_BYTES(0xCAFE), 0 };
void jar::init(unpacker* u_) {
BYTES_OF(*this).clear();
......@@ -105,13 +106,14 @@ void jar::add_to_jar_directory(const char* fname, bool store, int modtime,
header[0] = (ushort)SWAP_BYTES(0x4B50);
header[1] = (ushort)SWAP_BYTES(0x0201);
header[2] = (ushort)SWAP_BYTES(0xA);
header[2] = (ushort)SWAP_BYTES(( store ) ? 0x0A : 0x14);
// required version
header[3] = (ushort)SWAP_BYTES(0xA);
header[3] = (ushort)SWAP_BYTES(( store ) ? 0x0A : 0x14);
// flags 02 = maximum sub-compression flag
header[4] = ( store ) ? 0x0 : SWAP_BYTES(0x2);
// Flags - UTF-8 compression and separating crc and sizes
// into separate headers for deflated file
header[4] = ( store ) ? SWAP_BYTES(0x0800) : 0x0808;
// Compression method 8=deflate.
header[5] = ( store ) ? 0x0 : SWAP_BYTES(0x08);
......@@ -135,7 +137,8 @@ void jar::add_to_jar_directory(const char* fname, bool store, int modtime,
// Filename length
header[14] = (ushort)SWAP_BYTES(fname_length);
// So called "extra field" length.
header[15] = 0;
// If it's the first record we must add JAR magic sequence
header[15] = ( central_directory_count ) ? 0 : (ushort)SWAP_BYTES(4);
// So called "comment" length.
header[16] = 0;
// Disk number start
......@@ -155,6 +158,11 @@ void jar::add_to_jar_directory(const char* fname, bool store, int modtime,
// Copy the fname to the header.
central_directory.append(fname, fname_length);
// Add jar magic for the first record
if (central_directory_count == 0) {
central_directory.append((void *)jarmagic, sizeof(jarmagic));
}
central_directory_count++;
}
......@@ -170,10 +178,10 @@ void jar::write_jar_header(const char* fname, bool store, int modtime,
header[1] = (ushort)SWAP_BYTES(0x0403);
// Version
header[2] = (ushort)SWAP_BYTES(0xA);
header[2] = (ushort)SWAP_BYTES(( store ) ? 0x0A : 0x14);
// flags 02 = maximum sub-compression flag
header[3] = ( store ) ? 0x0 : SWAP_BYTES(0x2);
// General purpose flags - same as in the Central Directory
header[3] = ( store ) ? SWAP_BYTES(0x0800) : 0x0808;
// Compression method = deflate
header[4] = ( store ) ? 0x0 : SWAP_BYTES(0x08);
......@@ -182,28 +190,51 @@ void jar::write_jar_header(const char* fname, bool store, int modtime,
header[5] = (ushort)GET_INT_LO(dostime);
header[6] = (ushort)GET_INT_HI(dostime);
// CRC
header[7] = (ushort)GET_INT_LO(crc);
header[8] = (ushort)GET_INT_HI(crc);
// CRC, 0 if deflated, will come separately in extra header
header[7] = ( store ) ? (ushort)GET_INT_LO(crc) : 0;
header[8] = ( store ) ? (ushort)GET_INT_HI(crc) : 0;
// Compressed length:
header[9] = (ushort)GET_INT_LO(clen);
header[10] = (ushort)GET_INT_HI(clen);
// Compressed length, 0 if deflated
header[9] = ( store ) ? (ushort)GET_INT_LO(clen) : 0;
header[10] = ( store ) ? (ushort)GET_INT_HI(clen) : 0;
// Uncompressed length.
header[11] = (ushort)GET_INT_LO(len);
header[12] = (ushort)GET_INT_HI(len);
// Uncompressed length, 0 if deflated
header[11] = ( store ) ? (ushort)GET_INT_LO(len) : 0;
header[12] = ( store ) ? (ushort)GET_INT_HI(len) : 0;
// Filename length
header[13] = (ushort)SWAP_BYTES(fname_length);
// So called "extra field" length.
header[14] = 0;
header[14] = ( central_directory_count - 1 ) ? 0 : (ushort)SWAP_BYTES(4);
// Write the LOC header to the output file.
write_data(header, (int)sizeof(header));
// Copy the fname to the header.
write_data((char*)fname, (int)fname_length);
if (central_directory_count == 1) {
// Write JAR magic sequence
write_data((void *)jarmagic, (int)sizeof(jarmagic));
}
}
void jar::write_jar_extra(int len, int clen, uint crc) {
ushort header[8];
// Extra field signature
header[0] = (ushort)SWAP_BYTES(0x4B50);
header[1] = (ushort)SWAP_BYTES(0x0807);
// CRC
header[2] = (ushort)GET_INT_LO(crc);
header[3] = (ushort)GET_INT_HI(crc);
// Compressed length
header[4] = (ushort)GET_INT_LO(clen);
header[5] = (ushort)GET_INT_HI(clen);
// Uncompressed length
header[6] = (ushort)GET_INT_LO(len);
header[7] = (ushort)GET_INT_HI(len);
write_data(header, sizeof(header));
}
static const char marker_comment[] = ZIP_ARCHIVE_MARKER_COMMENT;
......@@ -212,6 +243,7 @@ void jar::write_central_directory() {
bytes mc; mc.set(marker_comment);
ushort header[11];
ushort header64[38];
// Create the End of Central Directory structure.
header[0] = (ushort)SWAP_BYTES(0x4B50);
......@@ -220,8 +252,8 @@ void jar::write_central_directory() {
header[2] = 0;
header[3] = 0;
// Number of entries in central directory.
header[4] = (ushort)SWAP_BYTES(central_directory_count);
header[5] = (ushort)SWAP_BYTES(central_directory_count);
header[4] = ( central_directory_count >= 0xffff ) ? 0xffff : (ushort)SWAP_BYTES(central_directory_count);
header[5] = ( central_directory_count >= 0xffff ) ? 0xffff : (ushort)SWAP_BYTES(central_directory_count);
// Size of the central directory}
header[6] = (ushort)GET_INT_LO((int)central_directory.size());
header[7] = (ushort)GET_INT_HI((int)central_directory.size());
......@@ -229,12 +261,71 @@ void jar::write_central_directory() {
header[8] = (ushort)GET_INT_LO(output_file_offset);
header[9] = (ushort)GET_INT_HI(output_file_offset);
// zipfile comment length;
header [10] = (ushort)SWAP_BYTES((int)mc.len);
header[10] = (ushort)SWAP_BYTES((int)mc.len);
// Write the central directory.
PRINTCR((2, "Central directory at %d\n", output_file_offset));
write_data(central_directory.b);
// If number of records exceeds the 0xFFFF we need to prepend extended
// Zip64 End of Central Directory record and its locator to the old
// style ECD record
if (central_directory_count > 0xFFFF) {
// Zip64 END signature
header64[0] = (ushort)SWAP_BYTES(0x4B50);
header64[1] = (ushort)0x0606;
// Size of header (long)
header64[2] = (ushort)SWAP_BYTES(44);;
header64[3] = 0;
header64[4] = 0;
header64[5] = 0;
// Version produced and required (short)
header64[6] = (ushort)SWAP_BYTES(45);
header64[7] = (ushort)SWAP_BYTES(45);
// Current disk number (int)
header64[8] = 0;
header64[9] = 0;
// Central directory start disk (int)
header64[10] = 0;
header64[11] = 0;
// Count of records on disk (long)
header64[12] = (ushort)GET_INT_LO(central_directory_count);
header64[13] = (ushort)GET_INT_HI(central_directory_count);
header64[14] = 0;
header64[15] = 0;
// Count of records totally (long)
header64[16] = (ushort)GET_INT_LO(central_directory_count);
header64[17] = (ushort)GET_INT_HI(central_directory_count);
header64[18] = 0;
header64[19] = 0;
// Length of the central directory (long)
header64[20] = header[6];
header64[21] = header[7];
header64[22] = 0;
header64[23] = 0;
// Offset of central directory (long)
header64[24] = header[8];
header64[25] = header[9];
header64[26] = 0;
header64[27] = 0;
// Zip64 end of central directory locator
// Locator signature
header64[28] = (ushort)SWAP_BYTES(0x4B50);
header64[29] = (ushort)SWAP_BYTES(0x0706);
// Start disk number (int)
header64[30] = 0;
header64[31] = 0;
// Offset of zip64 END record (long)
header64[32] = (ushort)GET_INT_LO(output_file_offset);
header64[33] = (ushort)GET_INT_HI(output_file_offset);
header64[34] = 0;
header64[35] = 0;
// Total number of disks (int)
header64[36] = (ushort)SWAP_BYTES(1);
header64[37] = 0;
write_data(header64, (int)sizeof(header64));
}
// Write the End of Central Directory structure.
PRINTCR((2, "end-of-directory at %d\n", output_file_offset));
write_data(header, (int)sizeof(header));
......@@ -286,6 +377,8 @@ void jar::addJarEntry(const char* fname,
if (deflate) {
write_data(deflated.b);
// Write deflated information in extra header
write_jar_extra(len, clen, crc);
} else {
write_data(head);
write_data(tail);
......@@ -368,7 +461,7 @@ bool jar::deflate_bytes(bytes& head, bytes& tail) {
// NOTE: the window size should always be -MAX_WBITS normally -15.
// unzip/zipup.c and java/Deflater.c
int error = deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED,
int error = deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
-MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
if (error != Z_OK) {
switch (error) {
......@@ -414,7 +507,8 @@ bool jar::deflate_bytes(bytes& head, bytes& tail) {
error = deflate(&zs, Z_FINISH);
}
if (error == Z_STREAM_END) {
if (len > (int)zs.total_out ) {
if ((int)zs.total_out > 0) {
// Even if compressed size is bigger than uncompressed, write it
PRINTCR((2, "deflate compressed data %d -> %d\n", len, zs.total_out));
deflated.b.len = zs.total_out;
deflateEnd(&zs);
......
/*
* Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2014, 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
......@@ -40,7 +40,7 @@ struct jar {
// Private members
fillbytes central_directory;
ushort central_directory_count;
uint central_directory_count;
uint output_file_offset;
fillbytes deflated; // temporary buffer
......@@ -74,6 +74,7 @@ struct jar {
int len, int clen, uLong crc);
void write_jar_header(const char* fname, bool store, int modtime,
int len, int clen, unsigned int crc);
void write_jar_extra(int len, int clen, unsigned int crc);
void write_central_directory();
uLong dostime(int y, int n, int d, int h, int m, int s);
uLong get_dostime(int modtime);
......
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2014, 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
......@@ -85,7 +85,7 @@ public class BadHandshakeTest {
success.set(line.contains("Listening for transport dt_socket at address:"));
return true;
},
1500,
Integer.MAX_VALUE,
TimeUnit.MILLISECONDS
);
......
<!--
Copyright (c) 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.
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.
-->
<html>
<head>
<title>High resolution custom cursor test, bug ID 8028212</title>
</head>
<body>
<applet CODE="MultiResolutionCursorTest.class" WIDTH=300 HEIGHT=100></applet>
<p> See the dialog box (usually in upper left corner) for instructions</p>
</body>
</html>
\ No newline at end of file
/*
* Copyright (c) 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.
*
* 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.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Label;
import java.awt.Point;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JApplet;
import sun.awt.OSInfo;
import sun.awt.image.MultiResolutionImage;
/**
* @test
* @bug 8028212
* @summary [macosx] Custom Cursor HiDPI support
* @author Alexander Scherbatiy
* @run applet/manual=yesno MultiResolutionCursorTest.html
*/
public class MultiResolutionCursorTest extends JApplet {
//Declare things used in the test, like buttons and labels here
static final int sizes[] = {16, 32, 128};
static final Color colors[] = {Color.WHITE, Color.RED, Color.GREEN, Color.BLUE};
public void init() {
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout(new BorderLayout());
if (OSInfo.getOSType().equals(OSInfo.OSType.MACOSX)) {
String[] instructions = {
"Verify that high resolution custom cursor is used"
+ " on HiDPI displays.",
"1) Run the test on Retina display or enable the Quartz Debug"
+ " and select the screen resolution with (HiDPI) label",
"2) Move the cursor to the Test Frame",
"3) Check that cursor has red, green or blue color",
"If so, press PASS, else press FAIL."
};
Sysout.createDialogWithInstructions(instructions);
} else {
String[] instructions = {
"This test is not applicable to the current platform. Press PASS."
};
Sysout.createDialogWithInstructions(instructions);
}
}//End init()
public void start() {
//Get things going. Request focus, set size, et cetera
setSize(200, 200);
setVisible(true);
validate();
final Image image = new MultiResolutionCursor();
int center = sizes[0] / 2;
Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(
image, new Point(center, center), "multi-resolution cursor");
Frame frame = new Frame("Test Frame");
frame.setSize(300, 300);
frame.setLocation(300, 50);
frame.add(new Label("Move cursor here"));
frame.setCursor(cursor);
frame.setVisible(true);
}// start()
static class MultiResolutionCursor extends BufferedImage implements MultiResolutionImage {
List<Image> highResolutionImages;
public MultiResolutionCursor() {
super(sizes[0], sizes[0], BufferedImage.TYPE_INT_RGB);
draw(getGraphics(), 0);
highResolutionImages = new LinkedList<>();
highResolutionImages.add(this);
for (int i = 1; i < sizes.length; i++) {
BufferedImage highResolutionImage =
new BufferedImage(sizes[i], sizes[i], BufferedImage.TYPE_INT_RGB);
draw(highResolutionImage.getGraphics(), i);
highResolutionImages.add(highResolutionImage);
}
}
@Override
public Image getResolutionVariant(int width, int height) {
for (int i = 0; i < sizes.length; i++) {
Image image = highResolutionImages.get(i);
int w = image.getWidth(null);
int h = image.getHeight(null);
if (width <= w && height <= h) {
return image;
}
}
return highResolutionImages.get(highResolutionImages.size() - 1);
}
void draw(Graphics graphics, int index) {
Graphics2D g2 = (Graphics2D) graphics;
Color color = colors[index];
g2.setColor(color);
g2.fillRect(0, 0, sizes[index], sizes[index]);
}
@Override
public List<Image> getResolutionVariants() {
return highResolutionImages;
}
}
}// class BlockedWindowTest
/* Place other classes related to the test after this line */
/**
* **************************************************
* Standard Test Machinery DO NOT modify anything below -- it's a standard chunk
* of code whose purpose is to make user interaction uniform, and thereby make
* it simpler to read and understand someone else's test.
* **************************************************
*/
/**
* This is part of the standard test machinery. It creates a dialog (with the
* instructions), and is the interface for sending text messages to the user. To
* print the instructions, send an array of strings to Sysout.createDialog
* WithInstructions method. Put one line of instructions per array entry. To
* display a message for the tester to see, simply call Sysout.println with the
* string to be displayed. This mimics System.out.println but works within the
* test harness as well as standalone.
*/
class Sysout {
private static TestDialog dialog;
public static void createDialogWithInstructions(String[] instructions) {
dialog = new TestDialog(new Frame(), "Instructions");
dialog.printInstructions(instructions);
dialog.setVisible(true);
println("Any messages for the tester will display here.");
}
public static void createDialog() {
dialog = new TestDialog(new Frame(), "Instructions");
String[] defInstr = {"Instructions will appear here. ", ""};
dialog.printInstructions(defInstr);
dialog.setVisible(true);
println("Any messages for the tester will display here.");
}
public static void printInstructions(String[] instructions) {
dialog.printInstructions(instructions);
}
public static void println(String messageIn) {
dialog.displayMessage(messageIn);
}
}// Sysout class
/**
* This is part of the standard test machinery. It provides a place for the test
* instructions to be displayed, and a place for interactive messages to the
* user to be displayed. To have the test instructions displayed, see Sysout. To
* have a message to the user be displayed, see Sysout. Do not call anything in
* this dialog directly.
*/
class TestDialog extends Dialog {
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog(Frame frame, String name) {
super(frame, name);
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
add("North", instructionsText);
messageText = new TextArea("", 5, maxStringLength, scrollBoth);
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions(String[] instructions) {
//Clear out any current instructions
instructionsText.setText("");
//Go down array of instruction strings
String printStr, remainingStr;
for (int i = 0; i < instructions.length; i++) {
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i];
while (remainingStr.length() > 0) {
//if longer than max then chop off first max chars to print
if (remainingStr.length() >= maxStringLength) {
//Try to chop on a word boundary
int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1);
if (posOfSpace <= 0) {
posOfSpace = maxStringLength - 1;
}
printStr = remainingStr.substring(0, posOfSpace + 1);
remainingStr = remainingStr.substring(posOfSpace + 1);
} //else just print
else {
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append(printStr + "\n");
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage(String messageIn) {
messageText.append(messageIn + "\n");
System.out.println(messageIn);
}
}// Te
\ No newline at end of file
/*
* Copyright (c) 2014, 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.
*
* 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.
*/
/*
@test
@bug 8013116
@summary Robot moves mouse to point which differs from set in mouseMove on
Unity shell
@author Oleg Pekhovskiy
@library ../../regtesthelpers
@build Util
@run main MultiScreenLocationTest
*/
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import test.java.awt.regtesthelpers.Util;
public class MultiScreenLocationTest {
private static final Point mouseOffset = new Point(150, 150);
private static final Point frameOffset = new Point(100, 100);
private static final Color color = Color.YELLOW;
private static String getErrorText(final String name, int screen)
{
return name + " test failed on Screen #" + screen + "!";
}
public static void main(String[] args) throws AWTException
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
if (gds.length < 2) {
System.out.println("It's a multiscreen test... skipping!");
return;
}
for (int i = 0; i < gds.length; ++i) {
GraphicsDevice gd = gds[i];
GraphicsConfiguration gc = gd.getDefaultConfiguration();
Rectangle screen = gc.getBounds();
Robot robot = new Robot(gd);
// check Robot.mouseMove()
robot.mouseMove(screen.x + mouseOffset.x, screen.y + mouseOffset.y);
Point mouse = MouseInfo.getPointerInfo().getLocation();
Point point = screen.getLocation();
point.translate(mouseOffset.x, mouseOffset.y);
if (!point.equals(mouse)) {
throw new RuntimeException(getErrorText("Robot.mouseMove", i));
}
// check Robot.getPixelColor()
Frame frame = new Frame(gc);
frame.setUndecorated(true);
frame.setSize(100, 100);
frame.setLocation(screen.x + frameOffset.x, screen.y + frameOffset.y);
frame.setBackground(color);
frame.setVisible(true);
robot.waitForIdle();
Rectangle bounds = frame.getBounds();
if (!Util.testBoundsColor(bounds, color, 5, 1000, robot)) {
throw new RuntimeException(getErrorText("Robot.getPixelColor", i));
}
// check Robot.createScreenCapture()
BufferedImage image = robot.createScreenCapture(bounds);
int rgb = color.getRGB();
if (image.getRGB(0, 0) != rgb
|| image.getRGB(image.getWidth() - 1, 0) != rgb
|| image.getRGB(image.getWidth() - 1, image.getHeight() - 1) != rgb
|| image.getRGB(0, image.getHeight() - 1) != rgb) {
throw new RuntimeException(
getErrorText("Robot.createScreenCapture", i));
}
frame.dispose();
}
System.out.println("Test PASSED!");
}
}
/*
* Copyright (c) 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.
*
* 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.
*/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import javax.imageio.ImageIO;
import sun.awt.OSInfo;
import sun.awt.SunHints;
import java.awt.MediaTracker;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.util.Arrays;
import java.util.List;
import javax.swing.JPanel;
import sun.awt.SunToolkit;
import sun.awt.image.MultiResolutionImage;
/**
* @test
* @bug 8011059
* @author Alexander Scherbatiy
* @summary [macosx] Make JDK demos look perfect on retina displays
* @run main MultiResolutionImageTest CUSTOM
* @run main MultiResolutionImageTest TOOLKIT_PREPARE
* @run main MultiResolutionImageTest TOOLKIT_LOAD
* @run main MultiResolutionImageTest TOOLKIT
*/
public class MultiResolutionImageTest {
private static final int IMAGE_WIDTH = 300;
private static final int IMAGE_HEIGHT = 200;
private static final Color COLOR_1X = Color.GREEN;
private static final Color COLOR_2X = Color.BLUE;
private static final String IMAGE_NAME_1X = "image.png";
private static final String IMAGE_NAME_2X = "image@2x.png";
public static void main(String[] args) throws Exception {
System.out.println("args: " + args.length);
if (args.length == 0) {
throw new RuntimeException("Not found a test");
}
String test = args[0];
System.out.println("TEST: " + test);
System.out.println("CHECK OS: " + checkOS());
if ("CUSTOM".equals(test)) {
testCustomMultiResolutionImage();
} else if (checkOS()) {
switch (test) {
case "CUSTOM":
break;
case "TOOLKIT_PREPARE":
testToolkitMultiResolutionImagePrepare();
break;
case "TOOLKIT_LOAD":
testToolkitMultiResolutionImageLoad();
break;
case "TOOLKIT":
testToolkitMultiResolutionImage();
testImageNameTo2xParsing();
break;
default:
throw new RuntimeException("Unknown test: " + test);
}
}
}
static boolean checkOS() {
return OSInfo.getOSType() == OSInfo.OSType.MACOSX;
}
public static void testCustomMultiResolutionImage() {
testCustomMultiResolutionImage(false);
testCustomMultiResolutionImage(true);
}
public static void testCustomMultiResolutionImage(boolean enableImageScaling) {
Image image = new MultiResolutionBufferedImage();
// Same image size
BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.drawImage(image, 0, 0, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
// Twice image size
bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
// Scale 2x
bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.scale(2, 2);
g2d.drawImage(image, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
// Rotate
bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.drawImage(image, 0, 0, null);
g2d.rotate(Math.PI / 4);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
// Scale 2x and Rotate
bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.scale(-2, 2);
g2d.rotate(-Math.PI / 10);
g2d.drawImage(image, -IMAGE_WIDTH, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
// General Transform
bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
float delta = 0.05f;
float cos = 1 - delta * delta / 2;
float sin = 1 + delta;
AffineTransform transform = new AffineTransform(2 * cos, 0.1, 0.3, -2 * sin, 10, -5);
g2d.setTransform(transform);
g2d.drawImage(image, 0, -IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
int D = 10;
// From Source to small Destination region
bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.drawImage(image, IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2, IMAGE_WIDTH - D, IMAGE_HEIGHT - D,
D, D, IMAGE_WIDTH - D, IMAGE_HEIGHT - D, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
// From Source to large Destination region
bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) bufferedImage.getGraphics();
setImageScalingHint(g2d, enableImageScaling);
g2d.drawImage(image, D, D, 2 * IMAGE_WIDTH - D, 2 * IMAGE_HEIGHT - D,
IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2, IMAGE_WIDTH - D, IMAGE_HEIGHT - D, null);
checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
}
static class MultiResolutionBufferedImage extends BufferedImage
implements MultiResolutionImage {
Image highResolutionImage;
public MultiResolutionBufferedImage() {
super(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
highResolutionImage = new BufferedImage(
2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
draw(getGraphics(), 1);
draw(highResolutionImage.getGraphics(), 2);
}
void draw(Graphics graphics, float resolution) {
Graphics2D g2 = (Graphics2D) graphics;
g2.scale(resolution, resolution);
g2.setColor((resolution == 1) ? COLOR_1X : COLOR_2X);
g2.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
}
@Override
public Image getResolutionVariant(int width, int height) {
return ((width <= getWidth() && height <= getHeight()))
? this : highResolutionImage;
}
@Override
public List<Image> getResolutionVariants() {
return Arrays.asList(this, highResolutionImage);
}
}
static void testToolkitMultiResolutionImagePrepare() throws Exception {
generateImages();
File imageFile = new File(IMAGE_NAME_1X);
String fileName = imageFile.getAbsolutePath();
Image image = Toolkit.getDefaultToolkit().getImage(fileName);
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
toolkit.prepareImage(image, IMAGE_WIDTH, IMAGE_HEIGHT, new LoadImageObserver(image));
testToolkitMultiResolutionImageLoad(image);
}
static void testToolkitMultiResolutionImageLoad() throws Exception {
generateImages();
File imageFile = new File(IMAGE_NAME_1X);
String fileName = imageFile.getAbsolutePath();
Image image = Toolkit.getDefaultToolkit().getImage(fileName);
testToolkitMultiResolutionImageLoad(image);
}
static void testToolkitMultiResolutionImageLoad(Image image) throws Exception {
MediaTracker tracker = new MediaTracker(new JPanel());
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorAny()) {
throw new RuntimeException("Error during image loading");
}
tracker.removeImage(image, 0);
testImageLoaded(image);
int w = image.getWidth(null);
int h = image.getHeight(null);
Image resolutionVariant = ((MultiResolutionImage) image)
.getResolutionVariant(2 * w, 2 * h);
if (image == resolutionVariant) {
throw new RuntimeException("Resolution variant is not loaded");
}
testImageLoaded(resolutionVariant);
}
static void testImageLoaded(Image image) {
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
int flags = toolkit.checkImage(image, IMAGE_WIDTH, IMAGE_WIDTH, new SilentImageObserver());
if ((flags & (ImageObserver.FRAMEBITS | ImageObserver.ALLBITS)) == 0) {
throw new RuntimeException("Image is not loaded!");
}
}
static class SilentImageObserver implements ImageObserver {
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
throw new RuntimeException("Observer should not be called!");
}
}
static class LoadImageObserver implements ImageObserver {
Image image;
public LoadImageObserver(Image image) {
this.image = image;
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if (image != img) {
throw new RuntimeException("Original image is not passed to the observer");
}
if ((infoflags & ImageObserver.WIDTH) != 0) {
if (width != IMAGE_WIDTH) {
throw new RuntimeException("Original width is not passed to the observer");
}
}
if ((infoflags & ImageObserver.HEIGHT) != 0) {
if (height != IMAGE_HEIGHT) {
throw new RuntimeException("Original height is not passed to the observer");
}
}
return (infoflags & ALLBITS) == 0;
}
}
static void testToolkitMultiResolutionImage() throws Exception {
generateImages();
File imageFile = new File(IMAGE_NAME_1X);
String fileName = imageFile.getAbsolutePath();
URL url = imageFile.toURI().toURL();
testToolkitMultiResolutionImageChache(fileName, url);
Image image = Toolkit.getDefaultToolkit().getImage(fileName);
testToolkitImageObserver(image);
testToolkitMultiResolutionImage(image, false);
testToolkitMultiResolutionImage(image, true);
image = Toolkit.getDefaultToolkit().getImage(url);
testToolkitImageObserver(image);
testToolkitMultiResolutionImage(image, false);
testToolkitMultiResolutionImage(image, true);
}
static void testToolkitMultiResolutionImageChache(String fileName, URL url) {
Image img1 = Toolkit.getDefaultToolkit().getImage(fileName);
if (!(img1 instanceof MultiResolutionImage)) {
throw new RuntimeException("Not a MultiResolutionImage");
}
Image img2 = Toolkit.getDefaultToolkit().getImage(fileName);
if (img1 != img2) {
throw new RuntimeException("Image is not cached");
}
img1 = Toolkit.getDefaultToolkit().getImage(url);
if (!(img1 instanceof MultiResolutionImage)) {
throw new RuntimeException("Not a MultiResolutionImage");
}
img2 = Toolkit.getDefaultToolkit().getImage(url);
if (img1 != img2) {
throw new RuntimeException("Image is not cached");
}
}
static void testToolkitMultiResolutionImage(Image image, boolean enableImageScaling)
throws Exception {
MediaTracker tracker = new MediaTracker(new JPanel());
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorAny()) {
throw new RuntimeException("Error during image loading");
}
final BufferedImage bufferedImage1x = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics2D g1x = (Graphics2D) bufferedImage1x.getGraphics();
setImageScalingHint(g1x, false);
g1x.drawImage(image, 0, 0, null);
checkColor(bufferedImage1x.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
Image resolutionVariant = ((MultiResolutionImage) image).
getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);
if (resolutionVariant == null) {
throw new RuntimeException("Resolution variant is null");
}
MediaTracker tracker2x = new MediaTracker(new JPanel());
tracker2x.addImage(resolutionVariant, 0);
tracker2x.waitForID(0);
if (tracker2x.isErrorAny()) {
throw new RuntimeException("Error during scalable image loading");
}
final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
setImageScalingHint(g2x, enableImageScaling);
g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
checkColor(bufferedImage2x.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
if (!(image instanceof MultiResolutionImage)) {
throw new RuntimeException("Not a MultiResolutionImage");
}
MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;
Image image1x = multiResolutionImage.getResolutionVariant(IMAGE_WIDTH, IMAGE_HEIGHT);
Image image2x = multiResolutionImage.getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);
if (image1x.getWidth(null) * 2 != image2x.getWidth(null)
|| image1x.getHeight(null) * 2 != image2x.getHeight(null)) {
throw new RuntimeException("Wrong resolution variant size");
}
}
static void testToolkitImageObserver(final Image image) {
ImageObserver observer = new ImageObserver() {
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if (img != image) {
throw new RuntimeException("Wrong image in observer");
}
if ((infoflags & (ImageObserver.ERROR | ImageObserver.ABORT)) != 0) {
throw new RuntimeException("Error during image loading");
}
return (infoflags & ImageObserver.ALLBITS) == 0;
}
};
final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
setImageScalingHint(g2x, true);
g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, observer);
}
static void setImageScalingHint(Graphics2D g2d, boolean enableImageScaling) {
g2d.setRenderingHint(SunHints.KEY_RESOLUTION_VARIANT, enableImageScaling
? SunHints.VALUE_RESOLUTION_VARIANT_ON
: SunHints.VALUE_RESOLUTION_VARIANT_OFF);
}
static void checkColor(int rgb, boolean isImageScaled) {
if (!isImageScaled && COLOR_1X.getRGB() != rgb) {
throw new RuntimeException("Wrong 1x color: " + new Color(rgb));
}
if (isImageScaled && COLOR_2X.getRGB() != rgb) {
throw new RuntimeException("Wrong 2x color" + new Color(rgb));
}
}
static void generateImages() throws Exception {
if (!new File(IMAGE_NAME_1X).exists()) {
generateImage(1);
}
if (!new File(IMAGE_NAME_2X).exists()) {
generateImage(2);
}
}
static void generateImage(int scale) throws Exception {
BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(scale == 1 ? COLOR_1X : COLOR_2X);
g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT);
File file = new File(scale == 1 ? IMAGE_NAME_1X : IMAGE_NAME_2X);
ImageIO.write(image, "png", file);
}
static void testImageNameTo2xParsing() throws Exception {
for (String[] testNames : TEST_FILE_NAMES) {
String testName = testNames[0];
String goldenName = testNames[1];
String resultName = getTestScaledImageName(testName);
if (!isValidPath(testName) && resultName == null) {
continue;
}
if (goldenName.equals(resultName)) {
continue;
}
throw new RuntimeException("Test name " + testName
+ ", result name: " + resultName);
}
for (URL[] testURLs : TEST_URLS) {
URL testURL = testURLs[0];
URL goldenURL = testURLs[1];
URL resultURL = getTestScaledImageURL(testURL);
if (!isValidPath(testURL.getPath()) && resultURL == null) {
continue;
}
if (goldenURL.equals(resultURL)) {
continue;
}
throw new RuntimeException("Test url: " + testURL
+ ", result url: " + resultURL);
}
}
static URL getTestScaledImageURL(URL url) throws Exception {
Method method = getScalableImageMethod("getScaledImageURL", URL.class);
return (URL) method.invoke(null, url);
}
static String getTestScaledImageName(String name) throws Exception {
Method method = getScalableImageMethod("getScaledImageName", String.class);
return (String) method.invoke(null, name);
}
private static boolean isValidPath(String path) {
return !path.isEmpty() && !path.endsWith("/") && !path.endsWith(".")
&& !path.contains("@2x");
}
private static Method getScalableImageMethod(String name,
Class... parameterTypes) throws Exception {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Method method = toolkit.getClass().getDeclaredMethod(name, parameterTypes);
method.setAccessible(true);
return method;
}
private static final String[][] TEST_FILE_NAMES;
private static final URL[][] TEST_URLS;
static {
TEST_FILE_NAMES = new String[][]{
{"", null},
{".", null},
{"..", null},
{"/", null},
{"/.", null},
{"dir/", null},
{"dir/.", null},
{"aaa@2x.png", null},
{"/dir/aaa@2x.png", null},
{"image", "image@2x"},
{"image.ext", "image@2x.ext"},
{"image.aaa.ext", "image.aaa@2x.ext"},
{"dir/image", "dir/image@2x"},
{"dir/image.ext", "dir/image@2x.ext"},
{"dir/image.aaa.ext", "dir/image.aaa@2x.ext"},
{"dir/aaa.bbb/image", "dir/aaa.bbb/image@2x"},
{"dir/aaa.bbb/image.ext", "dir/aaa.bbb/image@2x.ext"},
{"dir/aaa.bbb/image.ccc.ext", "dir/aaa.bbb/image.ccc@2x.ext"},
{"/dir/image", "/dir/image@2x"},
{"/dir/image.ext", "/dir/image@2x.ext"},
{"/dir/image.aaa.ext", "/dir/image.aaa@2x.ext"},
{"/dir/aaa.bbb/image", "/dir/aaa.bbb/image@2x"},
{"/dir/aaa.bbb/image.ext", "/dir/aaa.bbb/image@2x.ext"},
{"/dir/aaa.bbb/image.ccc.ext", "/dir/aaa.bbb/image.ccc@2x.ext"}
};
try {
TEST_URLS = new URL[][]{
// file
{new URL("file:/aaa"), new URL("file:/aaa@2x")},
{new URL("file:/aaa.ext"), new URL("file:/aaa@2x.ext")},
{new URL("file:/aaa.bbb.ext"), new URL("file:/aaa.bbb@2x.ext")},
{new URL("file:/ccc/aaa.bbb.ext"),
new URL("file:/ccc/aaa.bbb@2x.ext")},
{new URL("file:/ccc.ddd/aaa.bbb.ext"),
new URL("file:/ccc.ddd/aaa.bbb@2x.ext")},
{new URL("file:///~/image"), new URL("file:///~/image@2x")},
{new URL("file:///~/image.ext"),
new URL("file:///~/image@2x.ext")},
// http
{new URL("http://www.test.com"), null},
{new URL("http://www.test.com/"), null},
{new URL("http://www.test.com///"), null},
{new URL("http://www.test.com/image"),
new URL("http://www.test.com/image@2x")},
{new URL("http://www.test.com/image.ext"),
new URL("http://www.test.com/image@2x.ext")},
{new URL("http://www.test.com/dir/image"),
new URL("http://www.test.com/dir/image@2x")},
{new URL("http://www.test.com:80/dir/image.aaa.ext"),
new URL("http://www.test.com:80/dir/image.aaa@2x.ext")},
{new URL("http://www.test.com:8080/dir/image.aaa.ext"),
new URL("http://www.test.com:8080/dir/image.aaa@2x.ext")},
// jar
{new URL("jar:file:/dir/Java2D.jar!/image"),
new URL("jar:file:/dir/Java2D.jar!/image@2x")},
{new URL("jar:file:/dir/Java2D.jar!/image.aaa.ext"),
new URL("jar:file:/dir/Java2D.jar!/image.aaa@2x.ext")},
{new URL("jar:file:/dir/Java2D.jar!/images/image"),
new URL("jar:file:/dir/Java2D.jar!/images/image@2x")},
{new URL("jar:file:/dir/Java2D.jar!/images/image.ext"),
new URL("jar:file:/dir/Java2D.jar!/images/image@2x.ext")},
{new URL("jar:file:/aaa.bbb/Java2D.jar!/images/image.ext"),
new URL("jar:file:/aaa.bbb/Java2D.jar!/images/image@2x.ext")},
{new URL("jar:file:/dir/Java2D.jar!/aaa.bbb/image.ext"),
new URL("jar:file:/dir/Java2D.jar!/aaa.bbb/image@2x.ext")},};
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static class PreloadedImageObserver implements ImageObserver {
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
throw new RuntimeException("Image should be already preloaded");
}
}
}
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 2014, 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
......@@ -51,6 +51,7 @@ import java.awt.Toolkit;
import java.awt.IllegalComponentStateException;
import java.awt.AWTException;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
......@@ -184,6 +185,57 @@ public final class Util {
}
}
/**
* Tests whether screen pixel has the expected color performing several
* attempts. This method is useful for asynchronous window manager where
* it's impossible to determine when drawing actually takes place.
*
* @param x X position of pixel
* @param y Y position of pixel
* @param color expected color
* @param attempts number of attempts to undertake
* @param delay delay before each attempt
* @param robot a robot to use for retrieving pixel color
* @return true if pixel color matches the color expected, otherwise false
*/
public static boolean testPixelColor(int x, int y, final Color color, int attempts, int delay, final Robot robot) {
while (attempts-- > 0) {
robot.delay(delay);
Color screen = robot.getPixelColor(x, y);
if (screen.equals(color)) {
return true;
}
}
return false;
}
/**
* Tests whether the area within boundaries has the expected color
* performing several attempts. This method is useful for asynchronous
* window manager where it's impossible to determine when drawing actually
* takes place.
*
* @param bounds position of area
* @param color expected color
* @param attempts number of attempts to undertake
* @param delay delay before each attempt
* @param robot a robot to use for retrieving pixel color
* @return true if area color matches the color expected, otherwise false
*/
public static boolean testBoundsColor(final Rectangle bounds, final Color color, int attempts, int delay, final Robot robot) {
int right = bounds.x + bounds.width - 1;
int bottom = bounds.y + bounds.height - 1;
while (attempts-- > 0) {
if (testPixelColor(bounds.x, bounds.y, color, 1, delay, robot)
&& testPixelColor(right, bounds.y, color, 1, 0, robot)
&& testPixelColor(right, bottom, color, 1, 0, robot)
&& testPixelColor(bounds.x, bottom, color, 1, 0, robot)) {
return true;
}
}
return false;
}
public static void waitForIdle(final Robot robot) {
// we do not use robot for now, use SunToolkit.realSync() instead
((sun.awt.SunToolkit)Toolkit.getDefaultToolkit()).realSync();
......
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, 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
......@@ -27,18 +27,19 @@
* @summary Basic unit test of ThreadInfo.getLockName()
* and ThreadInfo.getLockOwnerName()
* @author Mandy Chung
* @author Jaroslav Bachorik
*
* @build ThreadExecutionSynchronizer
* @run main/othervm Locks
*/
import java.lang.management.*;
import java.util.concurrent.Phaser;
public class Locks {
private static Object objA = new Object();
private static Object objB = new Object();
private static Object objC = new Object();
private static ThreadMXBean tm = ManagementFactory.getThreadMXBean();
private static final Object objA = new Object();
private static final Object objB = new Object();
private static final Object objC = new Object();
private static final ThreadMXBean tm = ManagementFactory.getThreadMXBean();
private static boolean testFailed = false;
......@@ -49,15 +50,27 @@ public class Locks {
Integer.toHexString(System.identityHashCode(lock));
}
private static void assertNoLock(Thread t) {
long tid = t.getId();
ThreadInfo info = tm.getThreadInfo(tid);
String result = info.getLockName();
if (result != null) {
throw new RuntimeException("Thread " + t.getName() + " is not supposed to hold any lock. " +
"Currently owning lock: " + result);
}
}
private static void checkBlockedObject(Thread t, Object lock, Thread owner,
Thread.State expectedState) {
ThreadInfo info = tm.getThreadInfo(t.getId());
long tid = t.getId();
ThreadInfo info = tm.getThreadInfo(tid);
String result = info.getLockName();
String expectedLock = (lock != null ? getLockName(lock) : null);
String expectedOwner = (owner != null ? owner.getName() : null);
if (lock != null) {
if (expectedState ==Thread.State.BLOCKED) {
if (expectedState == Thread.State.BLOCKED) {
int retryCount=0;
while(info.getThreadState() != Thread.State.BLOCKED) {
if (retryCount++ > 500) {
......@@ -67,6 +80,8 @@ public class Locks {
" Thread.State = " + info.getThreadState());
}
goSleep(100);
info = tm.getThreadInfo(tid);
result = info.getLockName();
}
}
if (expectedState == Thread.State.WAITING &&
......@@ -100,53 +115,49 @@ public class Locks {
}
}
static ThreadExecutionSynchronizer thrsync = new ThreadExecutionSynchronizer();
static ThreadExecutionSynchronizer thrsync1 = new ThreadExecutionSynchronizer();
private static volatile int dummyCounter = 0;
static class LockAThread extends Thread {
public LockAThread() {
private final Phaser p;
public LockAThread(Phaser p) {
super("LockAThread");
this.p = p;
}
public void run() {
synchronized(objA) {
// stop here for LockBThread to hold objB
thrsync.waitForSignal();
System.out.println("LockAThread about to block on objB");
synchronized(objB) {};
p.arriveAndAwaitAdvance(); // Phase 1 (blocking)
synchronized(objB) {
dummyCounter++;
};
}
p.arriveAndAwaitAdvance(); // Phase 2 (blocking)
System.out.println("LockAThread about to exit");
// The state could be anything. The expected state value
// passed with this method is not verified.
checkBlockedObject(this, null, null, Thread.State.TERMINATED);
// Make sure the current thread is not holding any lock
assertNoLock(this);
}
}
static class LockBThread extends Thread {
public LockBThread() {
private final Phaser p;
public LockBThread(Phaser p) {
super("LockBThread");
this.p = p;
}
public void run() {
synchronized(objB) {
// signal waiting LockAThread.
thrsync.signal();
System.out.println("LockBThread about to block on objC");
p.arriveAndAwaitAdvance(); // Phase 1 (blocking)
// Signal main thread about to block on objC
thrsync1.signal();
synchronized(objC) {};
synchronized(objC) {
dummyCounter++;
};
}
p.arriveAndAwaitAdvance(); // Phase 2 (blocking)
System.out.println("LockBThread about to exit");
// The state could be anything. The expected state value
// passed with this method is not verified.
checkBlockedObject(this, null, null, Thread.State.TERMINATED);
}
public void aboutToLockC() {
// Stop here till LockBThread about to blocked
// for lock objC.
thrsync1.waitForSignal();
goSleep(500);
// Make sure the current thread is not holding any lock
assertNoLock(this);
}
}
......@@ -154,15 +165,17 @@ public class Locks {
private static Object ready = new Object();
private static CheckerThread checker;
static class WaitingThread extends Thread {
public WaitingThread() {
private final Phaser p;
public WaitingThread(Phaser p) {
super("WaitingThread");
this.p = p;
}
public void run() {
synchronized(objC) {
System.out.println("WaitingThread about to wait on objC");
try {
// Signal checker thread, about to wait on objC.
thrsync.signal();
p.arriveAndAwaitAdvance(); // Phase 1 (waiting)
objC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
......@@ -173,13 +186,15 @@ public class Locks {
System.out.println("WaitingThread about to block on ready");
// signal checker thread that it is about acquire
// object ready.
thrsync.signal();
synchronized(ready) {};
p.arriveAndAwaitAdvance(); // Phase 2 (waiting)
synchronized(ready) {
dummyCounter++;
};
}
synchronized(objC) {
try {
// signal checker thread, about to wait on objC
thrsync.signal();
p.arriveAndAwaitAdvance(); // Phase 3 (waiting)
objC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
......@@ -190,13 +205,15 @@ public class Locks {
}
}
static class CheckerThread extends Thread {
public CheckerThread() {
private final Phaser p;
public CheckerThread(Phaser p) {
super("CheckerThread");
this.p = p;
}
private void waitForState(Thread.State state) {
thrsync.waitForSignal();
while (waiter.getState() != state) {
p.arriveAndAwaitAdvance();
while (!waiter.isInterrupted() && waiter.getState() != state) {
goSleep(10);
}
}
......@@ -204,7 +221,7 @@ public class Locks {
public void run() {
synchronized (ready) {
// wait until WaitingThread about to wait for objC
waitForState(Thread.State.WAITING);
waitForState(Thread.State.WAITING); // Phase 1 (waiting)
checkBlockedObject(waiter, objC, null, Thread.State.WAITING);
synchronized (objC) {
......@@ -213,13 +230,13 @@ public class Locks {
// wait for waiter thread to about to enter
// synchronized object ready.
waitForState(Thread.State.BLOCKED);
waitForState(Thread.State.BLOCKED); // Phase 2 (waiting)
checkBlockedObject(waiter, ready, this, Thread.State.BLOCKED);
}
// wait for signal from waiting thread that it is about
// wait for objC.
waitForState(Thread.State.WAITING);
waitForState(Thread.State.WAITING); // Phase 3 (waiting)
synchronized(objC) {
checkBlockedObject(waiter, objC, Thread.currentThread(), Thread.State.WAITING);
objC.notify();
......@@ -235,24 +252,24 @@ public class Locks {
LockAThread t1;
LockBThread t2;
Phaser p = new Phaser(3);
synchronized(objC) {
// The state could be anything. The expected state value
// passed with this method is not verified.
checkBlockedObject(mainThread, null, null, Thread.State.RUNNABLE);
// Make sure the main thread is not holding any lock
assertNoLock(mainThread);
// Test deadlock case
// t1 holds lockA and attempts to lock B
// t2 holds lockB and attempts to lock C
t1 = new LockAThread();
t1 = new LockAThread(p);
t1.start();
t2 = new LockBThread();
t2 = new LockBThread(p);
t2.start();
t2.aboutToLockC();
checkBlockedObject(t1, objB, t2, Thread.State.BLOCKED);
p.arriveAndAwaitAdvance(); // Phase 1 (blocking)
checkBlockedObject(t2, objC, mainThread, Thread.State.BLOCKED);
checkBlockedObject(t1, objB, t2, Thread.State.BLOCKED);
long[] expectedThreads = new long[3];
expectedThreads[0] = t1.getId(); // blocked on lockB
......@@ -260,13 +277,14 @@ public class Locks {
expectedThreads[2] = mainThread.getId(); // owner of lockC
findThreadsBlockedOn(objB, expectedThreads);
}
goSleep(100);
p.arriveAndAwaitAdvance(); // Phase 2 (blocking)
p = new Phaser(2);
// Test Object.wait() case
waiter = new WaitingThread();
waiter = new WaitingThread(p);
waiter.start();
checker = new CheckerThread();
checker = new CheckerThread(p);
checker.start();
try {
......
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, 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
......@@ -27,45 +27,28 @@
* @summary Basic unit test of the synchronization statistics support:
*
* @author Mandy Chung
* @author Jaroslav Bachorik
*
* @ignore 6309226
* @build Semaphore
* @run main/othervm SynchronizationStatistics
*/
import java.lang.management.*;
import java.util.concurrent.Phaser;
public class SynchronizationStatistics {
private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
private static class LockerThread extends Thread {
public LockerThread(Runnable r) {
super(r, "LockerThread");
}
}
private static boolean blockedTimeCheck =
mbean.isThreadContentionMonitoringSupported();
private static boolean trace = false;
private static final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
private static Object lockA = new Object();
private static Object lockB = new Object();
private static Object lockC = new Object();
private static Object lockD = new Object();
private static Object waiter = new Object();
private static volatile boolean testFailed = false;
private static final boolean blockedTimeCheck =
mbean.isThreadContentionMonitoringSupported();
private static Object go = new Object();
private static void goSleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Unexpected exception.");
testFailed = true;
}
}
public static void main(String args[]) throws Exception {
if (args.length > 0 && args[0].equals("trace")) {
trace = true;
}
if (blockedTimeCheck) {
mbean.setThreadContentionMonitoringEnabled(true);
}
......@@ -75,457 +58,317 @@ public class SynchronizationStatistics {
"Thread Contention Monitoring is not enabled");
}
Examiner examiner = new Examiner("Examiner");
BlockedThread blocked = new BlockedThread("BlockedThread");
examiner.setThread(blocked);
// Start the threads and check them in Blocked and Waiting states
examiner.start();
// wait until the examiner acquires all the locks and waiting
// for the BlockedThread to start
examiner.waitUntilWaiting();
System.out.println("Checking the thread state for the examiner thread " +
"is waiting to begin.");
// The Examiner should be waiting to be notified by the BlockedThread
checkThreadState(examiner, Thread.State.WAITING);
System.out.println("Now starting the blocked thread");
blocked.start();
try {
examiner.join();
blocked.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Unexpected exception.");
testFailed = true;
}
if (testFailed)
throw new RuntimeException("TEST FAILED.");
testBlockingOnSimpleMonitor();
testBlockingOnNestedMonitor();
testWaitingOnSimpleMonitor();
testMultiWaitingOnSimpleMonitor();
testWaitingOnNestedMonitor();
System.out.println("Test passed.");
}
private static String INDENT = " ";
private static void printStack(Thread t, StackTraceElement[] stack) {
System.out.println(INDENT + t +
" stack: (length = " + stack.length + ")");
if (t != null) {
for (int j = 0; j < stack.length; j++) {
System.out.println(INDENT + stack[j]);
}
System.out.println();
private static LockerThread newLockerThread(Runnable r) {
LockerThread t = new LockerThread(r);
t.setDaemon(true);
return t;
}
}
private static void checkThreadState(Thread thread, Thread.State s)
throws Exception {
ThreadInfo ti = mbean.getThreadInfo(thread.getId());
if (ti.getThreadState() != s) {
ThreadInfo info = mbean.getThreadInfo(thread.getId(),
Integer.MAX_VALUE);
System.out.println(INDENT + "TEST FAILED:");
printStack(thread, info.getStackTrace());
System.out.println(INDENT + "Thread state: " + info.getThreadState());
throw new RuntimeException("TEST FAILED: " +
"Thread state for " + thread + " returns " + ti.getThreadState() +
". Expected to be " + s);
private static void waitForThreadState(Thread t, Thread.State state) throws InterruptedException {
while (!t.isInterrupted() && t.getState() != state) {
Thread.sleep(3);
}
}
private static void checkThreadState(Thread thread,
Thread.State s1, Thread.State s2)
throws Exception {
ThreadInfo ti = mbean.getThreadInfo(thread.getId());
if (ti.getThreadState() != s1 && ti.getThreadState() != s2) {
throw new RuntimeException("TEST FAILED: " +
"Thread state for " + thread + " returns " + ti.getThreadState() +
". Expected to be " + s1 + " or " + s2);
/**
* Tests that blocking on a single monitor properly increases the
* blocked count at least by 1. Also asserts that the correct lock name is provided.
*/
private static void testBlockingOnSimpleMonitor() throws Exception {
System.out.println("testBlockingOnSimpleMonitor");
final Object lock1 = new Object();
final Phaser p = new Phaser(2);
LockerThread lt = newLockerThread(new Runnable() {
@Override
public void run() {
p.arriveAndAwaitAdvance(); // phase[1]
synchronized(lock1) {
System.out.println("[LockerThread obtained Lock1]");
p.arriveAndAwaitAdvance(); // phase[2]
}
p.arriveAndAwaitAdvance(); // phase[3]
}
});
static class StatThread extends Thread {
private long blockingBaseTime = 0;
private long totalWaitTime = 0;
private long totalBlockedEnterTime = 0;
StatThread(String name) {
super(name);
lt.start();
long tid = lt.getId();
ThreadInfo ti = mbean.getThreadInfo(tid);
String lockName = null;
synchronized(lock1) {
p.arriveAndAwaitAdvance(); // phase[1]
waitForThreadState(lt, Thread.State.BLOCKED);
lockName = mbean.getThreadInfo(tid).getLockName();
}
void addWaitTime(long ns) {
totalWaitTime = totalWaitTime + ns;
}
void addBlockedEnterTime(long ns) {
totalBlockedEnterTime = totalBlockedEnterTime + ns;
}
void setBlockingBaseTime(long time) {
blockingBaseTime = time;
}
p.arriveAndAwaitAdvance(); // phase[2]
testBlocked(ti, mbean.getThreadInfo(tid), lockName, lock1);
p.arriveAndDeregister(); // phase[3]
long totalBlockedTimeMs() {
return totalBlockedEnterTime / 1000000;
}
lt.join();
long totalBlockedTimeMs(long now) {
long t = totalBlockedEnterTime + (now - blockingBaseTime);
return t / 1000000;
System.out.println("OK");
}
long totalWaitTimeMs() {
return totalWaitTime / 1000000;
/**
* Tests that blocking on a nested monitor properly increases the
* blocked count at least by 1 - it is not affected by the nesting depth.
* Also asserts that the correct lock name is provided.
*/
private static void testBlockingOnNestedMonitor() throws Exception {
System.out.println("testBlockingOnNestedMonitor");
final Object lock1 = new Object();
final Object lock2 = new Object();
final Phaser p = new Phaser(2);
LockerThread lt = newLockerThread(new Runnable() {
@Override
public void run() {
p.arriveAndAwaitAdvance(); // phase[1]
synchronized(lock1) {
System.out.println("[LockerThread obtained Lock1]");
p.arriveAndAwaitAdvance(); // phase[2]
p.arriveAndAwaitAdvance(); // phase[3]
synchronized(lock2) {
System.out.println("[LockerThread obtained Lock2]");
p.arriveAndAwaitAdvance(); // phase[4]
}
long totalWaitTimeMs(long now) {
long t = totalWaitTime + (now - blockingBaseTime);
return t / 1000000;
p.arriveAndAwaitAdvance(); // phase[5]
}
}
});
static class BlockedThread extends StatThread {
private Semaphore handshake = new Semaphore();
BlockedThread(String name) {
super(name);
lt.start();
long tid = lt.getId();
ThreadInfo ti = mbean.getThreadInfo(tid);
ThreadInfo ti1 = null;
String lockName = null;
synchronized(lock1) {
p.arriveAndAwaitAdvance(); // phase[1]
waitForThreadState(lt, Thread.State.BLOCKED);
lockName = mbean.getThreadInfo(tid).getLockName();
}
void waitUntilBlocked() {
handshake.semaP();
p.arriveAndAwaitAdvance(); // phase[2]
// give a chance for the examiner thread to really wait
goSleep(20);
}
ti1 = mbean.getThreadInfo(tid);
testBlocked(ti, ti1, lockName, lock1);
ti = ti1;
void waitUntilWaiting() {
waitUntilBlocked();
synchronized(lock2) {
p.arriveAndAwaitAdvance(); // phase [3]
waitForThreadState(lt, Thread.State.BLOCKED);
lockName = mbean.getThreadInfo(tid).getLockName();
}
p.arriveAndAwaitAdvance(); // phase [4]
testBlocked(ti, mbean.getThreadInfo(tid), lockName, lock2);
p.arriveAndDeregister();
boolean hasWaitersForBlocked() {
return (handshake.getWaiterCount() > 0);
}
lt.join();
private void notifyWaiter() {
// wait until the examiner waits on the semaphore
while (handshake.getWaiterCount() == 0) {
goSleep(20);
}
handshake.semaV();
System.out.println("OK");
}
private void waitObj(long ms) {
synchronized (waiter) {
/**
* Tests that waiting on a single monitor properly increases the waited
* count by 1 and the waited time by a positive number.
*/
private static void testWaitingOnSimpleMonitor() throws Exception {
System.out.println("testWaitingOnSimpleMonitor");
final Object lock1 = new Object();
final Phaser p = new Phaser(2);
LockerThread lt = newLockerThread(new Runnable() {
@Override
public void run() {
p.arriveAndAwaitAdvance(); // phase[1]
synchronized(lock1) {
System.out.println("[LockerThread obtained Lock1]");
try {
// notify examinerabout to wait on a monitor
notifyWaiter();
long base = System.nanoTime();
setBlockingBaseTime(base);
waiter.wait(ms);
long now = System.nanoTime();
addWaitTime(now - base);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Unexpected exception.");
testFailed = true;
lock1.wait(300);
} catch (InterruptedException ex) {
// ignore
}
p.arriveAndAwaitAdvance(); // phase[2]
}
p.arriveAndAwaitAdvance(); // phase[3]
}
});
private void test() {
// notify examiner about to block on lockA
notifyWaiter();
long base = System.nanoTime();
setBlockingBaseTime(base);
synchronized (lockA) {
long now = System.nanoTime();
addBlockedEnterTime(now - base);
A(); // Expected blocked count = 1
}
E();
lt.start();
ThreadInfo ti1 = mbean.getThreadInfo(lt.getId());
synchronized(lock1) {
p.arriveAndAwaitAdvance(); // phase[1]
waitForThreadState(lt, Thread.State.BLOCKED);
}
private void A() {
// notify examiner about to block on lockB
notifyWaiter();
p.arriveAndAwaitAdvance(); // phase[2]
long base = System.nanoTime();
setBlockingBaseTime(base);
synchronized (lockB) {
long now = System.nanoTime();
addBlockedEnterTime(now - base);
ThreadInfo ti2 = mbean.getThreadInfo(lt.getId());
p.arriveAndDeregister(); // phase[3]
B(); // Expected blocked count = 2
}
}
private void B() {
// notify examiner about to block on lockC
notifyWaiter();
long base = System.nanoTime();
setBlockingBaseTime(base);
synchronized (lockC) {
long now = System.nanoTime();
addBlockedEnterTime(now - base);
lt.join();
C(); // Expected blocked count = 3
testWaited(ti1, ti2, 1);
System.out.println("OK");
}
}
private void C() {
// notify examiner about to block on lockD
notifyWaiter();
long base = System.nanoTime();
setBlockingBaseTime(base);
synchronized (lockD) {
long now = System.nanoTime();
addBlockedEnterTime(now - base);
D(); // Expected blocked count = 4
}
}
private void D() {
goSleep(50);
}
private void E() {
final int WAIT = 1000;
waitObj(WAIT);
waitObj(WAIT);
waitObj(WAIT);
}
/**
* Tests that waiting multiple times on the same monitor subsequently
* increases the waited count by the number of subsequent calls and the
* waited time by a positive number.
*/
private static void testMultiWaitingOnSimpleMonitor() throws Exception {
System.out.println("testWaitingOnMultipleMonitors");
final Object lock1 = new Object();
final Phaser p = new Phaser(2);
LockerThread lt = newLockerThread(new Runnable() {
@Override
public void run() {
test();
} // run()
} // BlockedThread
static int blockedCount = 0;
static int waitedCount = 0;
static class Examiner extends StatThread {
private BlockedThread blockedThread;
private Semaphore semaphore = new Semaphore();
Examiner(String name) {
super(name);
p.arriveAndAwaitAdvance(); // phase[1]
synchronized(lock1) {
System.out.println("[LockerThread obtained Lock1]");
for (int i = 0; i < 3; i++) {
try {
lock1.wait(300);
} catch (InterruptedException ex) {
// ignore
}
public void setThread(BlockedThread thread) {
blockedThread = thread;
p.arriveAndAwaitAdvance(); // phase[2-4]
}
private void blockedTimeRangeCheck(StatThread t,
long blockedTime,
long nowNano)
throws Exception {
long expected = t.totalBlockedTimeMs(nowNano);
// accept 5% range
timeRangeCheck(blockedTime, expected, 5);
}
private void waitedTimeRangeCheck(StatThread t,
long waitedTime,
long nowNano)
throws Exception {
long expected = t.totalWaitTimeMs(nowNano);
// accept 5% range
timeRangeCheck(waitedTime, expected, 5);
p.arriveAndAwaitAdvance(); // phase[5]
}
});
private void timeRangeCheck(long time, long expected, int percent)
throws Exception {
double diff = expected - time;
if (trace) {
System.out.println(" Time = " + time +
" expected = " + expected +
". Diff = " + diff);
}
// throw an exception if blockedTime and expectedTime
// differs > percent%
if (diff < 0) {
diff = diff * -1;
lt.start();
ThreadInfo ti1 = mbean.getThreadInfo(lt.getId());
synchronized(lock1) {
p.arriveAndAwaitAdvance(); //phase[1]
waitForThreadState(lt, Thread.State.BLOCKED);
}
int phase = p.getPhase();
while ((p.arriveAndAwaitAdvance() - phase) < 3); // phase[2-4]
long range = (expected * percent) / 100;
// minimum range = 2 ms
if (range < 2) {
range = 2;
}
if (diff > range) {
throw new RuntimeException("TEST FAILED: " +
"Time returned = " + time +
" expected = " + expected + ". Diff = " + diff);
}
}
private void checkInfo(StatThread t, Thread.State s, Object lock,
String lockName, int bcount, int wcount)
throws Exception {
ThreadInfo ti2 = mbean.getThreadInfo(lt.getId());
p.arriveAndDeregister(); // phase[5]
String action = "ERROR";
if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) {
action = "wait on ";
} else if (s == Thread.State.BLOCKED) {
action = "block on ";
lt.join();
testWaited(ti1, ti2, 3);
System.out.println("OK");
}
System.out.println(t + " expected to " + action + lockName +
" with blocked count = " + bcount +
" and waited count = " + wcount);
long now = System.nanoTime();
ThreadInfo info = mbean.getThreadInfo(t.getId());
if (info.getThreadState() != s) {
printStack(t, info.getStackTrace());
throw new RuntimeException("TEST FAILED: " +
"Thread state returned is " + info.getThreadState() +
". Expected to be " + s);
/**
* Tests that waiting on monitors places in nested synchronized blocks
* properly increases the waited count by the number of times the "lock.wait()"
* was invoked and the waited time by a positive number.
*/
private static void testWaitingOnNestedMonitor() throws Exception {
System.out.println("testWaitingOnNestedMonitor");
final Object lock1 = new Object();
final Object lock2 = new Object();
final Object lock3 = new Object();
final Phaser p = new Phaser(2);
LockerThread lt = newLockerThread(new Runnable() {
@Override
public void run() {
p.arriveAndAwaitAdvance(); // phase[1]
synchronized(lock1) {
System.out.println("[LockerThread obtained Lock1]");
try {
lock1.wait(300);
} catch (InterruptedException ex) {
// ignore
}
if (info.getLockName() == null ||
!info.getLockName().equals(lock.toString())) {
throw new RuntimeException("TEST FAILED: " +
"getLockName() returned " + info.getLockName() +
". Expected to be " + lockName + " - " + lock.toString());
p.arriveAndAwaitAdvance(); // phase[2]
synchronized(lock2) {
System.out.println("[LockerThread obtained Lock2]");
try {
lock2.wait(300);
} catch (InterruptedException ex) {
// ignore
}
if (info.getBlockedCount() != bcount) {
throw new RuntimeException("TEST FAILED: " +
"Blocked Count returned is " + info.getBlockedCount() +
". Expected to be " + bcount);
p.arriveAndAwaitAdvance(); // phase[3]
synchronized(lock3) {
System.out.println("[LockerThread obtained Lock3]");
try {
lock3.wait(300);
} catch (InterruptedException ex) {
// ignore
}
if (info.getWaitedCount() != wcount) {
throw new RuntimeException("TEST FAILED: " +
"Waited Count returned is " + info.getWaitedCount() +
". Expected to be " + wcount);
p.arriveAndAwaitAdvance(); // phase[4]
}
String lockObj = info.getLockName();
if (lockObj == null || !lockObj.equals(lock.toString())) {
throw new RuntimeException("TEST FAILED: " +
"Object blocked on is " + lockObj +
". Expected to be " + lock.toString());
}
if (!blockedTimeCheck) {
return;
}
long blockedTime = info.getBlockedTime();
if (blockedTime < 0) {
throw new RuntimeException("TEST FAILED: " +
"Blocked time returned is negative = " + blockedTime);
p.arriveAndAwaitAdvance(); // phase[5]
}
});
if (s == Thread.State.BLOCKED) {
blockedTimeRangeCheck(t, blockedTime, now);
} else {
timeRangeCheck(blockedTime, t.totalBlockedTimeMs(), 5);
lt.start();
ThreadInfo ti1 = mbean.getThreadInfo(lt.getId());
synchronized(lock1) {
p.arriveAndAwaitAdvance(); // phase[1]
waitForThreadState(lt, Thread.State.BLOCKED);
}
long waitedTime = info.getWaitedTime();
if (waitedTime < 0) {
throw new RuntimeException("TEST FAILED: " +
"Waited time returned is negative = " + waitedTime);
}
if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) {
waitedTimeRangeCheck(t, waitedTime, now);
} else {
timeRangeCheck(waitedTime, t.totalWaitTimeMs(), 5);
synchronized(lock2) {
p.arriveAndAwaitAdvance(); // phase[2]
waitForThreadState(lt, Thread.State.BLOCKED);
}
synchronized(lock3) {
p.arriveAndAwaitAdvance(); // phase[3]
waitForThreadState(lt, Thread.State.BLOCKED);
}
private void examine() {
try {
synchronized (lockD) {
synchronized (lockC) {
synchronized (lockB) {
synchronized (lockA) {
// notify main thread to continue
semaphore.semaV();
// wait until BlockedThread has started
blockedThread.waitUntilBlocked();
p.arriveAndAwaitAdvance(); // phase[4]
ThreadInfo ti2 = mbean.getThreadInfo(lt.getId());
p.arriveAndDeregister(); // phase[5]
blockedCount++;
checkInfo(blockedThread, Thread.State.BLOCKED,
lockA, "lockA",
blockedCount, waitedCount);
lt.join();
testWaited(ti1, ti2, 3);
System.out.println("OK");
}
// wait until BlockedThread to block on lockB
blockedThread.waitUntilBlocked();
blockedCount++;
checkInfo(blockedThread, Thread.State.BLOCKED,
lockB, "lockB",
blockedCount, waitedCount);
private static void testWaited(ThreadInfo ti1, ThreadInfo ti2, int waited) throws Error {
long waitCntDiff = ti2.getWaitedCount() - ti1.getWaitedCount();
long waitTimeDiff = ti2.getWaitedTime() - ti1.getWaitedTime();
if (waitCntDiff < waited) {
throw new Error("Unexpected diff in waited count. Expecting at least "
+ waited + " , got " + waitCntDiff);
}
// wait until BlockedThread to block on lockC
blockedThread.waitUntilBlocked();
blockedCount++;
checkInfo(blockedThread, Thread.State.BLOCKED,
lockC, "lockC",
blockedCount, waitedCount);
if (waitTimeDiff <= 0) {
throw new Error("Unexpected diff in waited time. Expecting increasing " +
"value, got " + waitTimeDiff + "ms");
}
// wait until BlockedThread to block on lockD
blockedThread.waitUntilBlocked();
blockedCount++;
checkInfo(blockedThread, Thread.State.BLOCKED,
lockD, "lockD",
blockedCount, waitedCount);
}
// wait until BlockedThread about to call E()
// BlockedThread will wait on waiter for 3 times
blockedThread.waitUntilWaiting();
waitedCount++;
checkInfo(blockedThread, Thread.State.TIMED_WAITING,
waiter, "waiter", blockedCount, waitedCount);
blockedThread.waitUntilWaiting();
waitedCount++;
checkInfo(blockedThread, Thread.State.TIMED_WAITING,
waiter, "waiter", blockedCount, waitedCount);
blockedThread.waitUntilWaiting();
waitedCount++;
checkInfo(blockedThread, Thread.State.TIMED_WAITING,
waiter, "waiter", blockedCount, waitedCount);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Unexpected exception.");
testFailed = true;
private static void testBlocked(ThreadInfo ti1, ThreadInfo ti2,
String lockName, final Object lock)
throws Error {
long blkCntDiff = ti2.getBlockedCount() - ti1.getBlockedCount();
long blkTimeDiff = ti2.getBlockedTime() - ti1.getBlockedTime();
if (blkCntDiff < 1) {
throw new Error("Unexpected diff in blocked count. Expecting at least 1, " +
"got " + blkCntDiff);
}
if (blkTimeDiff < 0) {
throw new Error("Unexpected diff in blocked time. Expecting a positive " +
"number, got " + blkTimeDiff);
}
public void run() {
examine();
} // run()
public void waitUntilWaiting() {
semaphore.semaP();
// wait until the examiner is waiting for
while (!blockedThread.hasWaitersForBlocked()) {
goSleep(50);
if (!lockName.equals(lock.toString())) {
throw new Error("Unexpected blocked monitor name. Expecting " +
lock.toString() + ", got " +
lockName);
}
// give a chance for the examiner thread to really wait
goSleep(20);
}
} // Examiner
}
<!--
Copyright (c) 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.
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.
-->
<html>
<head>
<title>High resolution icon test, bug ID 8024926</title>
</head>
<body>
<applet CODE="bug8024926.class" WIDTH=300 HEIGHT=100></applet>
<p> See the dialog box (usually in upper left corner) for instructions</p>
</body>
</html>
/*
* Copyright (c) 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.
*
* 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.
*/
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.TextArea;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import sun.awt.OSInfo;
/**
* @test
* @bug 8024926
* @summary [macosx] AquaIcon HiDPI support
* @author Alexander Scherbatiy
* @run applet/manual=yesno bug8024926.html
*/
public class bug8024926 extends JApplet {
//Declare things used in the test, like buttons and labels here
public void init() {
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout(new BorderLayout());
if (OSInfo.getOSType().equals(OSInfo.OSType.MACOSX)) {
String[] instructions = {
"Verify that high resolution system icons are used"
+ " in JOptionPane on HiDPI displays.",
"1) Run the test on Retina display or enable the Quartz Debug"
+ " and select the screen resolution with (HiDPI) label",
"2) Check that the error icon on the JOptionPane is smooth",
"If so, press PASS, else press FAIL."
};
Sysout.createDialogWithInstructions(instructions);
} else {
String[] instructions = {
"This test is not applicable to the current platform. Press PASS."
};
Sysout.createDialogWithInstructions(instructions);
}
}//End init()
public void start() {
//Get things going. Request focus, set size, et cetera
setSize(200, 200);
setVisible(true);
validate();
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}// start()
//The rest of this class is the actions which perform the test...
//Use Sysout.println to communicate with the user NOT System.out!!
//Sysout.println ("Something Happened!");
private static void createAndShowGUI() {
JOptionPane.showMessageDialog(null,
"Icons should have high resolution.",
"High resolution icon test.",
JOptionPane.ERROR_MESSAGE);
}
}// class BlockedWindowTest
/* Place other classes related to the test after this line */
/**
* **************************************************
* Standard Test Machinery DO NOT modify anything below -- it's a standard chunk
* of code whose purpose is to make user interaction uniform, and thereby make
* it simpler to read and understand someone else's test.
* **************************************************
*/
/**
* This is part of the standard test machinery. It creates a dialog (with the
* instructions), and is the interface for sending text messages to the user. To
* print the instructions, send an array of strings to Sysout.createDialog
* WithInstructions method. Put one line of instructions per array entry. To
* display a message for the tester to see, simply call Sysout.println with the
* string to be displayed. This mimics System.out.println but works within the
* test harness as well as standalone.
*/
class Sysout {
private static TestDialog dialog;
public static void createDialogWithInstructions(String[] instructions) {
dialog = new TestDialog(new Frame(), "Instructions");
dialog.printInstructions(instructions);
dialog.setVisible(true);
println("Any messages for the tester will display here.");
}
public static void createDialog() {
dialog = new TestDialog(new Frame(), "Instructions");
String[] defInstr = {"Instructions will appear here. ", ""};
dialog.printInstructions(defInstr);
dialog.setVisible(true);
println("Any messages for the tester will display here.");
}
public static void printInstructions(String[] instructions) {
dialog.printInstructions(instructions);
}
public static void println(String messageIn) {
dialog.displayMessage(messageIn);
}
}// Sysout class
/**
* This is part of the standard test machinery. It provides a place for the test
* instructions to be displayed, and a place for interactive messages to the
* user to be displayed. To have the test instructions displayed, see Sysout. To
* have a message to the user be displayed, see Sysout. Do not call anything in
* this dialog directly.
*/
class TestDialog extends Dialog {
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog(Frame frame, String name) {
super(frame, name);
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
add("North", instructionsText);
messageText = new TextArea("", 5, maxStringLength, scrollBoth);
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions(String[] instructions) {
//Clear out any current instructions
instructionsText.setText("");
//Go down array of instruction strings
String printStr, remainingStr;
for (int i = 0; i < instructions.length; i++) {
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i];
while (remainingStr.length() > 0) {
//if longer than max then chop off first max chars to print
if (remainingStr.length() >= maxStringLength) {
//Try to chop on a word boundary
int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1);
if (posOfSpace <= 0) {
posOfSpace = maxStringLength - 1;
}
printStr = remainingStr.substring(0, posOfSpace + 1);
remainingStr = remainingStr.substring(posOfSpace + 1);
} //else just print
else {
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append(printStr + "\n");
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage(String messageIn) {
messageText.append(messageIn + "\n");
System.out.println(messageIn);
}
}// TestDialog class
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2014, 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
......@@ -28,6 +28,8 @@ import java.util.function.Function;
/**
* @test
* @bug 8020816
* @author Robert Field
*/
......
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2014, 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
......@@ -116,11 +116,17 @@ public class Version {
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
// HSX has nn.n[n] (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
if (Character.isDigit(cs.charAt(4))) {
minor = Integer.valueOf(version.substring(3, 5)).intValue();
cs = cs.subSequence(5, cs.length());
}
else {
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
......
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2014, 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
......@@ -23,7 +23,7 @@
/**
* @test
* @bug 6545058 6611182
* @bug 6545058 6611182 8016209
* @summary validate and test -version, -fullversion, and internal, as well as
* sanity checks if a tool can be launched.
* @compile VersionCheck.java
......
/*
* Copyright (c) 2014, 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.
*
* 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.
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
/*
* @test
* @bug 8029646
* @summary tests that native unpacker produces the same result as Java one
* @compile -XDignore.symbol.file Utils.java PackTestZip64.java
* @run main PackTestZip64
* @author kizune
*/
public class PackTestZip64 {
public static void main(String... args) throws Exception {
testPacking();
Utils.cleanup();
}
// 1KB buffer is enough to copy jar content
private static final byte[] BUFFER = new byte[1024];
static void testPacking() throws IOException {
// make a copy of the test specimen to local directory
File testFile = new File("tools_java.jar");
// Add a large number of small files to the golden jar
generateLargeJar(testFile, Utils.locateJar("golden.jar"));
List<String> cmdsList = new ArrayList<>();
// Repack file to get the Java-based result
cmdsList.add(Utils.getPack200Cmd());
cmdsList.add("--repack");
cmdsList.add(testFile.getName());
Utils.runExec(cmdsList);
cmdsList.clear();
// Pack file with pack200 and unpack in with unpack200
File packedFile = new File("tools.pack.gz");
cmdsList.add(Utils.getPack200Cmd());
cmdsList.add(packedFile.getName());
cmdsList.add(testFile.getName());
Utils.runExec(cmdsList);
cmdsList.clear();
File unpackedFile = new File("tools_native.jar");
cmdsList.add(Utils.getUnpack200Cmd());
cmdsList.add(packedFile.getName());
cmdsList.add(unpackedFile.getName());
Utils.runExec(cmdsList);
// Compare files binary
compareTwoFiles(testFile, unpackedFile);
// Cleaning up generated files
testFile.delete();
packedFile.delete();
unpackedFile.delete();
}
static void compareTwoFiles(File src, File dst) throws IOException {
if (!src.exists()) {
throw new IOException("File " + src.getName() + " does not exist!");
}
if(!dst.exists()) {
throw new IOException("File " + dst.getName() + " does not exist!");
}
BufferedInputStream srcis, dstis;
srcis = new BufferedInputStream(new FileInputStream(src));
dstis = new BufferedInputStream(new FileInputStream(dst));
int s = 0, d, pos = 0;
while (s != -1) { // Checking of just one result for EOF is enough
s = srcis.read();
d = dstis.read();
if (s != d) {
throw new IOException("Files are differ starting at position: "
+ Integer.toHexString(pos));
}
pos++;
}
srcis.close();
dstis.close();
}
static void generateLargeJar(File result, File source) throws IOException {
if (result.exists()) {
result.delete();
}
try (JarOutputStream copyTo = new JarOutputStream(new FileOutputStream(result));
JarFile srcJar = new JarFile(source)) {
for (JarEntry je : Collections.list(srcJar.entries())) {
copyTo.putNextEntry(je);
if (!je.isDirectory()) {
copyStream(srcJar.getInputStream(je), copyTo);
}
copyTo.closeEntry();
}
int many = Short.MAX_VALUE * 2 + 2;
for (int i = 0 ; i < many ; i++) {
JarEntry e = new JarEntry("F-" + i + ".txt");
copyTo.putNextEntry(e);
}
copyTo.flush();
copyTo.close();
}
}
static void copyStream(InputStream in, OutputStream out) throws IOException {
int bytesRead;
while ((bytesRead = in.read(BUFFER))!= -1) {
out.write(BUFFER, 0, bytesRead);
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册