提交 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) {
Image createImage() {
return getThisApplicationsIcon(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,15 +70,15 @@ 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;
}
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.
// Verify that the hotspot is within cursor bounds.
......@@ -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,9 +492,30 @@ 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);
}
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://";
......@@ -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;
}
Image resolutionVariant = getImageFromHash(this, resolutionVariantName);
image = createImageWithResolutionVariant(image, resolutionVariant);
imgCache.put(fileName, image);
return image;
}
return createImage(new FileImageSource(filename));
}
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;
}
}
}
} catch (java.io.IOException ioe) {
sm.checkConnect(url.getHost(), url.getPort());
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;
}
}
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;
* }
*
* @Override
* public List<Image> getResolutionVariants() {
* return Arrays.asList(this, highResolutionImage);
* }
* }
* }</pre>
*
* It is recommended to cache image variants for performance reasons.
*
* @summary This class is used to synchronize execution of two threads.
* @author Swamy Venkataramanappa
* <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) {
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);
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) 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;
......@@ -46,48 +47,62 @@ public class Locks {
if (lock == null) return null;
return lock.getClass().getName() + '@' +
Integer.toHexString(System.identityHashCode(lock));
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) {
throw new RuntimeException("Thread " + t.getName() +
" is expected to block on " + expectedLock +
" but got " + result +
" Thread.State = " + info.getThreadState());
" is expected to block on " + expectedLock +
" but got " + result +
" Thread.State = " + info.getThreadState());
}
goSleep(100);
info = tm.getThreadInfo(tid);
result = info.getLockName();
}
}
if (expectedState == Thread.State.WAITING &&
info.getThreadState() != Thread.State.WAITING) {
info.getThreadState() != Thread.State.WAITING) {
throw new RuntimeException("Thread " + t.getName() +
" is expected to wait on " + expectedLock +
" but got " + result +
" Thread.State = " + info.getThreadState());
" is expected to wait on " + expectedLock +
" but got " + result +
" Thread.State = " + info.getThreadState());
}
}
if ((result != null && !result.equals(expectedLock)) ||
(result == null && expectedLock != null)) {
(result == null && expectedLock != null)) {
throw new RuntimeException("Thread " + t.getName() + " is blocked on " +
expectedLock + " but got " + result);
expectedLock + " but got " + result);
}
result = info.getLockOwnerName();
if ((result != null && !result.equals(expectedOwner)) ||
(result == null && expectedOwner != null)) {
(result == null && expectedOwner != null)) {
throw new RuntimeException("Owner of " + lock + " should be " +
expectedOwner + " but got " + result);
expectedOwner + " but got " + result);
}
}
......@@ -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) {};
// stop here for LockBThread to hold objB
System.out.println("LockAThread about to block on 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");
// Signal main thread about to block on objC
thrsync1.signal();
synchronized(objC) {};
System.out.println("LockBThread about to block on objC");
p.arriveAndAwaitAdvance(); // Phase 1 (blocking)
// Signal main thread about to block on 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,32 +165,36 @@ 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();
objC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
testFailed = true;
}
// block until CheckerThread finishes checking
System.out.println("WaitingThread about to block on ready");
// signal checker thread that it is about acquire
// object ready.
thrsync.signal();
synchronized(ready) {};
System.out.println("WaitingThread about to wait on objC");
try {
// Signal checker thread, about to wait on objC.
p.arriveAndAwaitAdvance(); // Phase 1 (waiting)
objC.wait();
} catch (InterruptedException e) {
e.printStackTrace();
testFailed = true;
}
// block until CheckerThread finishes checking
System.out.println("WaitingThread about to block on ready");
// signal checker thread that it is about acquire
// object 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,21 +205,23 @@ 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) {
goSleep(10);
p.arriveAndAwaitAdvance();
while (!waiter.isInterrupted() && waiter.getState() != state) {
goSleep(10);
}
}
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 {
......@@ -284,7 +302,7 @@ public class Locks {
}
private static ThreadInfo findOwnerInfo(ThreadInfo[] infos, String lock)
throws Exception {
throws Exception {
ThreadInfo ownerInfo = null;
for (int i = 0; i < infos.length; i++) {
String blockedLock = infos[i].getLockName();
......@@ -292,7 +310,7 @@ public class Locks {
long threadId = infos[i].getLockOwnerId();
if (threadId == -1) {
throw new RuntimeException("TEST FAILED: " +
lock + " expected to have owner");
lock + " expected to have owner");
}
for (int j = 0; j < infos.length; j++) {
if (infos[j].getThreadId() == threadId) {
......@@ -305,7 +323,7 @@ public class Locks {
return ownerInfo;
}
private static void findThreadsBlockedOn(Object o, long[] expectedThreads)
throws Exception {
throws Exception {
String lock = getLockName(o);
// Check with ThreadInfo with no stack trace (i.e. no safepoint)
ThreadInfo[] infos = tm.getThreadInfo(tm.getAllThreadIds());
......@@ -317,14 +335,14 @@ public class Locks {
}
private static void doCheck(ThreadInfo[] infos, String lock, long[] expectedThreads)
throws Exception {
throws Exception {
ThreadInfo ownerInfo = null;
// Find the thread who is blocking on lock
for (int i = 0; i < infos.length; i++) {
String blockedLock = infos[i].getLockName();
if (lock.equals(blockedLock)) {
System.out.print(infos[i].getThreadName() +
" blocked on " + blockedLock);
" blocked on " + blockedLock);
ownerInfo = infos[i];
}
}
......@@ -336,7 +354,7 @@ public class Locks {
ownerInfo = findOwnerInfo(infos, lock);
threads[count++] = ownerInfo.getThreadId();
System.out.println(" Owner = " + ownerInfo.getThreadName() +
" id = " + ownerInfo.getThreadId());
" id = " + ownerInfo.getThreadId());
lock = ownerInfo.getLockName();
System.out.print(ownerInfo.getThreadName() + " Id = " +
ownerInfo.getThreadId() +
......@@ -346,13 +364,13 @@ public class Locks {
if (count != expectedThreads.length) {
throw new RuntimeException("TEST FAILED: " +
"Expected chain of threads not matched; current count =" + count);
"Expected chain of threads not matched; current count =" + count);
}
for (int i = 0; i < count; i++) {
if (threads[i] != expectedThreads[i]) {
System.out.println("TEST FAILED: " +
"Unexpected thread in the chain " + threads[i] +
" expected to be " + expectedThreads[i]);
"Unexpected thread in the chain " + threads[i] +
" expected to be " + expectedThreads[i]);
}
}
}
......
<!--
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,10 +116,16 @@ 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();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
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)) &&
......
/*
* 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.
先完成此消息的编辑!
想要评论请 注册