This commit is contained in:
Phil Race 2014-06-18 14:53:35 -07:00
commit 48ca67c5c4
103 changed files with 2977 additions and 354 deletions

View File

@ -317,6 +317,8 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
* subclasses to initialize specific peers properties.
*/
void initializeImpl() {
// note that these methods can be overridden by the user and
// can return some strange values like null.
setBackground(target.getBackground());
setForeground(target.getForeground());
setFont(target.getFont());

View File

@ -443,6 +443,12 @@ public class LWWindowPeer
getPlatformWindow().updateIconImages();
}
@Override
public void setBackground(final Color c) {
super.setBackground(c);
updateOpaque();
}
@Override
public void setOpacity(float opacity) {
getPlatformWindow().setOpacity(opacity);

View File

@ -29,12 +29,18 @@ import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.MenuBar;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import sun.awt.CGraphicsDevice;
import sun.awt.CGraphicsEnvironment;
import sun.awt.CausedFocusEvent;
import sun.awt.LightweightFrame;
import sun.java2d.SurfaceData;
import sun.lwawt.LWLightweightFramePeer;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformWindow;
@ -72,11 +78,6 @@ public class CPlatformLWWindow extends CPlatformWindow {
return null;
}
@Override
public GraphicsDevice getGraphicsDevice() {
return null;
}
@Override
public SurfaceData getScreenSurface() {
return null;
@ -199,4 +200,24 @@ public class CPlatformLWWindow extends CPlatformWindow {
public long getLayerPtr() {
return 0;
}
@Override
public GraphicsDevice getGraphicsDevice() {
CGraphicsEnvironment ge = (CGraphicsEnvironment)GraphicsEnvironment.
getLocalGraphicsEnvironment();
LWLightweightFramePeer peer = (LWLightweightFramePeer)getPeer();
int scale = ((LightweightFrame)peer.getTarget()).getScaleFactor();
Rectangle bounds = ((LightweightFrame)peer.getTarget()).getHostBounds();
for (GraphicsDevice d : ge.getScreenDevices()) {
if (d.getDefaultConfiguration().getBounds().intersects(bounds) &&
((CGraphicsDevice)d).getScaleFactor() == scale)
{
return d;
}
}
// We shouldn't be here...
return ge.getDefaultScreenDevice();
}
}

View File

@ -746,20 +746,22 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
@Override
public void setOpaque(boolean isOpaque) {
CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
boolean isTextured = (peer == null)? false : peer.isTextured();
if (!isOpaque && !isTextured) {
long clearColor = CWrapper.NSColor.clearColor();
CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
boolean isTextured = (peer == null) ? false : peer.isTextured();
if (!isTextured) {
if (!isOpaque) {
CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), 0);
} else if (peer != null) {
Color color = peer.getBackground();
if (color != null) {
int rgb = color.getRGB();
CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), rgb);
}
}
}
//This is a temporary workaround. Looks like after 7124236 will be fixed
//the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
invalidateShadow();
}
});
SwingUtilities.invokeLater(this::invalidateShadow);
}
@Override

View File

@ -61,7 +61,14 @@ final class CWrapper {
static native void setAlphaValue(long window, float alpha);
static native void setOpaque(long window, boolean opaque);
static native void setBackgroundColor(long window, long color);
/**
* Sets background color of the NSWindow.
*
* @param window the pointer of the NSWindow
* @param color the color in argb format
*/
static native void setBackgroundColor(long window, int color);
static native void miniaturize(long window);
static native void deminiaturize(long window);
@ -82,8 +89,4 @@ final class CWrapper {
static native void setToolTip(long view, String msg);
}
static final class NSColor {
static native long clearColor();
}
}

View File

@ -57,7 +57,7 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){
CFArrayRef allModes = CGDisplayCopyAllDisplayModes(displayID, NULL);
CFIndex numModes = CFArrayGetCount(allModes);
CFMutableArrayRef validModes = CFArrayCreateMutable(kCFAllocatorDefault, numModes + 1, NULL);
CFMutableArrayRef validModes = CFArrayCreateMutable(kCFAllocatorDefault, numModes + 1, &kCFTypeArrayCallBacks);
CFIndex n;
for (n=0; n < numModes; n++) {

View File

@ -337,12 +337,17 @@ JNF_COCOA_EXIT(env);
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CWrapper_00024NSWindow_setBackgroundColor
(JNIEnv *env, jclass cls, jlong windowPtr, jlong colorPtr)
(JNIEnv *env, jclass cls, jlong windowPtr, jint rgb)
{
JNF_COCOA_ENTER(env);
NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr);
NSColor *color = (NSColor *)jlong_to_ptr(colorPtr);
CGFloat alpha = (((rgb >> 24) & 0xff) / 255.0);
CGFloat red = (((rgb >> 16) & 0xff) / 255.0);
CGFloat green = (((rgb >> 8) & 0xff) / 255.0);
CGFloat blue = (((rgb >> 0) & 0xff) / 255.0);
NSColor *color = [NSColor colorWithCalibratedRed:red green:green blue:blue
alpha:alpha];
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
[window setBackgroundColor:color];
}];
@ -575,26 +580,3 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CWrapper$NSColor
* Method: clearColor
* Signature: ()J
*/
JNIEXPORT jlong JNICALL
Java_sun_lwawt_macosx_CWrapper_00024NSColor_clearColor
(JNIEnv *env, jclass cls)
{
__block jlong clearColorPtr = 0L;
JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
clearColorPtr = ptr_to_jlong([NSColor clearColor]);
}];
JNF_COCOA_EXIT(env);
return clearColorPtr;
}

View File

@ -1,5 +1,5 @@
/*
* 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
@ -285,6 +285,8 @@ public abstract class Path2D implements Shape, Cloneable {
int grow = size;
if (grow > EXPAND_MAX) {
grow = EXPAND_MAX;
} else if (grow == 0) {
grow = 1;
}
pointTypes = Arrays.copyOf(pointTypes, size+grow);
}
@ -1121,6 +1123,8 @@ public abstract class Path2D implements Shape, Cloneable {
int grow = size;
if (grow > EXPAND_MAX) {
grow = EXPAND_MAX;
} else if (grow == 0) {
grow = 1;
}
pointTypes = Arrays.copyOf(pointTypes, size+grow);
}

View File

@ -647,6 +647,7 @@ public class JDialog extends Dialog implements WindowConstants,
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
setLocale( JComponent.getDefaultLocale() );
setRootPane(createRootPane());
setBackground(UIManager.getColor("control"));
setRootPaneCheckingEnabled(true);
if (JDialog.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =

View File

@ -1809,7 +1809,7 @@ public abstract class AbstractDocument implements Document, Serializable {
if (getAttributeCount() > 0) {
out.println("");
// dump the attributes
Enumeration names = attributes.getAttributeNames();
Enumeration<?> names = attributes.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
indent(out, indentAmount + 1);
@ -2193,7 +2193,7 @@ public abstract class AbstractDocument implements Document, Serializable {
* <code>Enumeration</code>.
* @return the children of the receiver as an <code>Enumeration</code>
*/
public abstract Enumeration children();
public abstract Enumeration<?> children();
// --- serialization ---------------------------------------------
@ -2456,7 +2456,7 @@ public abstract class AbstractDocument implements Document, Serializable {
* <code>Enumeration</code>.
* @return the children of the receiver
*/
public Enumeration children() {
public Enumeration<AbstractElement> children() {
if(nchildren == 0)
return null;
@ -2610,7 +2610,7 @@ public abstract class AbstractDocument implements Document, Serializable {
* <code>Enumeration</code>.
* @return the children of the receiver
*/
public Enumeration children() {
public Enumeration<?> children() {
return null;
}

View File

@ -668,7 +668,7 @@ public abstract class AbstractWriter {
*/
protected void writeAttributes(AttributeSet attr) throws IOException {
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
write(" " + name + "=" + attr.getAttribute(name));

View File

@ -108,8 +108,8 @@ public class DateFormatter extends InternationalFormatter {
/**
* Returns the field that will be adjusted by adjustValue.
*/
Object getAdjustField(int start, Map attributes) {
Iterator attrs = attributes.keySet().iterator();
Object getAdjustField(int start, Map<?, ?> attributes) {
Iterator<?> attrs = attributes.keySet().iterator();
while (attrs.hasNext()) {
Object key = attrs.next();
@ -127,7 +127,7 @@ public class DateFormatter extends InternationalFormatter {
* Adjusts the Date if FieldPosition identifies a known calendar
* field.
*/
Object adjustValue(Object value, Map attributes, Object key,
Object adjustValue(Object value, Map<?, ?> attributes, Object key,
int direction) throws
BadLocationException, ParseException {
if (key != null) {

View File

@ -246,12 +246,12 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter
}
}
if (vc != null) {
Constructor cons;
Constructor<?> cons;
try {
ReflectUtil.checkPackageAccess(vc);
SwingUtilities2.checkAccess(vc.getModifiers());
cons = vc.getConstructor(new Class[]{String.class});
cons = vc.getConstructor(new Class<?>[]{String.class});
} catch (NoSuchMethodException nsme) {
cons = null;

View File

@ -1048,8 +1048,9 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc
styleChangeListener = createStyleChangeListener();
}
if (styleChangeListener != null && styles != null) {
Enumeration styleNames = styles.getStyleNames();
Vector v = (Vector)listeningStyles.clone();
Enumeration<?> styleNames = styles.getStyleNames();
@SuppressWarnings("unchecked")
Vector<Style> v = (Vector<Style>)listeningStyles.clone();
listeningStyles.removeAllElements();
List<ChangeListener> staleListeners =
AbstractChangeHandler.getStaleListeners(styleChangeListener);
@ -1069,7 +1070,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc
}
}
for (int counter = v.size() - 1; counter >= 0; counter--) {
Style aStyle = (Style)v.elementAt(counter);
Style aStyle = v.elementAt(counter);
aStyle.removeChangeListener(styleChangeListener);
}
if (listeningStyles.size() == 0) {
@ -2630,14 +2631,14 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc
}
/** Class-specific reference queues. */
private final static Map<Class, ReferenceQueue<DefaultStyledDocument>> queueMap
= new HashMap<Class, ReferenceQueue<DefaultStyledDocument>>();
private final static Map<Class<?>, ReferenceQueue<DefaultStyledDocument>> queueMap
= new HashMap<Class<?>, ReferenceQueue<DefaultStyledDocument>>();
/** A weak reference to the document object. */
private DocReference doc;
AbstractChangeHandler(DefaultStyledDocument d) {
Class c = getClass();
Class<?> c = getClass();
ReferenceQueue<DefaultStyledDocument> q;
synchronized (queueMap) {
q = queueMap.get(c);

View File

@ -361,7 +361,7 @@ public class ElementIterator implements Cloneable {
System.out.println("elem: " + elem.getName());
AttributeSet attr = elem.getAttributes();
String s = "";
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object key = names.nextElement();
Object value = attr.getAttribute(key);

View File

@ -710,7 +710,8 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
* @param length the length &gt;= 0
* @return the set of instances
*/
protected Vector getPositionsInRange(Vector v, int offset, int length) {
protected Vector<UndoPosRef> getPositionsInRange(Vector<UndoPosRef> v,
int offset, int length) {
int endOffset = offset + length;
int startIndex;
int endIndex;
@ -738,8 +739,9 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
endIndex = findMarkAdjustIndex(endOffset + (g1 - g0) + 1);
}
Vector placeIn = (v == null) ? new Vector(Math.max(1, endIndex -
startIndex)) : v;
Vector<UndoPosRef> placeIn = (v == null) ?
new Vector<>(Math.max(1, endIndex - startIndex)) :
v;
for (int counter = startIndex; counter < endIndex; counter++) {
placeIn.addElement(new UndoPosRef(marks.elementAt(counter)));
@ -756,7 +758,7 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
*
* @param positions the UndoPosRef instances to reset
*/
protected void updateUndoPositions(Vector positions, int offset,
protected void updateUndoPositions(Vector<UndoPosRef> positions, int offset,
int length) {
// Find the indexs of the end points.
int endOffset = offset + length;
@ -773,7 +775,7 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
// Reset the location of the refenences.
for(int counter = positions.size() - 1; counter >= 0; counter--) {
UndoPosRef ref = (UndoPosRef)positions.elementAt(counter);
UndoPosRef ref = positions.elementAt(counter);
ref.resetLocation(endOffset, g1);
}
// We have to resort the marks in the range startIndex to endIndex.
@ -900,7 +902,7 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
protected String string;
/** An array of instances of UndoPosRef for the Positions in the
* range that was removed, valid after undo. */
protected Vector posRefs;
protected Vector<UndoPosRef> posRefs;
} // GapContent.InsertUndo
@ -952,6 +954,6 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S
protected String string;
/** An array of instances of UndoPosRef for the Positions in the
* range that was removed, valid before undo. */
protected Vector posRefs;
protected Vector<UndoPosRef> posRefs;
} // GapContent.RemoveUndo
}

View File

@ -253,7 +253,7 @@ public class GlyphView extends View implements TabableView, Cloneable {
// the classname should probably come from a property file.
String classname = "javax.swing.text.GlyphPainter1";
try {
Class c;
Class<?> c;
ClassLoader loader = getClass().getClassLoader();
if (loader != null) {
c = loader.loadClass(classname);

View File

@ -106,11 +106,11 @@ public class InternationalFormatter extends DefaultFormatter {
/**
* Can be used to impose a maximum value.
*/
private Comparable max;
private Comparable<?> max;
/**
* Can be used to impose a minimum value.
*/
private Comparable min;
private Comparable<?> min;
/**
* <code>InternationalFormatter</code>'s behavior is dicatated by a
@ -211,7 +211,7 @@ public class InternationalFormatter extends DefaultFormatter {
* @param minimum Minimum legal value that can be input
* @see #setValueClass
*/
public void setMinimum(Comparable minimum) {
public void setMinimum(Comparable<?> minimum) {
if (getValueClass() == null && minimum != null) {
setValueClass(minimum.getClass());
}
@ -223,7 +223,7 @@ public class InternationalFormatter extends DefaultFormatter {
*
* @return Minimum legal value that can be input
*/
public Comparable getMinimum() {
public Comparable<?> getMinimum() {
return min;
}
@ -236,7 +236,7 @@ public class InternationalFormatter extends DefaultFormatter {
* @param max Maximum legal value that can be input
* @see #setValueClass
*/
public void setMaximum(Comparable max) {
public void setMaximum(Comparable<?> max) {
if (getValueClass() == null && max != null) {
setValueClass(max.getClass());
}
@ -248,7 +248,7 @@ public class InternationalFormatter extends DefaultFormatter {
*
* @return Maximum legal value that can be input
*/
public Comparable getMaximum() {
public Comparable<?> getMaximum() {
return max;
}
@ -411,7 +411,8 @@ public class InternationalFormatter extends DefaultFormatter {
* false is returned.
*/
boolean isValidValue(Object value, boolean wantsCCE) {
Comparable min = getMinimum();
@SuppressWarnings("unchecked")
Comparable<Object> min = (Comparable<Object>)getMinimum();
try {
if (min != null && min.compareTo(value) > 0) {
@ -424,7 +425,8 @@ public class InternationalFormatter extends DefaultFormatter {
return false;
}
Comparable max = getMaximum();
@SuppressWarnings("unchecked")
Comparable<Object> max = (Comparable<Object>)getMaximum();
try {
if (max != null && max.compareTo(value) < 0) {
return false;
@ -770,7 +772,7 @@ public class InternationalFormatter extends DefaultFormatter {
/**
* Returns true if <code>attributes</code> is null or empty.
*/
boolean isLiteral(Map attributes) {
boolean isLiteral(Map<?, ?> attributes) {
return ((attributes == null) || attributes.size() == 0);
}
@ -797,7 +799,7 @@ public class InternationalFormatter extends DefaultFormatter {
iterator.first();
while (iterator.current() != CharacterIterator.DONE) {
Map attributes = iterator.getAttributes();
Map<Attribute,Object> attributes = iterator.getAttributes();
boolean set = isLiteral(attributes);
int start = iterator.getIndex();
int end = iterator.getRunLimit();
@ -858,7 +860,7 @@ public class InternationalFormatter extends DefaultFormatter {
/**
* Returns the field that will be adjusted by adjustValue.
*/
Object getAdjustField(int start, Map attributes) {
Object getAdjustField(int start, Map<?, ?> attributes) {
return null;
}
@ -900,7 +902,7 @@ public class InternationalFormatter extends DefaultFormatter {
* null depending upon <code>canIncrement</code>) and
* <code>direction</code> is the amount to increment by.
*/
Object adjustValue(Object value, Map attributes, Object field,
Object adjustValue(Object value, Map<?, ?> attributes, Object field,
int direction) throws
BadLocationException, ParseException {
return null;
@ -1023,7 +1025,7 @@ public class InternationalFormatter extends DefaultFormatter {
iterator.setIndex(start);
Map attributes = iterator.getAttributes();
Map<Attribute,Object> attributes = iterator.getAttributes();
Object field = getAdjustField(start, attributes);
if (canIncrement(field, start)) {

View File

@ -1091,6 +1091,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A
private static HashMap<String,Keymap> getKeymapTable() {
synchronized (KEYMAP_TABLE) {
AppContext appContext = AppContext.getAppContext();
@SuppressWarnings("unchecked")
HashMap<String,Keymap> keymapTable =
(HashMap<String,Keymap>)appContext.get(KEYMAP_TABLE);
if (keymapTable == null) {

View File

@ -173,7 +173,8 @@ public class NumberFormatter extends InternationalFormatter {
* <code>Byte</code> or <code>Short</code> and <code>value</code>
* is an instanceof <code>Number</code>.
*/
private Object convertValueToValueClass(Object value, Class valueClass) {
private Object convertValueToValueClass(Object value,
Class<?> valueClass) {
if (valueClass != null && (value instanceof Number)) {
Number numberValue = (Number)value;
if (valueClass == Integer.class) {
@ -266,7 +267,7 @@ public class NumberFormatter extends InternationalFormatter {
* Subclassed to treat the decimal separator, grouping separator,
* exponent symbol, percent, permille, currency and sign as literals.
*/
boolean isLiteral(Map attrs) {
boolean isLiteral(Map<?, ?> attrs) {
if (!super.isLiteral(attrs)) {
if (attrs == null) {
return false;
@ -327,7 +328,7 @@ public class NumberFormatter extends InternationalFormatter {
while (index >= 0 && index < max) {
iterator.setIndex(index);
Map attrs = iterator.getAttributes();
Map<?,?> attrs = iterator.getAttributes();
if (attrs != null && attrs.size() > 0) {
for (Object key : attrs.keySet()) {
@ -432,8 +433,8 @@ public class NumberFormatter extends InternationalFormatter {
try {
ReflectUtil.checkPackageAccess(valueClass);
SwingUtilities2.checkAccess(valueClass.getModifiers());
Constructor cons = valueClass.getConstructor(
new Class[] { String.class });
Constructor<?> cons = valueClass.getConstructor(
new Class<?>[] { String.class });
if (cons != null) {
SwingUtilities2.checkAccess(cons.getModifiers());
return cons.newInstance(new Object[]{string});

View File

@ -806,7 +806,7 @@ public class ParagraphView extends FlowView implements TabExpander {
/**
* Used to create an i18n-based layout strategy
*/
static Class i18nStrategy;
static Class<?> i18nStrategy;
/** Used for searching for a tab. */
static char[] tabChars;

View File

@ -172,7 +172,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
public boolean containsAttributes(AttributeSet attributes) {
boolean result = true;
Enumeration names = attributes.getAttributeNames();
Enumeration<?> names = attributes.getAttributeNames();
while (result && names.hasMoreElements()) {
Object name = names.nextElement();
result = attributes.getAttribute(name).equals(getAttribute(name));
@ -197,7 +197,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
* @param attributes the set of attributes to add
*/
public void addAttributes(AttributeSet attributes) {
Enumeration names = attributes.getAttributeNames();
Enumeration<?> names = attributes.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
addAttribute(name, attributes.getAttribute(name));
@ -233,7 +233,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
table.clear();
}
else {
Enumeration names = attributes.getAttributeNames();
Enumeration<?> names = attributes.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
Object value = attributes.getAttribute(name);
@ -272,6 +272,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
*
* @return the new set of attributes
*/
@SuppressWarnings("unchecked") // Cast of result of clone
public Object clone() {
SimpleAttributeSet attr;
try {
@ -317,7 +318,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
*/
public String toString() {
String s = "";
Enumeration names = getAttributeNames();
Enumeration<?> names = getAttributeNames();
while (names.hasMoreElements()) {
Object key = names.nextElement();
Object value = getAttribute(key);
@ -364,7 +365,7 @@ public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cl
public Object getAttribute(Object key) {
return null;
}
public Enumeration getAttributeNames() {
public Enumeration<?> getAttributeNames() {
return Collections.emptyEnumeration();
}
public boolean containsAttribute(Object name, Object value) {

View File

@ -271,11 +271,11 @@ public final class StringContent implements AbstractDocument.Content, Serializab
* @param length the length &gt;= 0
* @return the set of instances
*/
protected Vector getPositionsInRange(Vector v, int offset,
protected Vector<UndoPosRef> getPositionsInRange(Vector<UndoPosRef> v, int offset,
int length) {
int n = marks.size();
int end = offset + length;
Vector placeIn = (v == null) ? new Vector() : v;
Vector<UndoPosRef> placeIn = (v == null) ? new Vector<>() : v;
for (int i = 0; i < n; i++) {
PosRec mark = marks.elementAt(i);
if (mark.unused) {
@ -298,9 +298,9 @@ public final class StringContent implements AbstractDocument.Content, Serializab
*
* @param positions the positions of the instances
*/
protected void updateUndoPositions(Vector positions) {
protected void updateUndoPositions(Vector<UndoPosRef> positions) {
for(int counter = positions.size() - 1; counter >= 0; counter--) {
UndoPosRef ref = (UndoPosRef)positions.elementAt(counter);
UndoPosRef ref = positions.elementAt(counter);
// Check if the Position is still valid.
if(ref.rec.unused) {
positions.removeElementAt(counter);
@ -437,7 +437,7 @@ public final class StringContent implements AbstractDocument.Content, Serializab
protected String string;
// An array of instances of UndoPosRef for the Positions in the
// range that was removed, valid after undo.
protected Vector posRefs;
protected Vector<UndoPosRef> posRefs;
}
@ -494,6 +494,6 @@ public final class StringContent implements AbstractDocument.Content, Serializab
protected String string;
// An array of instances of UndoPosRef for the Positions in the
// range that was removed, valid before undo.
protected Vector posRefs;
protected Vector<UndoPosRef> posRefs;
}
}

View File

@ -589,7 +589,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
AttributeSet a) throws IOException {
int n = a.getAttributeCount();
out.writeInt(n);
Enumeration keys = a.getAttributeNames();
Enumeration<?> keys = a.getAttributeNames();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof Serializable) {
@ -771,7 +771,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
public SmallAttributeSet(AttributeSet attrs) {
int n = attrs.getAttributeCount();
Object[] tbl = new Object[2 * n];
Enumeration names = attrs.getAttributeNames();
Enumeration<?> names = attrs.getAttributeNames();
int i = 0;
while (names.hasMoreElements()) {
tbl[i] = names.nextElement();
@ -971,7 +971,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
public boolean containsAttributes(AttributeSet attrs) {
boolean result = true;
Enumeration names = attrs.getAttributeNames();
Enumeration<?> names = attrs.getAttributeNames();
while (result && names.hasMoreElements()) {
Object name = names.nextElement();
result = attrs.getAttribute(name).equals(getAttribute(name));
@ -1051,7 +1051,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
} else {
keys.removeAllElements();
data.removeAllElements();
Enumeration names = a.getAttributeNames();
Enumeration<?> names = a.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
addAttribute(name, a.getAttribute(name));
@ -1117,7 +1117,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
addAttribute(tbl[i], tbl[i+1]);
}
} else {
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
addAttribute(name, attr.getAttribute(name));
@ -1142,7 +1142,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
/**
* Removes the set of keys from the set.
*/
public void removeAttributes(Enumeration names) {
public void removeAttributes(Enumeration<?> names) {
while (names.hasMoreElements()) {
Object name = names.nextElement();
removeAttribute(name);
@ -1153,7 +1153,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon
* Removes the set of matching attributes from the set.
*/
public void removeAttributes(AttributeSet attr) {
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
Object value = attr.getAttribute(name);

View File

@ -115,8 +115,8 @@ public abstract class TextAction extends AbstractAction {
}
Action[] actions = new Action[h.size()];
int index = 0;
for (Enumeration e = h.elements() ; e.hasMoreElements() ;) {
actions[index++] = (Action) e.nextElement();
for (Enumeration<Action> e = h.elements() ; e.hasMoreElements() ;) {
actions[index++] = e.nextElement();
}
return actions;
}

View File

@ -2740,7 +2740,7 @@ class AccessibleHTML implements Accessible {
* <code>child</code> isn't a valid child.
*/
public int indexOf(ElementInfo child) {
ArrayList children = this.children;
ArrayList<ElementInfo> children = this.children;
if (children != null) {
return children.indexOf(child);

View File

@ -1370,7 +1370,7 @@ public class CSS implements Serializable {
private void translateEmbeddedAttributes(AttributeSet htmlAttrSet,
MutableAttributeSet cssAttrSet) {
Enumeration keys = htmlAttrSet.getAttributeNames();
Enumeration<?> keys = htmlAttrSet.getAttributeNames();
if (htmlAttrSet.getAttribute(StyleConstants.NameAttribute) ==
HTML.Tag.HR) {
// HR needs special handling due to us treating it as a leaf.
@ -1393,7 +1393,7 @@ public class CSS implements Serializable {
private void translateAttributes(HTML.Tag tag,
AttributeSet htmlAttrSet,
MutableAttributeSet cssAttrSet) {
Enumeration names = htmlAttrSet.getAttributeNames();
Enumeration<?> names = htmlAttrSet.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
@ -3342,7 +3342,7 @@ public class CSS implements Serializable {
s.defaultWriteObject();
// Determine what values in valueConvertor need to be written out.
Enumeration keys = valueConvertor.keys();
Enumeration<?> keys = valueConvertor.keys();
s.writeInt(valueConvertor.size());
if (keys != null) {
while (keys.hasMoreElements()) {

View File

@ -168,8 +168,8 @@ public class FormView extends ComponentView implements ActionListener {
} else if (t == HTML.Tag.SELECT) {
if (model instanceof OptionListModel) {
JList list = new JList((ListModel) model);
@SuppressWarnings("unchecked")
JList<?> list = new JList<>((ListModel) model);
int size = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.SIZE,
1);
@ -177,7 +177,9 @@ public class FormView extends ComponentView implements ActionListener {
list.setSelectionModel((ListSelectionModel)model);
c = new JScrollPane(list);
} else {
c = new JComboBox((ComboBoxModel) model);
@SuppressWarnings("unchecked")
JComboBox<?> tmp = new JComboBox<>((ComboBoxModel) model);
c = tmp;
maxIsPreferred = 3;
}
} else if (t == HTML.Tag.TEXTAREA) {
@ -342,7 +344,8 @@ public class FormView extends ComponentView implements ActionListener {
// BasicListUI$Handler.
// For JComboBox, there are 2 stale ListDataListeners, which are
// BasicListUI$Handler and BasicComboBoxUI$Handler.
AbstractListModel listModel = (AbstractListModel) model;
@SuppressWarnings("unchecked")
AbstractListModel<?> listModel = (AbstractListModel) model;
String listenerClass1 =
"javax.swing.plaf.basic.BasicListUI$Handler";
String listenerClass2 =
@ -788,6 +791,7 @@ public class FormView extends ComponentView implements ActionListener {
}
Object m = attr.getAttribute(StyleConstants.ModelAttribute);
if (m instanceof OptionListModel) {
@SuppressWarnings("unchecked")
OptionListModel<Option> model = (OptionListModel<Option>) m;
for (int i = 0; i < model.getSize(); i++) {
@ -797,7 +801,8 @@ public class FormView extends ComponentView implements ActionListener {
}
}
} else if (m instanceof ComboBoxModel) {
ComboBoxModel model = (ComboBoxModel)m;
@SuppressWarnings("unchecked")
ComboBoxModel<?> model = (ComboBoxModel)m;
Option option = (Option)model.getSelectedItem();
if (option != null) {
appendBuffer(buffer, name, option.getValue());
@ -904,7 +909,8 @@ public class FormView extends ComponentView implements ActionListener {
} catch (BadLocationException e) {
}
} else if (m instanceof OptionListModel) {
OptionListModel model = (OptionListModel) m;
@SuppressWarnings("unchecked")
OptionListModel<?> model = (OptionListModel) m;
int size = model.getSize();
for (int i = 0; i < size; i++) {
model.removeIndexInterval(i, i);
@ -916,7 +922,8 @@ public class FormView extends ComponentView implements ActionListener {
}
}
} else if (m instanceof OptionComboBoxModel) {
OptionComboBoxModel model = (OptionComboBoxModel) m;
@SuppressWarnings("unchecked")
OptionComboBoxModel<?> model = (OptionComboBoxModel) m;
Option option = model.getInitialSelection();
if (option != null) {
model.setSelectedItem(option);

View File

@ -863,11 +863,13 @@ public class HTMLDocument extends DefaultStyledDocument {
Object maps = getProperty(MAP_PROPERTY);
if (maps == null) {
maps = new Hashtable(11);
maps = new Hashtable<>(11);
putProperty(MAP_PROPERTY, maps);
}
if (maps instanceof Hashtable) {
((Hashtable)maps).put("#" + name, map);
@SuppressWarnings("unchecked")
Hashtable<Object, Object> tmp = (Hashtable)maps;
tmp.put("#" + name, map);
}
}
}
@ -910,11 +912,13 @@ public class HTMLDocument extends DefaultStyledDocument {
* @return the enumerated list of maps, or <code>null</code>
* if the maps are not an instance of <code>Hashtable</code>
*/
Enumeration getMaps() {
Enumeration<Object> getMaps() {
Object maps = getProperty(MAP_PROPERTY);
if (maps instanceof Hashtable) {
return ((Hashtable)maps).elements();
@SuppressWarnings("unchecked")
Hashtable<Object, Object> tmp = (Hashtable) maps;
return tmp.elements();
}
return null;
}
@ -1493,7 +1497,7 @@ public class HTMLDocument extends DefaultStyledDocument {
else if (searchLeafAttributes && attr != null) {
// For some leaf elements we store the actual attributes inside
// the AttributeSet of the Element (such as anchors).
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
if (names != null) {
while (names.hasMoreElements()) {
Object name = names.nextElement();
@ -2694,10 +2698,12 @@ public class HTMLDocument extends DefaultStyledDocument {
return;
}
if (comments == null) {
comments = new Vector();
comments = new Vector<>();
putProperty(AdditionalComments, comments);
}
((Vector)comments).addElement(comment);
@SuppressWarnings("unchecked")
Vector<Object> v = (Vector<Object>)comments;
v.addElement(comment);
}
/**
@ -3439,6 +3445,7 @@ public class HTMLDocument extends DefaultStyledDocument {
option = new Option(attr);
if (selectModel instanceof OptionListModel) {
@SuppressWarnings("unchecked")
OptionListModel<Option> m = (OptionListModel<Option>) selectModel;
m.addElement(option);
if (option.isSelected()) {
@ -3446,6 +3453,7 @@ public class HTMLDocument extends DefaultStyledDocument {
m.setInitialSelection(optionCount);
}
} else if (selectModel instanceof OptionComboBoxModel) {
@SuppressWarnings("unchecked")
OptionComboBoxModel<Option> m = (OptionComboBoxModel<Option>) selectModel;
m.addElement(option);
if (option.isSelected()) {

View File

@ -590,7 +590,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible {
protected Parser getParser() {
if (defaultParser == null) {
try {
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
Class<?> c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
defaultParser = (Parser) c.newInstance();
} catch (Throwable e) {
}
@ -1874,7 +1874,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible {
* Returns the object in an AttributeSet matching a key
*/
static private Object getAttrValue(AttributeSet attr, HTML.Attribute key) {
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object nextKey = names.nextElement();
Object nextVal = attr.getAttribute(nextKey);

View File

@ -254,7 +254,7 @@ public class HTMLWriter extends AbstractWriter {
convAttr.removeAttributes(convAttr);
convertToHTML32(attr, convAttr);
Enumeration names = convAttr.getAttributeNames();
Enumeration<?> names = convAttr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
if (name instanceof HTML.Tag ||
@ -527,6 +527,7 @@ public class HTMLWriter extends AbstractWriter {
Object model = attr.getAttribute(StyleConstants.ModelAttribute);
incrIndent();
if (model instanceof OptionListModel) {
@SuppressWarnings("unchecked")
OptionListModel<Option> listModel = (OptionListModel<Option>) model;
int size = listModel.getSize();
for (int i = 0; i < size; i++) {
@ -534,6 +535,7 @@ public class HTMLWriter extends AbstractWriter {
writeOption(option);
}
} else if (model instanceof OptionComboBoxModel) {
@SuppressWarnings("unchecked")
OptionComboBoxModel<Option> comboBoxModel = (OptionComboBoxModel<Option>) model;
int size = comboBoxModel.getSize();
for (int i = 0; i < size; i++) {
@ -657,7 +659,7 @@ public class HTMLWriter extends AbstractWriter {
(HTMLDocument.AdditionalComments);
if (comments instanceof Vector) {
Vector v = (Vector)comments;
Vector<?> v = (Vector)comments;
for (int counter = 0, maxCounter = v.size(); counter < maxCounter;
counter++) {
writeComment(v.elementAt(counter).toString());
@ -707,7 +709,7 @@ public class HTMLWriter extends AbstractWriter {
// translate css attributes to html
attr = convertToHTML(attr, oConvAttr);
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
if (name instanceof HTML.Tag) {
@ -848,7 +850,7 @@ public class HTMLWriter extends AbstractWriter {
* Outputs the maps as elements. Maps are not stored as elements in
* the document, and as such this is used to output them.
*/
void writeMaps(Enumeration maps) throws IOException {
void writeMaps(Enumeration<?> maps) throws IOException {
if (maps != null) {
while(maps.hasMoreElements()) {
Map map = (Map)maps.nextElement();
@ -896,7 +898,7 @@ public class HTMLWriter extends AbstractWriter {
*/
void writeStyles(StyleSheet sheet) throws IOException {
if (sheet != null) {
Enumeration styles = sheet.getStyleNames();
Enumeration<?> styles = sheet.getStyleNames();
if (styles != null) {
boolean outputStyle = false;
while (styles.hasMoreElements()) {
@ -922,7 +924,7 @@ public class HTMLWriter extends AbstractWriter {
boolean writeStyle(String name, Style style, boolean outputStyle)
throws IOException{
boolean didOutputStyle = false;
Enumeration attributes = style.getAttributeNames();
Enumeration<?> attributes = style.getAttributeNames();
if (attributes != null) {
while (attributes.hasMoreElements()) {
Object attribute = attributes.nextElement();
@ -1032,7 +1034,7 @@ public class HTMLWriter extends AbstractWriter {
if (from == null) {
return;
}
Enumeration keys = from.getAttributeNames();
Enumeration<?> keys = from.getAttributeNames();
String value = "";
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
@ -1139,7 +1141,7 @@ public class HTMLWriter extends AbstractWriter {
* attribute.
*/
private static void convertToHTML40(AttributeSet from, MutableAttributeSet to) {
Enumeration keys = from.getAttributeNames();
Enumeration<?> keys = from.getAttributeNames();
String value = "";
while (keys.hasMoreElements()) {
Object key = keys.nextElement();

View File

@ -691,10 +691,11 @@ public class ImageView extends View {
URL src = getImageURL();
Image newImage = null;
if (src != null) {
Dictionary cache = (Dictionary)getDocument().
getProperty(IMAGE_CACHE_PROPERTY);
@SuppressWarnings("unchecked")
Dictionary<URL, Image> cache = (Dictionary)getDocument().
getProperty(IMAGE_CACHE_PROPERTY);
if (cache != null) {
newImage = (Image)cache.get(src);
newImage = cache.get(src);
}
else {
newImage = Toolkit.getDefaultToolkit().createImage(src);

View File

@ -155,7 +155,7 @@ public class MinimalHTMLWriter extends AbstractWriter {
* @exception IOException on any I/O error
*/
protected void writeAttributes(AttributeSet attr) throws IOException {
Enumeration attributeNames = attr.getAttributeNames();
Enumeration<?> attributeNames = attr.getAttributeNames();
while (attributeNames.hasMoreElements()) {
Object name = attributeNames.nextElement();
if ((name instanceof StyleConstants.ParagraphConstants) ||
@ -255,7 +255,7 @@ public class MinimalHTMLWriter extends AbstractWriter {
* stylenames.
*/
DefaultStyledDocument styledDoc = ((DefaultStyledDocument)getDocument());
Enumeration styleNames = styledDoc.getStyleNames();
Enumeration<?> styleNames = styledDoc.getStyleNames();
while (styleNames.hasMoreElements()) {
Style s = styledDoc.getStyle((String)styleNames.nextElement());

View File

@ -213,7 +213,7 @@ class MuxingAttributeSet implements AttributeSet, Serializable {
* @return the attribute names
* @see AttributeSet#getAttributeNames
*/
public Enumeration getAttributeNames() {
public Enumeration<?> getAttributeNames() {
return new MuxingAttributeNameEnumeration();
}
@ -240,7 +240,7 @@ class MuxingAttributeSet implements AttributeSet, Serializable {
public boolean containsAttributes(AttributeSet attrs) {
boolean result = true;
Enumeration names = attrs.getAttributeNames();
Enumeration<?> names = attrs.getAttributeNames();
while (result && names.hasMoreElements()) {
Object name = names.nextElement();
result = attrs.getAttribute(name).equals(getAttribute(name));
@ -268,7 +268,7 @@ class MuxingAttributeSet implements AttributeSet, Serializable {
* An Enumeration of the Attribute names in a MuxingAttributeSet.
* This may return the same name more than once.
*/
private class MuxingAttributeNameEnumeration implements Enumeration {
private class MuxingAttributeNameEnumeration implements Enumeration<Object> {
MuxingAttributeNameEnumeration() {
updateEnum();
@ -307,6 +307,6 @@ class MuxingAttributeSet implements AttributeSet, Serializable {
/** Index into attrs the current Enumeration came from. */
private int attrIndex;
/** Enumeration from attrs. */
private Enumeration currentEnum;
private Enumeration<?> currentEnum;
}
}

View File

@ -91,8 +91,8 @@ public class ObjectView extends ComponentView {
String classname = (String) attr.getAttribute(HTML.Attribute.CLASSID);
try {
ReflectUtil.checkPackageAccess(classname);
Class c = Class.forName(classname, true,Thread.currentThread().
getContextClassLoader());
Class<?> c = Class.forName(classname, true,Thread.currentThread().
getContextClassLoader());
Object o = c.newInstance();
if (o instanceof Component) {
Component comp = (Component) o;
@ -125,7 +125,7 @@ public class ObjectView extends ComponentView {
* &lt;object&gt; element.
*/
private void setParameters(Component comp, AttributeSet attr) {
Class k = comp.getClass();
Class<?> k = comp.getClass();
BeanInfo bi;
try {
bi = Introspector.getBeanInfo(k);
@ -145,7 +145,7 @@ public class ObjectView extends ComponentView {
// read-only property. ignore
return; // for now
}
Class[] params = writer.getParameterTypes();
Class<?>[] params = writer.getParameterTypes();
if (params.length != 1) {
// zero or more than one argument, ignore
return; // for now

View File

@ -40,7 +40,7 @@ import java.io.Serializable;
* It also stores the initial state of the JList, to ensure an
* accurate reset, if the user requests a reset of the form.
*
@author Sunita Mani
* @author Sunita Mani
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
class OptionListModel<E> extends DefaultListModel<E> implements ListSelectionModel, Serializable {
@ -469,7 +469,8 @@ class OptionListModel<E> extends DefaultListModel<E> implements ListSelectionMod
* and (b) define a <code>clone</code> method
*/
public Object clone() throws CloneNotSupportedException {
OptionListModel clone = (OptionListModel)super.clone();
@SuppressWarnings("unchecked")
OptionListModel<E> clone = (OptionListModel)super.clone();
clone.value = (BitSet)value.clone();
clone.listenerList = new EventListenerList();
return clone;

View File

@ -192,6 +192,7 @@ public class StyleSheet extends StyleContext {
try {
// Build an array of all the parent elements.
@SuppressWarnings("unchecked")
Vector<Element> searchContext = sb.getVector();
for (Element p = e; p != null; p = p.getParentElement()) {
@ -693,7 +694,7 @@ public class StyleSheet extends StyleContext {
private AttributeSet removeHTMLTags(AttributeSet old, AttributeSet attr) {
if (!(attr instanceof LargeConversionSet) &&
!(attr instanceof SmallConversionSet)) {
Enumeration names = attr.getAttributeNames();
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object key = names.nextElement();
@ -726,14 +727,14 @@ public class StyleSheet extends StyleContext {
// in most cases, there are no StyleConstants attributes
// so we iterate the collection of keys to avoid creating
// a new set.
Enumeration names = a.getAttributeNames();
Enumeration<?> names = a.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
if (name instanceof StyleConstants) {
// we really need to do a conversion, iterate again
// building a new set.
MutableAttributeSet converted = new LargeConversionSet();
Enumeration keys = a.getAttributeNames();
Enumeration<?> keys = a.getAttributeNames();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object cssValue = null;
@ -1078,6 +1079,7 @@ public class StyleSheet extends StyleContext {
String[] getSimpleSelectors(String selector) {
selector = cleanSelectorString(selector);
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
@SuppressWarnings("unchecked")
Vector<String> selectors = sb.getVector();
int lastIndex = 0;
int length = selector.length();
@ -1256,7 +1258,7 @@ public class StyleSheet extends StyleContext {
* create the resolved style, if necessary.
*/
private synchronized Style getResolvedStyle(String selector,
Vector elements,
Vector<Element> elements,
HTML.Tag t) {
Style retStyle = resolvedStyles.get(selector);
if (retStyle == null) {
@ -1368,7 +1370,9 @@ public class StyleSheet extends StyleContext {
String[] tags,
String[] ids, String[] classes) {
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
@SuppressWarnings("unchecked")
Vector<SelectorMapping> tempVector = sb.getVector();
@SuppressWarnings("unchecked")
Hashtable<SelectorMapping, SelectorMapping> tempHashtable = sb.getHashtable();
// Determine all the Styles that are appropriate, placing them
// in tempVector
@ -1452,7 +1456,7 @@ public class StyleSheet extends StyleContext {
* @param t the Tag to use for
* the first Element in <code>elements</code>
*/
private Style createResolvedStyle(String selector, Vector elements,
private Style createResolvedStyle(String selector, Vector<Element> elements,
HTML.Tag t) {
int numElements = elements.size();
// Build three arrays, one for tags, one for class's, and one for
@ -1461,7 +1465,7 @@ public class StyleSheet extends StyleContext {
String ids[] = new String[numElements];
String classes[] = new String[numElements];
for (int counter = 0; counter < numElements; counter++) {
Element e = (Element)elements.elementAt(counter);
Element e = elements.elementAt(counter);
AttributeSet attr = e.getAttributes();
if (counter == 0 && e.isLeaf()) {
// For leafs, we use the second tier attributes.
@ -1513,6 +1517,7 @@ public class StyleSheet extends StyleContext {
private Style createResolvedStyle(String selector) {
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
// Will contain the tags, ids, and classes, in that order.
@SuppressWarnings("unchecked")
Vector<String> elements = sb.getVector();
try {
boolean done;
@ -1678,6 +1683,7 @@ public class StyleSheet extends StyleContext {
* releaseSearchBuffer to get a SearchBuffer, and release it when
* done.
*/
@SuppressWarnings("rawtypes")
private static class SearchBuffer {
/** A stack containing instances of SearchBuffer. Used in getting
* rules. */
@ -2630,6 +2636,7 @@ public class StyleSheet extends StyleContext {
// implementation.
Document doc = v.getDocument();
SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
@SuppressWarnings("unchecked")
Vector<AttributeSet> muxList = sb.getVector();
try {
if (doc instanceof HTMLDocument) {
@ -2642,7 +2649,7 @@ public class StyleSheet extends StyleContext {
muxList.addElement(htmlAttr);
}
if (elem.isLeaf()) {
Enumeration keys = a.getAttributeNames();
Enumeration<?> keys = a.getAttributeNames();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof HTML.Tag) {

View File

@ -370,6 +370,7 @@ class DTD implements DTDConstants {
private static Hashtable<String, DTD> getDtdHash() {
AppContext appContext = AppContext.getAppContext();
@SuppressWarnings("unchecked")
Hashtable<String, DTD> result = (Hashtable<String, DTD>) appContext.get(DTD_HASH_KEY);
if (result == null) {

View File

@ -74,7 +74,7 @@ class MockAttributeSet
public void addAttributes(AttributeSet attr)
{
Enumeration as = attr.getAttributeNames();
Enumeration<?> as = attr.getAttributeNames();
while(as.hasMoreElements()) {
Object el = as.nextElement();
backing.put(el, attr.getAttribute(el));
@ -102,7 +102,7 @@ class MockAttributeSet
}
public Enumeration getAttributeNames()
public Enumeration<?> getAttributeNames()
{
return backing.keys();
}

View File

@ -96,13 +96,13 @@ class RTFGenerator extends Object
static {
MagicToken = new Object();
Dictionary textKeywordDictionary = RTFReader.textKeywords;
Enumeration keys = textKeywordDictionary.keys();
Dictionary<String, String> textKeywordDictionary = RTFReader.textKeywords;
Enumeration<String> keys = textKeywordDictionary.keys();
Vector<CharacterKeywordPair> tempPairs = new Vector<CharacterKeywordPair>();
while(keys.hasMoreElements()) {
CharacterKeywordPair pair = new CharacterKeywordPair();
pair.keyword = (String)keys.nextElement();
pair.character = ((String)textKeywordDictionary.get(pair.keyword)).charAt(0);
pair.keyword = keys.nextElement();
pair.character = textKeywordDictionary.get(pair.keyword).charAt(0);
tempPairs.addElement(pair);
}
textKeywords = new CharacterKeywordPair[tempPairs.size()];
@ -340,7 +340,7 @@ public void writeRTFHeader()
/* write color table */
if (colorCount > 1) {
Color[] sortedColorTable = new Color[colorCount];
Enumeration colors = colorTable.keys();
Enumeration<Object> colors = colorTable.keys();
Color color;
while(colors.hasMoreElements()) {
color = (Color)colors.nextElement();

View File

@ -220,6 +220,7 @@ public void begingroup()
Object oldSaveState = parserState.get("_savedState");
if (oldSaveState != null)
parserState.remove("_savedState");
@SuppressWarnings("unchecked")
Dictionary<String, Object> saveState = (Dictionary<String, Object>)((Hashtable)parserState).clone();
if (oldSaveState != null)
saveState.put("_savedState", oldSaveState);
@ -242,13 +243,14 @@ public void endgroup()
skippingCharacters = 0;
}
@SuppressWarnings("unchecked")
Dictionary<Object, Object> restoredState = (Dictionary<Object, Object>)parserState.get("_savedState");
Destination restoredDestination = (Destination)restoredState.get("dst");
if (restoredDestination != rtfDestination) {
rtfDestination.close(); /* allow the destination to clean up */
rtfDestination = restoredDestination;
}
Dictionary oldParserState = parserState;
Dictionary<Object, Object> oldParserState = parserState;
parserState = restoredState;
if (rtfDestination != null)
rtfDestination.endgroup(oldParserState);
@ -258,7 +260,8 @@ protected void setRTFDestination(Destination newDestination)
{
/* Check that setting the destination won't close the
current destination (should never happen) */
Dictionary previousState = (Dictionary)parserState.get("_savedState");
@SuppressWarnings("unchecked")
Dictionary<Object, Object> previousState = (Dictionary)parserState.get("_savedState");
if (previousState != null) {
if (rtfDestination != previousState.get("dst")) {
warning("Warning, RTF destination overridden, invalid RTF.");
@ -277,7 +280,7 @@ protected void setRTFDestination(Destination newDestination)
public void close()
throws IOException
{
Enumeration docProps = documentAttributes.getAttributeNames();
Enumeration<?> docProps = documentAttributes.getAttributeNames();
while(docProps.hasMoreElements()) {
Object propName = docProps.nextElement();
target.putProperty(propName,
@ -628,7 +631,7 @@ interface Destination {
boolean handleKeyword(String keyword, int parameter);
void begingroup();
void endgroup(Dictionary oldState);
void endgroup(Dictionary<Object, Object> oldState);
void close();
}
@ -666,7 +669,7 @@ class DiscardingDestination implements Destination
current group level as necessary */
}
public void endgroup(Dictionary oldState)
public void endgroup(Dictionary<Object, Object> oldState)
{
/* Ignore groups */
}
@ -736,7 +739,7 @@ class FonttblDestination implements Destination
/* Groups are irrelevant. */
public void begingroup() {}
public void endgroup(Dictionary oldState) {}
public void endgroup(Dictionary<Object, Object> oldState) {}
/* currently, the only thing we do when the font table ends is
dump its contents to the debugging log. */
@ -806,7 +809,7 @@ class ColortblDestination implements Destination
/* Groups are irrelevant. */
public void begingroup() {}
public void endgroup(Dictionary oldState) {}
public void endgroup(Dictionary<Object, Object> oldState) {}
/* Shouldn't see any binary blobs ... */
public void handleBinaryBlob(byte[] data) {}
@ -1098,7 +1101,7 @@ abstract class AttributeTrackingDestination implements Destination
parserState.put("sec", sectionAttributes);
}
public void endgroup(Dictionary oldState)
public void endgroup(Dictionary<Object, Object> oldState)
{
characterAttributes = (MutableAttributeSet)parserState.get("chr");
paragraphAttributes = (MutableAttributeSet)parserState.get("pgf");
@ -1262,7 +1265,9 @@ abstract class AttributeTrackingDestination implements Destination
Dictionary<Object, Object> tabs;
Integer stopCount;
tabs = (Dictionary<Object, Object>)parserState.get("_tabs");
@SuppressWarnings("unchecked")
Dictionary<Object, Object>tmp = (Dictionary)parserState.get("_tabs");
tabs = tmp;
if (tabs == null) {
tabs = new Hashtable<Object, Object>();
parserState.put("_tabs", tabs);
@ -1420,7 +1425,8 @@ abstract class AttributeTrackingDestination implements Destination
tabs = (TabStop[])parserState.get("_tabs_immutable");
if (tabs == null) {
Dictionary workingTabs = (Dictionary)parserState.get("_tabs");
@SuppressWarnings("unchecked")
Dictionary<Object, Object> workingTabs = (Dictionary)parserState.get("_tabs");
if (workingTabs != null) {
int count = ((Integer)workingTabs.get("stop count")).intValue();
tabs = new TabStop[count];

View File

@ -31,6 +31,7 @@ import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuBar;
import java.awt.MenuComponent;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.peer.FramePeer;
@ -124,4 +125,48 @@ public abstract class LightweightFrame extends Frame {
* @see SunToolkit#ungrab(java.awt.Window)
*/
public abstract void ungrabFocus();
/**
* Returns the scale factor of this frame. The default value is 1.
*
* @return the scale factor
* @see #notifyDisplayChanged(int)
*/
public abstract int getScaleFactor();
/**
* Called when display of the hosted frame is changed.
*
* @param scaleFactor the scale factor
*/
public abstract void notifyDisplayChanged(int scaleFactor);
/**
* Host window absolute bounds.
*/
private int hostX, hostY, hostW, hostH;
/**
* Returns the absolute bounds of the host (embedding) window.
*
* @return the host window bounds
*/
public Rectangle getHostBounds() {
if (hostX == 0 && hostY == 0 && hostW == 0 && hostH == 0) {
// The client app is probably unaware of the setHostBounds.
// A safe fall-back:
return getBounds();
}
return new Rectangle(hostX, hostY, hostW, hostH);
}
/**
* Sets the absolute bounds of the host (embedding) window.
*/
public void setHostBounds(int x, int y, int w, int h) {
hostX = x;
hostY = y;
hostW = w;
hostH = h;
}
}

View File

@ -2108,7 +2108,7 @@ public final class SunGraphics2D
if (theData.copyArea(this, x, y, w, h, dx, dy)) {
return;
}
if (transformState >= TRANSFORM_TRANSLATESCALE) {
if (transformState > TRANSFORM_TRANSLATESCALE) {
throw new InternalError("transformed copyArea not implemented yet");
}
// REMIND: This method does not deal with missing data from the
@ -2129,8 +2129,25 @@ public final class SunGraphics2D
lastCAcomp = comp;
}
x += transX;
y += transY;
double[] coords = {x, y, x + w, y + h, x + dx, y + dy};
transform.transform(coords, 0, coords, 0, 3);
x = (int)Math.ceil(coords[0] - 0.5);
y = (int)Math.ceil(coords[1] - 0.5);
w = ((int)Math.ceil(coords[2] - 0.5)) - x;
h = ((int)Math.ceil(coords[3] - 0.5)) - y;
dx = ((int)Math.ceil(coords[4] - 0.5)) - x;
dy = ((int)Math.ceil(coords[5] - 0.5)) - y;
// In case of negative scale transform, reflect the rect coords.
if (w < 0) {
w *= -1;
x -= w;
}
if (h < 0) {
h *= -1;
y -= h;
}
Blit ob = lastCAblit;
if (dy == 0 && dx > 0 && dx < w) {

View File

@ -510,6 +510,7 @@ class OGLRTTSurfaceToSurfaceTransform extends TransformBlit {
final class OGLSurfaceToSwBlit extends Blit {
private final int typeval;
private WeakReference<SurfaceData> srcTmp;
// destination will actually be ArgbPre or Argb
OGLSurfaceToSwBlit(final SurfaceType dstType,final int typeval) {
@ -519,11 +520,66 @@ final class OGLSurfaceToSwBlit extends Blit {
this.typeval = typeval;
}
private synchronized void complexClipBlit(SurfaceData src, SurfaceData dst,
Composite comp, Region clip,
int sx, int sy, int dx, int dy,
int w, int h) {
SurfaceData cachedSrc = null;
if (srcTmp != null) {
// use cached intermediate surface, if available
cachedSrc = srcTmp.get();
}
// We can convert argb_pre data from OpenGL surface in two places:
// - During OpenGL surface -> SW blit
// - During SW -> SW blit
// The first one is faster when we use opaque OGL surface, because in
// this case we simply skip conversion and use color components as is.
// Because of this we align intermediate buffer type with type of
// destination not source.
final int type = typeval == OGLSurfaceData.PF_INT_ARGB_PRE ?
BufferedImage.TYPE_INT_ARGB_PRE :
BufferedImage.TYPE_INT_ARGB;
src = convertFrom(this, src, sx, sy, w, h, cachedSrc, type);
// copy intermediate SW to destination SW using complex clip
final Blit performop = Blit.getFromCache(src.getSurfaceType(),
CompositeType.SrcNoEa,
dst.getSurfaceType());
performop.Blit(src, dst, comp, clip, 0, 0, dx, dy, w, h);
if (src != cachedSrc) {
// cache the intermediate surface
srcTmp = new WeakReference<>(src);
}
}
public void Blit(SurfaceData src, SurfaceData dst,
Composite comp, Region clip,
int sx, int sy, int dx, int dy,
int w, int h)
{
if (clip != null) {
clip = clip.getIntersectionXYWH(dx, dy, w, h);
// At the end this method will flush the RenderQueue, we should exit
// from it as soon as possible.
if (clip.isEmpty()) {
return;
}
sx += clip.getLoX() - dx;
sy += clip.getLoY() - dy;
dx = clip.getLoX();
dy = clip.getLoY();
w = clip.getWidth();
h = clip.getHeight();
if (!clip.isRectangular()) {
complexClipBlit(src, dst, comp, clip, sx, sy, dx, dy, w, h);
return;
}
}
OGLRenderQueue rq = OGLRenderQueue.getInstance();
rq.lock();
try {

View File

@ -54,6 +54,7 @@ import javax.swing.RepaintManager;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import sun.awt.DisplayChangedListener;
import sun.awt.LightweightFrame;
import sun.security.action.GetPropertyAction;
import sun.swing.SwingUtilities2.RepaintListener;
@ -80,6 +81,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
private BufferedImage bbImage;
private volatile int scaleFactor = 1;
/**
* {@code copyBufferEnabled}, true by default, defines the following strategy.
* A duplicating (copy) buffer is created for the original pixel buffer.
@ -90,7 +93,7 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
* by the lock (managed with the {@link LightweightContent#paintLock()},
* {@link LightweightContent#paintUnlock()} methods).
*/
private boolean copyBufferEnabled;
private static boolean copyBufferEnabled;
private int[] copyBuffer;
private PropertyChangeListener layoutSizeListener;
@ -103,6 +106,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
frame.updateClientCursor();
}
});
copyBufferEnabled = "true".equals(AccessController.
doPrivileged(new GetPropertyAction("swing.jlf.copyBufferEnabled", "true")));
}
/**
@ -144,7 +149,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
}
Point p = SwingUtilities.convertPoint(c, x, y, jlf);
Rectangle r = new Rectangle(p.x, p.y, w, h).intersection(
new Rectangle(0, 0, bbImage.getWidth(), bbImage.getHeight()));
new Rectangle(0, 0, bbImage.getWidth() / scaleFactor,
bbImage.getHeight() / scaleFactor));
if (!r.isEmpty()) {
notifyImageUpdated(r.x, r.y, r.width, r.height);
@ -198,6 +204,7 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
g.setBackground(getBackground());
g.setColor(getForeground());
g.setFont(getFont());
g.scale(scaleFactor, scaleFactor);
return g;
}
@ -221,7 +228,39 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
if (content != null) content.focusUngrabbed();
}
private void syncCopyBuffer(boolean reset, int x, int y, int w, int h) {
@Override
public int getScaleFactor() {
return scaleFactor;
}
@Override
public void notifyDisplayChanged(final int scaleFactor) {
if (scaleFactor != this.scaleFactor) {
if (!copyBufferEnabled) content.paintLock();
try {
if (bbImage != null) {
resizeBuffer(getWidth(), getHeight(), scaleFactor);
}
} finally {
if (!copyBufferEnabled) content.paintUnlock();
}
this.scaleFactor = scaleFactor;
}
if (getPeer() instanceof DisplayChangedListener) {
((DisplayChangedListener)getPeer()).displayChanged();
}
repaint();
}
@Override
public void addNotify() {
super.addNotify();
if (getPeer() instanceof DisplayChangedListener) {
((DisplayChangedListener)getPeer()).displayChanged();
}
}
private void syncCopyBuffer(boolean reset, int x, int y, int w, int h, int scale) {
content.paintLock();
try {
int[] srcBuffer = ((DataBufferInt)bbImage.getRaster().getDataBuffer()).getData();
@ -230,6 +269,11 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
}
int linestride = bbImage.getWidth();
x *= scale;
y *= scale;
w *= scale;
h *= scale;
for (int i=0; i<h; i++) {
int from = (y + i) * linestride + x;
System.arraycopy(srcBuffer, from, copyBuffer, from, w);
@ -241,7 +285,7 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
private void notifyImageUpdated(int x, int y, int width, int height) {
if (copyBufferEnabled) {
syncCopyBuffer(false, x, y, width, height);
syncCopyBuffer(false, x, y, width, height, scaleFactor);
}
content.imageUpdated(x, y, width, height);
}
@ -269,7 +313,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
notifyImageUpdated(clip.x, clip.y, clip.width, clip.height);
Rectangle c = contentPane.getBounds().intersection(clip);
notifyImageUpdated(c.x, c.y, c.width, c.height);
}
});
} finally {
@ -323,48 +368,37 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
content.paintLock();
}
try {
if ((bbImage == null) || (width != bbImage.getWidth()) || (height != bbImage.getHeight())) {
boolean createBB = true;
int newW = width;
int newH = height;
if (bbImage != null) {
int oldW = bbImage.getWidth();
int oldH = bbImage.getHeight();
if ((oldW >= newW) && (oldH >= newH)) {
createBB = false;
} else {
if (oldW >= newW) {
newW = oldW;
boolean createBB = (bbImage == null);
int newW = width;
int newH = height;
if (bbImage != null) {
int imgWidth = bbImage.getWidth() / scaleFactor;
int imgHeight = bbImage.getHeight() / scaleFactor;
if (width != imgWidth || height != imgHeight) {
createBB = true;
if (bbImage != null) {
int oldW = imgWidth;
int oldH = imgHeight;
if ((oldW >= newW) && (oldH >= newH)) {
createBB = false;
} else {
newW = Math.max((int)(oldW * 1.2), width);
}
if (oldH >= newH) {
newH = oldH;
} else {
newH = Math.max((int)(oldH * 1.2), height);
if (oldW >= newW) {
newW = oldW;
} else {
newW = Math.max((int)(oldW * 1.2), width);
}
if (oldH >= newH) {
newH = oldH;
} else {
newH = Math.max((int)(oldH * 1.2), height);
}
}
}
}
if (createBB) {
BufferedImage oldBB = bbImage;
bbImage = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB_PRE);
if (oldBB != null) {
Graphics g = bbImage.getGraphics();
try {
g.drawImage(oldBB, 0, 0, newW, newH, null);
} finally {
g.dispose();
oldBB.flush();
}
}
int[] pixels = ((DataBufferInt)bbImage.getRaster().getDataBuffer()).getData();
if (copyBufferEnabled) {
syncCopyBuffer(true, 0, 0, width, height);
pixels = copyBuffer;
}
content.imageBufferReset(pixels, 0, 0, width, height, bbImage.getWidth());
return;
}
}
if (createBB) {
resizeBuffer(newW, newH, scaleFactor);
return;
}
content.imageReshaped(0, 0, width, height);
@ -375,6 +409,18 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan
}
}
private void resizeBuffer(int width, int height, int newScaleFactor) {
bbImage = new BufferedImage(width*newScaleFactor,height*newScaleFactor,
BufferedImage.TYPE_INT_ARGB_PRE);
int[] pixels= ((DataBufferInt)bbImage.getRaster().getDataBuffer()).getData();
if (copyBufferEnabled) {
syncCopyBuffer(true, 0, 0, width, height, newScaleFactor);
pixels = copyBuffer;
}
content.imageBufferReset(pixels, 0, 0, width, height,
width * newScaleFactor, newScaleFactor);
}
@Override
public JRootPane getRootPane() {
return rootPane;

View File

@ -85,31 +85,53 @@ public interface LightweightContent {
* {@code JLightweightFrame} calls this method to notify the client
* application that a new data buffer has been set as a content pixel
* buffer. Typically this occurs when a buffer of a larger size is
* created in response to a content resize event. The method reports
* a reference to the pixel data buffer, the content image bounds
* within the buffer and the line stride of the buffer. These values
* have the following correlation.
* created in response to a content resize event.
* <p>
* The {@code width} and {@code height} matches the size of the content
* The method reports a reference to the pixel data buffer, the content
* image bounds within the buffer and the line stride of the buffer.
* These values have the following correlation.
* The {@code width} and {@code height} matches the layout size of the content
* (the component returned from the {@link #getComponent} method). The
* {@code x} and {@code y} is the origin of the content, {@code (0, 0)}
* in the coordinate space of the content, appearing at
* {@code data[y * linestride + x]} in the buffer. All indices
* {@code data[(y + j) * linestride + (x + i)]} where
* {@code (0 <= i < width)} and {@code (0 <= j < height)} will represent
* valid pixel data, {@code (i, j)} in the coordinate space of the content.
* in the layout coordinate space of the content, appearing at
* {@code data[y * scale * linestride + x * scale]} in the buffer.
* A pixel with indices {@code (i, j)}, where {@code (0 <= i < width)} and
* {@code (0 <= j < height)}, in the layout coordinate space of the content
* is represented by a {@code scale^2} square of pixels in the physical
* coordinate space of the buffer. The top-left corner of the square has the
* following physical coordinate in the buffer:
* {@code data[(y + j) * scale * linestride + (x + i) * scale]}.
*
* @param data the content pixel data buffer of INT_ARGB_PRE type
* @param x the x coordinate of the image
* @param y the y coordinate of the image
* @param width the width of the image
* @param height the height of the image
* @param x the logical x coordinate of the image
* @param y the logical y coordinate of the image
* @param width the logical width of the image
* @param height the logical height of the image
* @param linestride the line stride of the pixel buffer
* @param scale the scale factor of the pixel buffer
*/
public void imageBufferReset(int[] data,
default public void imageBufferReset(int[] data,
int x, int y,
int width, int height,
int linestride);
int linestride,
int scale)
{
imageBufferReset(data, x, y, width, height, linestride);
}
/**
* The default implementation for #imageBufferReset uses a hard-coded value
* of 1 for the scale factor. Both the old and the new methods provide
* default implementations in order to allow a client application to run
* with any JDK version without breaking backward compatibility.
*/
default public void imageBufferReset(int[] data,
int x, int y,
int width, int height,
int linestride)
{
imageBufferReset(data, x, y, width, height, linestride, 1);
}
/**
* {@code JLightweightFrame} calls this method to notify the client

View File

@ -783,6 +783,8 @@ gboolean gtk2_load(JNIEnv *env)
fp_gtk_widget_show = dl_symbol("gtk_widget_show");
fp_gtk_main = dl_symbol("gtk_main");
fp_g_path_get_dirname = dl_symbol("g_path_get_dirname");
/**
* GLib thread system
*/

View File

@ -817,7 +817,7 @@ gulong (*fp_g_signal_connect_data)(gpointer instance,
void (*fp_gtk_widget_show)(GtkWidget *widget);
void (*fp_gtk_main)(void);
guint (*fp_gtk_main_level)(void);
gchar* (*fp_g_path_get_dirname) (const gchar *file_name);
/**
* This function is available for GLIB > 2.20, so it MUST be

View File

@ -59,7 +59,6 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs
static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gpointer obj)
{
JNIEnv *env;
jclass cx;
jstring filename;
env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2);
@ -158,62 +157,55 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_setBounds
fp_gdk_threads_leave();
}
/**
* Convert a GSList to an array of filenames (without the parent folder)
/*
* baseDir should be freed by user.
*/
static jobjectArray toFilenamesArray(JNIEnv *env, GSList* list)
{
jstring str;
jclass stringCls;
GSList *iterator;
jobjectArray array;
int i;
char* entry;
static gboolean isFromSameDirectory(GSList* list, gchar** baseDir) {
if (NULL == list) {
return NULL;
}
GSList *it = list;
gchar* prevDir = NULL;
gboolean isAllDirsSame = TRUE;
stringCls = (*env)->FindClass(env, "java/lang/String");
if (stringCls == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not get java.lang.String class");
return NULL;
}
while (it) {
gchar* dir = fp_g_path_get_dirname((gchar*) it->data);
array = (*env)->NewObjectArray(env, fp_gtk_g_slist_length(list), stringCls, NULL);
if (array == NULL) {
(*env)->ExceptionClear(env);
JNU_ThrowInternalError(env, "Could not instantiate array files array");
return NULL;
}
i = 0;
for (iterator = list; iterator; iterator = iterator->next) {
entry = (char*) iterator->data;
entry = strrchr(entry, '/') + 1;
str = (*env)->NewStringUTF(env, entry);
if (str && !(*env)->ExceptionCheck(env)) {
(*env)->SetObjectArrayElement(env, array, i, str);
if (prevDir && strcmp(prevDir, dir) != 0) {
isAllDirsSame = FALSE;
fp_g_free(dir);
break;
}
i++;
if (!prevDir) {
prevDir = strdup(dir);
}
fp_g_free(dir);
it = it->next;
}
return array;
if (isAllDirsSame) {
*baseDir = prevDir;
} else {
free(prevDir);
*baseDir = strdup("/");
}
return isAllDirsSame;
}
/**
* Convert a GSList to an array of filenames (with the parent folder)
* Convert a GSList to an array of filenames
*/
static jobjectArray toPathAndFilenamesArray(JNIEnv *env, GSList* list)
static jobjectArray toFilenamesArray(JNIEnv *env, GSList* list, jstring* jcurrent_folder)
{
jstring str;
jclass stringCls;
GSList *iterator;
jobjectArray array;
int i;
char* entry;
gchar* entry;
gchar * baseDir;
gboolean isFromSameDir;
if (list == NULL) {
return NULL;
@ -233,12 +225,23 @@ static jobjectArray toPathAndFilenamesArray(JNIEnv *env, GSList* list)
return NULL;
}
i = 0;
for (iterator = list; iterator; iterator = iterator->next) {
entry = (char*) iterator->data;
isFromSameDir = isFromSameDirectory(list, &baseDir);
//check for leading slash.
if (entry[0] == '/') {
*jcurrent_folder = (*env)->NewStringUTF(env, baseDir);
if (*jcurrent_folder == NULL) {
free(baseDir);
return NULL;
}
for (iterator = list, i=0;
iterator;
iterator = iterator->next, i++) {
entry = (gchar*) iterator->data;
if (isFromSameDir) {
entry = strrchr(entry, '/') + 1;
} else if (entry[0] == '/') {
entry++;
}
@ -246,48 +249,33 @@ static jobjectArray toPathAndFilenamesArray(JNIEnv *env, GSList* list)
if (str && !(*env)->ExceptionCheck(env)) {
(*env)->SetObjectArrayElement(env, array, i, str);
}
i++;
}
free(baseDir);
return array;
}
static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj)
{
JNIEnv *env;
char *current_folder;
GSList *filenames;
jclass cx;
jstring jcurrent_folder;
jstring jcurrent_folder = NULL;
jobjectArray jfilenames;
env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2);
current_folder = NULL;
filenames = NULL;
gboolean full_path_names = FALSE;
if (responseId == GTK_RESPONSE_ACCEPT) {
current_folder = fp_gtk_file_chooser_get_current_folder(
GTK_FILE_CHOOSER(aDialog));
if (current_folder == NULL) {
full_path_names = TRUE;
}
filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(aDialog));
}
if (full_path_names) {
//This is a hack for use with "Recent Folders" in gtk where each
//file could have its own directory.
jfilenames = toPathAndFilenamesArray(env, filenames);
jcurrent_folder = (*env)->NewStringUTF(env, "/");
} else {
jfilenames = toFilenamesArray(env, filenames);
jcurrent_folder = (*env)->NewStringUTF(env, current_folder);
}
jfilenames = toFilenamesArray(env, filenames, &jcurrent_folder);
if (!(*env)->ExceptionCheck(env)) {
(*env)->CallVoidMethod(env, obj, setFileInternalMethodID,
jcurrent_folder, jfilenames);
}
fp_g_free(current_folder);
quit(env, (jobject)obj, TRUE);
}

View File

@ -42,8 +42,6 @@ import sun.awt.windows.WFontConfiguration;
import sun.font.FontManager;
import sun.font.SunFontManager;
import sun.font.TrueTypeFont;
import sun.java2d.HeadlessGraphicsEnvironment;
import sun.java2d.SunGraphicsEnvironment;
/**
* The X11 implementation of {@link FontManager}.
@ -56,7 +54,7 @@ public class Win32FontManager extends SunFontManager {
static {
AccessController.doPrivileged(new PrivilegedAction() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
String eudcFile = getEUDCFontFile();
@ -90,7 +88,7 @@ public class Win32FontManager extends SunFontManager {
public Win32FontManager() {
super();
AccessController.doPrivileged(new PrivilegedAction() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
/* Register the JRE fonts so that the native platform can
@ -227,7 +225,7 @@ public class Win32FontManager extends SunFontManager {
final String[] dirs = getPlatformFontDirs(true);
if (dirs.length > 1) {
String dir = (String)
AccessController.doPrivileged(new PrivilegedAction() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
for (int i=0; i<dirs.length; i++) {
String path =
@ -272,7 +270,7 @@ public class Win32FontManager extends SunFontManager {
fontsForPrinting = null;
}
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
new java.security.PrivilegedAction<Object>() {
public Object run() {
File f1 = new File(pathName);
String[] ls = f1.list(SunFontManager.getInstance().

View File

@ -172,7 +172,7 @@ public class Win32GraphicsDevice extends GraphicsDevice implements
int max = getMaxConfigs(screen);
int defaultPixID = getDefaultPixID(screen);
Vector v = new Vector( max );
Vector<GraphicsConfiguration> v = new Vector<>( max );
if (defaultPixID == 0) {
// Workaround for failing GDI calls
defaultConfig = Win32GraphicsConfig.getConfig(this,
@ -437,7 +437,7 @@ public class Win32GraphicsDevice extends GraphicsDevice implements
protected native void configDisplayMode(int screen, WindowPeer w, int width,
int height, int bitDepth,
int refreshRate);
protected native void enumDisplayModes(int screen, ArrayList modes);
protected native void enumDisplayModes(int screen, ArrayList<DisplayMode> modes);
@Override
public synchronized DisplayMode getDisplayMode() {
@ -447,12 +447,12 @@ public class Win32GraphicsDevice extends GraphicsDevice implements
@Override
public synchronized DisplayMode[] getDisplayModes() {
ArrayList modes = new ArrayList();
ArrayList<DisplayMode> modes = new ArrayList<>();
enumDisplayModes(screen, modes);
int listSize = modes.size();
DisplayMode[] retArray = new DisplayMode[listSize];
for (int i = 0; i < listSize; i++) {
retArray[i] = (DisplayMode)modes.get(i);
retArray[i] = modes.get(i);
}
return retArray;
}

View File

@ -894,10 +894,10 @@ final class Win32ShellFolder2 extends ShellFolder {
// Icons
private static Map smallSystemImages = new HashMap();
private static Map largeSystemImages = new HashMap();
private static Map smallLinkedSystemImages = new HashMap();
private static Map largeLinkedSystemImages = new HashMap();
private static Map<Integer, Image> smallSystemImages = new HashMap<>();
private static Map<Integer, Image> largeSystemImages = new HashMap<>();
private static Map<Integer, Image> smallLinkedSystemImages = new HashMap<>();
private static Map<Integer, Image> largeLinkedSystemImages = new HashMap<>();
// NOTE: this method uses COM and must be called on the 'COM thread'. See ComInvoker for the details
private static native long getIShellIcon(long pIShellFolder);
@ -970,13 +970,13 @@ final class Win32ShellFolder2 extends ShellFolder {
// These are cached per type (using the index in the system image list)
int index = getIconIndex(parentIShellIcon, relativePIDL);
if (index > 0) {
Map imageCache;
Map<Integer, Image> imageCache;
if (isLink()) {
imageCache = getLargeIcon ? largeLinkedSystemImages : smallLinkedSystemImages;
} else {
imageCache = getLargeIcon ? largeSystemImages : smallSystemImages;
}
newIcon = (Image) imageCache.get(Integer.valueOf(index));
newIcon = imageCache.get(Integer.valueOf(index));
if (newIcon == null) {
long hIcon = getIcon(getAbsolutePath(), getLargeIcon);
newIcon = makeIcon(hIcon, getLargeIcon);

View File

@ -414,14 +414,14 @@ public class Win32ShellFolderManager2 extends ShellFolderManager {
return false;
}
private static List topFolderList = null;
private static List<Win32ShellFolder2> topFolderList = null;
static int compareShellFolders(Win32ShellFolder2 sf1, Win32ShellFolder2 sf2) {
boolean special1 = sf1.isSpecial();
boolean special2 = sf2.isSpecial();
if (special1 || special2) {
if (topFolderList == null) {
ArrayList tmpTopFolderList = new ArrayList();
ArrayList<Win32ShellFolder2> tmpTopFolderList = new ArrayList<>();
tmpTopFolderList.add(Win32ShellFolderManager2.getPersonal());
tmpTopFolderList.add(Win32ShellFolderManager2.getDesktop());
tmpTopFolderList.add(Win32ShellFolderManager2.getDrives());

View File

@ -29,6 +29,7 @@ import java.awt.Component;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
@ -76,8 +77,9 @@ final class WDragSourceContextPeer extends SunDragSourceContextPeer {
return theInstance;
}
@Override
protected void startDrag(Transferable trans,
long[] formats, Map formatMap) {
long[] formats, Map<Long, DataFlavor> formatMap) {
long nativeCtxtLocal = 0;
@ -153,7 +155,7 @@ final class WDragSourceContextPeer extends SunDragSourceContextPeer {
InputEvent nativeTrigger,
int actions,
long[] formats,
Map formatMap);
Map<Long, DataFlavor> formatMap);
/**
* downcall into native code

View File

@ -53,7 +53,7 @@ public final class WFontConfiguration extends FontConfiguration {
@Override
protected void initReorderMap() {
if (encoding.equalsIgnoreCase("windows-31j")) {
localeMap = new Hashtable();
localeMap = new Hashtable<>();
/* Substitute Mincho for Gothic in this one case.
* Note the windows fontconfig files already contain the mapping:
* filename.MS_Mincho=MSMINCHO.TTC
@ -67,7 +67,7 @@ public final class WFontConfiguration extends FontConfiguration {
localeMap.put("dialoginput.italic.japanese", "MS Mincho");
localeMap.put("dialoginput.bolditalic.japanese", "MS Mincho");
}
reorderMap = new HashMap();
reorderMap = new HashMap<>();
reorderMap.put("UTF-8.hi", "devanagari");
reorderMap.put("windows-1255", "hebrew");
reorderMap.put("x-windows-874", "thai");
@ -118,7 +118,7 @@ public final class WFontConfiguration extends FontConfiguration {
@Override
protected String makeAWTFontName(String platformFontName, String characterSubsetName) {
String windowsCharset = (String) subsetCharsetMap.get(characterSubsetName);
String windowsCharset = subsetCharsetMap.get(characterSubsetName);
if (windowsCharset == null) {
windowsCharset = "DEFAULT_CHARSET";
}
@ -127,7 +127,7 @@ public final class WFontConfiguration extends FontConfiguration {
@Override
protected String getEncoding(String awtFontName, String characterSubsetName) {
String encoding = (String) subsetEncodingMap.get(characterSubsetName);
String encoding = subsetEncodingMap.get(characterSubsetName);
if (encoding == null) {
encoding = "default";
}
@ -174,8 +174,8 @@ public final class WFontConfiguration extends FontConfiguration {
return fontName;
}
private static HashMap subsetCharsetMap = new HashMap();
private static HashMap subsetEncodingMap = new HashMap();
private static HashMap<String, String> subsetCharsetMap = new HashMap<>();
private static HashMap<String, String> subsetEncodingMap = new HashMap<>();
private static String textInputCharset;
private void initTables(String defaultEncoding) {

View File

@ -199,10 +199,10 @@ final class WFontMetrics extends FontMetrics {
native void init();
static Hashtable table = new Hashtable();
static Hashtable<Font, FontMetrics> table = new Hashtable<>();
static FontMetrics getFontMetrics(Font font) {
FontMetrics fm = (FontMetrics)table.get(font);
FontMetrics fm = table.get(font);
if (fm == null) {
table.put(font, fm = new WFontMetrics(font));
}

View File

@ -86,26 +86,27 @@ final class WInputMethod extends InputMethodAdapter
// Initialize highlight mapping table
static {
@SuppressWarnings({"rawtypes", "unchecked"})
Map<TextAttribute,Object> styles[] = new Map[4];
HashMap<TextAttribute,Object> map;
// UNSELECTED_RAW_TEXT_HIGHLIGHT
map = new HashMap(1);
map = new HashMap<>(1);
map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_DOTTED);
styles[0] = Collections.unmodifiableMap(map);
// SELECTED_RAW_TEXT_HIGHLIGHT
map = new HashMap(1);
map = new HashMap<>(1);
map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_GRAY);
styles[1] = Collections.unmodifiableMap(map);
// UNSELECTED_CONVERTED_TEXT_HIGHLIGHT
map = new HashMap(1);
map = new HashMap<>(1);
map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_DOTTED);
styles[2] = Collections.unmodifiableMap(map);
// SELECTED_CONVERTED_TEXT_HIGHLIGHT
map = new HashMap(4);
map = new HashMap<>(4);
Color navyBlue = new Color(0, 0, 128);
map.put(TextAttribute.FOREGROUND, navyBlue);
map.put(TextAttribute.BACKGROUND, Color.white);

View File

@ -843,6 +843,7 @@ public final class WToolkit extends SunToolkit implements Runnable {
}
@Override
@SuppressWarnings("unchecked")
public <T extends DragGestureRecognizer> T
createDragGestureRecognizer(Class<T> abstractRecognizerClass,
DragSource ds, Component c, int srcActions,

View File

@ -717,7 +717,7 @@ class D3DTextureToSurfaceTransform extends TransformBlit {
class D3DGeneralBlit extends Blit {
private Blit performop;
private WeakReference srcTmp;
private WeakReference<SurfaceData> srcTmp;
D3DGeneralBlit(SurfaceType dstType,
CompositeType compType,
@ -739,7 +739,7 @@ class D3DGeneralBlit extends Blit {
SurfaceData cachedSrc = null;
if (srcTmp != null) {
// use cached intermediate surface, if available
cachedSrc = (SurfaceData)srcTmp.get();
cachedSrc = srcTmp.get();
}
// convert source to IntArgbPre
@ -752,7 +752,7 @@ class D3DGeneralBlit extends Blit {
if (src != cachedSrc) {
// cache the intermediate surface
srcTmp = new WeakReference(src);
srcTmp = new WeakReference<>(src);
}
}
}

View File

@ -41,7 +41,6 @@ import sun.awt.Win32GraphicsDevice;
import sun.awt.windows.WWindowPeer;
import sun.java2d.pipe.hw.ContextCapabilities;
import sun.java2d.windows.WindowsFlags;
import static sun.java2d.pipe.BufferedOpCodes.*;
import static sun.java2d.d3d.D3DContext.D3DContextCaps.*;
import sun.java2d.d3d.D3DContext.D3DContextCaps;
@ -383,9 +382,9 @@ public class D3DGraphicsDevice extends Win32GraphicsDevice {
}
private static native void enumDisplayModesNative(int screen,
ArrayList modes);
ArrayList<DisplayMode> modes);
@Override
protected void enumDisplayModes(final int screen, final ArrayList modes) {
protected void enumDisplayModes(final int screen, final ArrayList<DisplayMode> modes) {
D3DRenderQueue rq = D3DRenderQueue.getInstance();
rq.lock();
try {

View File

@ -75,7 +75,7 @@ public class GDIWindowSurfaceData extends SurfaceData {
public static final SurfaceType ThreeByteBgrGdi =
SurfaceType.ThreeByteBgr.deriveSubType(DESC_GDI);
private static native void initIDs(Class xorComp);
private static native void initIDs(Class<?> xorComp);
static {
initIDs(XORComposite.class);

View File

@ -201,7 +201,7 @@ public class WindowsFlags {
private static void initJavaFlags() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction()
new java.security.PrivilegedAction<Object>()
{
public Object run() {
magPresent = getBooleanProp(

View File

@ -454,7 +454,7 @@ JNIEXPORT jobjectArray JNICALL Java_sun_awt_windows_WInputMethodDescriptor_getNa
TRY;
// get list of available HKLs
int layoutCount = ::GetKeyboardLayoutList(0, NULL);
const int layoutCount = ::GetKeyboardLayoutList(0, NULL);
HKL FAR * hKLList = (HKL FAR *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(HKL), layoutCount);
CHECK_NULL_RETURN(hKLList, NULL);
::GetKeyboardLayoutList(layoutCount, hKLList);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 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
@ -219,7 +219,7 @@ void AwtList::SetMultiSelect(BOOL ms) {
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
/* Copy current box's contents to string array */
int nCount = GetCount();
const int nCount = GetCount();
LPTSTR * strings = new LPTSTR[nCount];
int i;

View File

@ -20,10 +20,6 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
import java.awt.*;

View File

@ -0,0 +1,480 @@
/*
* 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
* 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 6275887 6429971 6459792
@summary Test that we don't crash when alt+tabbing in and out of
fullscreen app
@author Dmitri.Trembovetski@sun.com: area=FullScreen
@run main/othervm/timeout=100 AltTabCrashTest -auto -changedm
@run main/othervm/timeout=100 -Dsun.java2d.d3d=True AltTabCrashTest -auto -changedm
@run main/othervm/timeout=100 -Dsun.java2d.d3d=True AltTabCrashTest -auto -usebs -changedm
@run main/othervm/timeout=100 -Dsun.java2d.opengl=True AltTabCrashTest -auto
*/
import java.awt.AWTException;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.Random;
import java.util.Vector;
/**
* Note that the alt+tabbing in and out part will most likely only work
* on Windows, and only if there are no interventions.
*/
public class AltTabCrashTest extends Frame {
public static int width;
public static int height;
public static volatile boolean autoMode;
public static boolean useBS;
public static final int NUM_OF_BALLS = 70;
// number of times to alt+tab in and out of the app
public static int altTabs = 5;
private final Vector<Ball> balls = new Vector<>();
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice();
VolatileImage vimg = null;
BufferStrategy bufferStrategy = null;
volatile boolean timeToQuit = false;
static final Object lock = new Object();
enum SpriteType {
OVALS, VIMAGES, BIMAGES, AAOVALS, TEXT
}
private static boolean changeDM = false;
private static SpriteType spriteType;
static Random rnd = new Random();
public AltTabCrashTest( ) {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
timeToQuit = true;
}
}
});
setIgnoreRepaint(true);
addMouseListener(new MouseHandler());
for (int i = 0; i < NUM_OF_BALLS; i++) {
int x = 50 + rnd.nextInt(550), y = 50 + rnd.nextInt(400);
balls.addElement(createRandomBall(y, x));
}
setUndecorated(true);
gd.setFullScreenWindow(this);
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
if (gd.isDisplayChangeSupported() && changeDM) {
DisplayMode dm = findDisplayMode();
if (dm != null) {
try {
gd.setDisplayMode(dm);
} catch (IllegalArgumentException iae) {
System.err.println("Error setting display mode");
}
}
}
if (useBS) {
createBufferStrategy(2);
bufferStrategy = getBufferStrategy();
} else {
Graphics2D g = (Graphics2D) getGraphics();
render(g);
g.dispose();
}
Thread t = new BallThread();
t.start();
if (autoMode) {
Thread tt = new AltTabberThread();
tt.start();
synchronized (lock) {
while (!timeToQuit) {
try {
lock.wait(200);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
t = null;
dispose();
}
}
private Ball createRandomBall(final int y, final int x) {
Ball b;
SpriteType type;
if (spriteType == null) {
int index = rnd.nextInt(SpriteType.values().length);
type = SpriteType.values()[index];
} else {
type = spriteType;
}
switch (type) {
case VIMAGES: b = new VISpriteBall(x, y); break;
case AAOVALS: b = new AAOvalBall(x, y); break;
case BIMAGES: b = new BISpriteBall(x, y); break;
case TEXT: b = new TextBall(x,y, "Text Sprite!"); break;
default: b = new Ball(x, y); break;
}
return b;
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
synchronized (balls) {
balls.addElement(createRandomBall(e.getX(), e.getY()));
}
}
}
private class AltTabberThread extends Thread {
Robot robot;
void pressAltTab() {
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_ALT);
}
void pressShiftAltTab() {
robot.keyPress(KeyEvent.VK_SHIFT);
pressAltTab();
robot.keyRelease(KeyEvent.VK_SHIFT);
}
public void run() {
try {
robot = new Robot();
robot.setAutoDelay(200);
} catch (AWTException e) {
throw new RuntimeException("Can't create robot");
}
boolean out = true;
while (altTabs-- > 0 && !timeToQuit) {
System.err.println("Alt+tabber Iteration: "+altTabs);
try { Thread.sleep(2500); } catch (InterruptedException ex) {}
if (out) {
System.err.println("Issuing alt+tab");
pressAltTab();
} else {
System.err.println("Issuing shift ");
pressShiftAltTab();
}
out = !out;
}
System.err.println("Alt+tabber finished.");
synchronized (lock) {
timeToQuit = true;
lock.notify();
}
}
}
private class BallThread extends Thread {
public void run() {
while (!timeToQuit) {
if (useBS) {
renderToBS();
bufferStrategy.show();
} else {
Graphics g = AltTabCrashTest.this.getGraphics();
render(g);
g.dispose();
}
}
gd.setFullScreenWindow(null);
AltTabCrashTest.this.dispose();
}
}
static class Ball {
int x, y; // current location
int dx, dy; // motion delta
int diameter = 40;
Color color = Color.red;
public Ball() {
}
public Ball(int x, int y) {
this.x = x;
this.y = y;
dx = x % 20 + 1;
dy = y % 20 + 1;
color = new Color(rnd.nextInt(0x00ffffff));
}
public void move() {
if (x < 10 || x >= AltTabCrashTest.width - 20)
dx = -dx;
if (y < 10 || y > AltTabCrashTest.height - 20)
dy = -dy;
x += dx;
y += dy;
}
public void paint(Graphics g, Color c) {
if (c == null) {
g.setColor(color);
} else {
g.setColor(c);
}
g.fillOval(x, y, diameter, diameter);
}
}
static class TextBall extends Ball {
String text;
public TextBall(int x, int y, String text) {
super(x, y);
this.text = text;
}
public void paint(Graphics g, Color c) {
if (c == null) {
g.setColor(color);
} else {
g.setColor(c);
}
g.drawString(text, x, y);
}
}
static class AAOvalBall extends Ball {
public AAOvalBall(int x, int y) {
super(x, y);
}
public void paint(Graphics g, Color c) {
if (c == null) {
Graphics2D g2d = (Graphics2D)g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(color);
g2d.fillOval(x, y, diameter, diameter);
} else {
g.setColor(c);
g.fillOval(x-2, y-2, diameter+4, diameter+4);
}
}
}
static abstract class SpriteBall extends Ball {
Image image;
public SpriteBall(int x, int y) {
super(x, y);
image = createSprite();
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
}
public void paint(Graphics g, Color c) {
if (c != null) {
g.setColor(c);
g.fillRect(x, y, image.getWidth(null), image.getHeight(null));
} else do {
validateSprite();
g.drawImage(image, x, y, null);
} while (renderingIncomplete());
}
public abstract Image createSprite();
public void validateSprite() {}
public boolean renderingIncomplete() { return false; }
}
class VISpriteBall extends SpriteBall {
public VISpriteBall(int x, int y) {
super(x, y);
}
public boolean renderingIncomplete() {
return ((VolatileImage)image).contentsLost();
}
public Image createSprite() {
return gd.getDefaultConfiguration().
createCompatibleVolatileImage(20, 20);
}
public void validateSprite() {
int result =
((VolatileImage)image).validate(getGraphicsConfiguration());
if (result == VolatileImage.IMAGE_INCOMPATIBLE) {
image = createSprite();
result = VolatileImage.IMAGE_RESTORED;
}
if (result == VolatileImage.IMAGE_RESTORED) {
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
}
}
}
class BISpriteBall extends SpriteBall {
public BISpriteBall(int x, int y) {
super(x, y);
}
public Image createSprite() {
return new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
}
}
public void renderOffscreen() {
Graphics2D g2d = (Graphics2D) vimg.getGraphics();
synchronized (balls) {
for (Ball b : balls) {
b.paint(g2d, getBackground());
b.move();
b.paint(g2d, null);
}
}
g2d.dispose();
}
public void renderToBS() {
width = getWidth();
height = getHeight();
do {
Graphics2D g2d = (Graphics2D)bufferStrategy.getDrawGraphics();
g2d.clearRect(0, 0, width, height);
synchronized (balls) {
for (Ball b : balls) {
b.move();
b.paint(g2d, null);
}
}
g2d.dispose();
} while (bufferStrategy.contentsLost() ||
bufferStrategy.contentsRestored());
}
public void render(Graphics g) {
do {
height = getBounds().height;
width = getBounds().width;
if (vimg == null) {
vimg = createVolatileImage(width, height);
renderOffscreen();
}
int returnCode = vimg.validate(getGraphicsConfiguration());
if (returnCode == VolatileImage.IMAGE_RESTORED) {
renderOffscreen();
} else if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
vimg = getGraphicsConfiguration().
createCompatibleVolatileImage(width, height);
renderOffscreen();
} else if (returnCode == VolatileImage.IMAGE_OK) {
renderOffscreen();
}
g.drawImage(vimg, 0, 0, this);
} while (vimg.contentsLost());
}
public static void main(String args[]) {
for (String arg : args) {
if (arg.equalsIgnoreCase("-auto")) {
autoMode = true;
System.err.println("Running in automatic mode using Robot");
} else if (arg.equalsIgnoreCase("-usebs")) {
useBS = true;
System.err.println("Using BufferStrategy instead of VI");
} else if (arg.equalsIgnoreCase("-changedm")) {
changeDM= true;
System.err.println("The test will change display mode");
} else if (arg.equalsIgnoreCase("-vi")) {
spriteType = SpriteType.VIMAGES;
} else if (arg.equalsIgnoreCase("-bi")) {
spriteType = SpriteType.BIMAGES;
} else if (arg.equalsIgnoreCase("-ov")) {
spriteType = SpriteType.OVALS;
} else if (arg.equalsIgnoreCase("-aaov")) {
spriteType = SpriteType.AAOVALS;
} else if (arg.equalsIgnoreCase("-tx")) {
spriteType = SpriteType.TEXT;
} else {
System.err.println("Usage: AltTabCrashTest [-usebs][-auto]" +
"[-changedm][-vi|-bi|-ov|-aaov|-tx]");
System.err.println(" -usebs: use BufferStrategy instead of VI");
System.err.println(" -auto: automatically alt+tab in and out" +
" of the application ");
System.err.println(" -changedm: change display mode");
System.err.println(" -(vi|bi|ov|tx|aaov) : use only VI, BI, " +
"text or [AA] [draw]Oval sprites");
System.exit(0);
}
}
if (spriteType != null) {
System.err.println("The test will only use "+spriteType+" sprites.");
}
new AltTabCrashTest();
}
private DisplayMode findDisplayMode() {
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
DisplayMode dms[] = gd.getDisplayModes();
DisplayMode currentDM = gd.getDisplayMode();
for (DisplayMode dm : dms) {
if (dm.getBitDepth() > 8 &&
dm.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI &&
dm.getBitDepth() != currentDM.getBitDepth() &&
dm.getWidth() == currentDM.getWidth() &&
dm.getHeight() == currentDM.getHeight())
{
// found a mode which has the same dimensions but different
// depth
return dm;
}
if (dm.getBitDepth() == DisplayMode.BIT_DEPTH_MULTI &&
(dm.getWidth() != currentDM.getWidth() ||
dm.getHeight() != currentDM.getHeight()))
{
// found a mode which has the same depth but different
// dimensions
return dm;
}
}
return null;
}
}

View File

@ -0,0 +1,60 @@
/*
* 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.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
/**
* @test
* @bug 8029455
* @summary Tests that copyarea on offscreen images works as expected when
* scaled transform is set
* @run main ScaledCopyArea
*/
public final class ScaledCopyArea {
public static void main(final String[] args) {
final BufferedImage bi = new BufferedImage(100, 300,
BufferedImage.TYPE_INT_RGB);
final Graphics2D g = bi.createGraphics();
g.scale(2, 2);
g.setColor(Color.RED);
g.fillRect(0, 0, 100, 300);
g.setColor(Color.GREEN);
g.fillRect(0, 100, 100, 100);
g.copyArea(0, 100, 100, 100, 0, -100);
g.dispose();
for (int x = 0; x < 100; ++x) {
for (int y = 0; y < 100; ++y) {
final int actual = bi.getRGB(x, y);
final int exp = Color.GREEN.getRGB();
if (actual != exp) {
System.err.println("Expected:" + Integer.toHexString(exp));
System.err.println("Actual:" + Integer.toHexString(actual));
throw new RuntimeException("Test " + "failed");
}
}
}
}
}

View File

@ -0,0 +1,49 @@
/*
* 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 4181601
@summary tests that DataFlavor.clone method doesn't throw exception
@author xianfa: area=
@run main DataFlavorCloneTest
*/
import java.awt.datatransfer.DataFlavor;
public class DataFlavorCloneTest {
public static void main(String[] args) throws Exception {
DataFlavor df1 = null;
Object df2 = null;
try {
df1 = new DataFlavor();
df2 = df1.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("FAILED: Unexpected exception: " + e);
} catch (NullPointerException e) {
throw new RuntimeException("FAILED: Got Null pointer exception");
}
}
}

View File

@ -0,0 +1,62 @@
/*
* 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 4175731
@summary DataFlavor.equals(null) throws NullPointerException
@author prs@sparc.spb.su: area=
@run main DataFlavorEqualsNullTest
*/
import java.awt.datatransfer.DataFlavor;
public class DataFlavorEqualsNullTest {
public static boolean finished = false;
static boolean noexc = true;
static boolean eq = false;
static DataFlavor df = null;
public static void main(String[] args) throws Exception {
try {
df = new DataFlavor("application/postscript;class=java.awt.datatransfer.DataFlavor");
} catch (ClassNotFoundException e) {
// This should never happen
}
try {
eq = df.equals((Object) null);
if (eq) noexc = false;
eq = df.equals((DataFlavor) null);
if (eq) noexc = false;
eq = df.equals((String) null);
if (eq) noexc = false;
} catch (NullPointerException e1) {
noexc = false;
}
finished = true;
if (!noexc)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,58 @@
/*
* 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 4175341
@summary DataFlavor.equals throws NullPointerException
@author prs@sparc.spb.su: area=
@run main DataFlavorEqualsTest
*/
import java.awt.datatransfer.DataFlavor;
public class DataFlavorEqualsTest {
public static boolean finished = false;
static boolean noexc = true;
static boolean eq = false;
static DataFlavor df = null;
public static void main(String[] args) {
df = new DataFlavor();
try {
eq = df.equals((Object)new DataFlavor());
if (!eq) noexc = false;
eq = df.equals(new DataFlavor());
if (!eq) noexc = false;
eq = df.equals("application/postscript;class=java.awt.datatransfer.DataFlavor");
if (eq) noexc = false;
} catch (NullPointerException e1) {
noexc = false;
}
finished = true;
if (!noexc)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,45 @@
/*
* 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 4172848
@summary DataFlavor.isFlavorJavaFileListType works wrong
@author prs@sparc.spb.su: area=
@run main DataFlavorFileListTest
*/
import java.awt.datatransfer.DataFlavor;
public class DataFlavorFileListTest {
public static boolean finished = false;
static DataFlavor df = null;
public static void main(String[] args) throws Exception {
df = new DataFlavor("application/x-java-file-list;class=java.util.ArrayList");
boolean fl = df.isFlavorJavaFileListType();
finished = true;
if (!fl)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,46 @@
/*
* 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 4174020
@summary DataFlavor.isMimeTypeSerializedObject works wrong
@author prs@sparc.spb.su: area=
@run main DataFlavorSerializedTest
*/
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
public class DataFlavorSerializedTest {
public static boolean finished = false;
static DataFlavor df = null;
public static void main(String[] args) throws Exception {
df = new DataFlavor("application/x-java-serialized-object;class=java.io.Serializable");
boolean fl = df.isMimeTypeSerializedObject();
finished = true;
if (!fl)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,64 @@
/*
* 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 4250750
@summary tests that DataFlavor.match() does not throw NPE.
@author prs@sparc.spb.su: area=
@run main DefaultMatchTest
*/
import java.awt.datatransfer.DataFlavor;
public class DefaultMatchTest {
static DataFlavor df1, df2, df3;
public static void main(String[] args) throws Exception {
boolean passed = true;
try {
df1 = new DataFlavor("application/postscript");
df2 = new DataFlavor();
df3 = new DataFlavor();
} catch (ClassNotFoundException e1) {
throw new RuntimeException("Could not create DataFlavors. This should never happen.");
} catch (IllegalArgumentException e2) {
passed = false;
}
try {
boolean b;
b = df1.match(df2);
b = df2.match(df1);
b = df2.match(df3);
} catch (NullPointerException e) {
throw new RuntimeException("The test FAILED: DataFlavor.match still throws NPE");
}
if (!passed) {
throw new RuntimeException("Test FAILED");
}
System.out.println("Test PASSED");
}
}

View File

@ -0,0 +1,83 @@
/*
* 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 4157612
@summary tests that certain awt classes do not break basic hashCode() contract.
@author prs@sparc.spb.su: area=
@run main EqualHashCodeTest
*/
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
public class EqualHashCodeTest {
static DataFlavor df1, df2;
static Insets insets1, insets2;
static Dimension dim1, dim2;
static ColorModel cm1, cm2;
static int[] ColorModelBits = { 8, 8, 8, 8 };
public static void main(String[] args) throws Exception {
boolean passed = true;
try {
df1 = new DataFlavor( "application/postscript" );
df2 = new DataFlavor( "application/*" );
} catch (ClassNotFoundException e1) {
throw new RuntimeException("Could not create DataFlavors. This should never happen.");
} catch (IllegalArgumentException e2) {
passed = false;
}
if (df1.hashCode() != df2.hashCode()) {
passed = false;
}
dim1 = new Dimension(3, 18);
dim2 = new Dimension(3, 18);
if (dim1.hashCode() != dim2.hashCode()) {
passed = false;
}
insets1 = new Insets(3, 4, 7, 11);
insets2 = new Insets(3, 4, 7, 11);
if (insets1.hashCode() != insets2.hashCode()) {
passed = false;
}
cm1 = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
ColorModelBits, true, true,
Transparency.OPAQUE, 0);
cm2 = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
ColorModelBits, true, true,
Transparency.OPAQUE, 0);
if (cm1.hashCode() != cm2.hashCode()) {
passed = false;
}
if (!passed)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,80 @@
/*
* 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 4274267
@summary Tests that externalized DataFlavor is restored properly
@author prs@sparc.spb.su: area=
@run main ExternalizeTest
*/
import java.awt.datatransfer.DataFlavor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ExternalizeTest {
public static void main(String[] args) {
DataFlavor df = new DataFlavor("text/enriched; charset=ascii", "Enrich Flavor");
storeDataFlavor(df);
DataFlavor df1 = retrieveDataFlavor();
if (!df.equals(df1)) {
throw new RuntimeException("FAILED: restored DataFlavor is not equal to externalized one");
}
}
public static void storeDataFlavor(DataFlavor dfs){
// To store the dataflavor into a file using writeExternal()
try {
FileOutputStream ostream = new FileOutputStream("t.tmp");
ObjectOutputStream p = new ObjectOutputStream(ostream);
dfs.writeExternal(p);
ostream.close();
} catch (Exception ex){
throw new RuntimeException("FAIL: problem occured while storing DataFlavor");
}
}
public static DataFlavor retrieveDataFlavor(){
DataFlavor df=DataFlavor.stringFlavor;
try {
FileInputStream istream = new FileInputStream("t.tmp");
ObjectInputStream p = new ObjectInputStream(istream);
df.readExternal(p);
istream.close();
} catch (Exception ex){
throw new RuntimeException("FAIL: problem occured while retrieving DataFlavor");
}
return df;
}
}

View File

@ -0,0 +1,70 @@
/*
* 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 4260874
@summary Tests that DataFlavor.getReaderForText do not throw NPE when transferObject is null
@author tdv@sparc.spb.su: area=
@run main GetReaderForTextIAEForStringSelectionTest
*/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Reader;
public class GetReaderForTextIAEForStringSelectionTest {
public static void main(String[] args) throws Exception {
DataFlavor pt ;
try {
pt = DataFlavor.plainTextFlavor;
StringSelection ss = new StringSelection("ReaderExample");
Reader re = pt.getReaderForText(ss);
if(re == null) {
throw new RuntimeException("Test FAILED! reader==null");
}
} catch (Exception e) {
throw new RuntimeException("Test FAILED because of the exception: " + e);
}
}
}
class FakeTransferable implements Transferable {
public DataFlavor[] getTransferDataFlavors() {
return null;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return false;
}
public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException, IOException {
return null;
}
}

View File

@ -0,0 +1,74 @@
/*
* 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 4260874
@summary Tests that DataFlavor.getReaderForText do not throw NPE when transferObject is null
@author tdv@sparc.spb.su: area=
@run main GetReaderForTextNPETest
*/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Reader;
public class GetReaderForTextNPETest {
public static void main(String[] args) {
DataFlavor df = new DataFlavor();
FakeTransferable t = new FakeTransferable();
Reader reader;
try {
reader = df.getReaderForText(null);
} catch (Exception e) {
if (!(e instanceof NullPointerException)) {
throw new RuntimeException("TEST FAILED: not a NPE thrown on a null argument.");
}
}
try {
reader = df.getReaderForText(t);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
throw new RuntimeException("FAILED: not an IllegalArgumentException thrown on a transferable with null transfer data .");
}
}
}
}
class FakeTransferable implements Transferable {
public DataFlavor[] getTransferDataFlavors() {
return null;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return false;
}
public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException, IOException {
return null;
}
}

View File

@ -0,0 +1,86 @@
/*
* 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 4116781
@summary Tests that long (more than 64K) MimeType can be serialized
and deserialized.
@author gas@sparc.spb.su area=datatransfer
@run main MimeTypeSerializationTest
*/
import java.awt.datatransfer.DataFlavor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class MimeTypeSerializationTest {
public static void main(String[] args) throws Exception {
boolean failed = false;
try {
int len = 70000;
char[] longValue = new char[len];
Arrays.fill(longValue, 'v');
DataFlavor longdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
"; class=java.lang.String; longParameter=" + new String(longValue));
DataFlavor shortdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
"; class=java.lang.String");
ByteArrayOutputStream baos = new ByteArrayOutputStream(100000);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(longdf);
oos.writeObject(shortdf);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
DataFlavor longdf2 = (DataFlavor) ois.readObject();
DataFlavor shortdf2 = (DataFlavor) ois.readObject();
ois.close();
failed = !( longdf.getMimeType().equals(longdf2.getMimeType()) &&
shortdf.getMimeType().equals(shortdf2.getMimeType()) );
if (failed) {
System.err.println("deserialized MIME type does not match original one");
}
} catch (IOException e) {
failed = true;
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (failed) {
throw new RuntimeException("test failed: serialization attempt failed");
} else {
System.err.println("test passed");
}
}
}

View File

@ -0,0 +1,50 @@
/*
* 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 4212613
@summary tests that DataFlavor(String) doesn't through Exception if no "class=" specified.
@author prs@sparc.spb.su: area=
@run main NoClassParameterTest
*/
import java.awt.datatransfer.DataFlavor;
public class NoClassParameterTest {
static DataFlavor df = null;
public static void main(String[] args) {
boolean passed = true;
try {
df = new DataFlavor("application/postscript");
} catch (ClassNotFoundException e1) {
throw new RuntimeException("This should never happen.");
} catch (IllegalArgumentException e2) {
passed = false;
}
if (!passed)
throw new RuntimeException("Test FAILED");
}
}

View File

@ -0,0 +1,60 @@
/*
* 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 4260860
@summary tests that DataFlavor.normalizeMimeTypeParameter() returns parm value
@author ssi@sparc.spb.su area=
@run main NormalizeMimeTypeParameter
*/
import java.awt.datatransfer.DataFlavor;
public class NormalizeMimeTypeParameter {
static class TestFlavor extends DataFlavor {
public String normalizeMimeType(String mimeType) {
return super.normalizeMimeType(mimeType);
}
public String normalizeMimeTypeParameter(String parameterName,
String parameterValue) {
return super.normalizeMimeTypeParameter(parameterName, parameterValue);
}
}
static TestFlavor testFlavor;
public static void main(String[] args) {
testFlavor = new TestFlavor();
String type = "TestType";
String parameter = "TestParameter";
String retValue = testFlavor.normalizeMimeTypeParameter(type, parameter);
if(!retValue.equals(parameter)) {
throw new RuntimeException("Test FAILED: " + retValue);
}
}
}

View File

@ -0,0 +1,108 @@
/*
* 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 4682039
@summary Tests that DataTransferer.getFormatsForFlavors() does not throw
NullPointerException if some of given as parameter data flavors
are null.
@author gas@sparc.spb.su area=datatransfer
@run main NullDataFlavorTest
*/
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
public class NullDataFlavorTest {
private final static Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
public static void main(String[] args) throws Exception {
boolean failed = false;
try {
clipboard.setContents(new NullSelection("DATA1",
new DataFlavor[] { null, null, null }), null);
clipboard.setContents(new NullSelection("DATA2",
new DataFlavor[] { null, DataFlavor.stringFlavor, null }), null);
clipboard.setContents(new NullSelection("DATA3", null), null);
} catch (NullPointerException e) {
failed = true;
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
if (failed) {
throw new RuntimeException("test failed: NullPointerException " +
"has been thrown");
} else {
System.err.println("test passed");
}
}
}
class NullSelection implements Transferable {
private final DataFlavor[] flavors;
private final String data;
public NullSelection(String data, DataFlavor[] flavors) {
this.data = data;
this.flavors = flavors;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
for (DataFlavor fl : flavors) {
if (flavor.equals(fl)) {
return true;
}
}
return false;
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, java.io.IOException
{
for (DataFlavor fl : flavors) {
if (flavor.equals(fl)) {
return data;
}
}
throw new UnsupportedFlavorException(flavor);
}
}

View File

@ -0,0 +1,90 @@
/*
* 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 4274234
@summary Tests that DataFlavor.getReaderForText() doesn't throw UnsupportedEncodingException for unicode text
@author prs@sparc.spb.su: area=
@run main ReaderForUnicodeText
*/
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
public class ReaderForUnicodeText {
public static void main(String[] args) throws Exception {
DataFlavor df = DataFlavor.plainTextFlavor;
TextTransferable t = new TextTransferable();
Reader reader;
try {
reader = df.getReaderForText(t);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("FAILED: Exception thrown in getReaderForText()");
}
}
}
class TextTransferable implements Transferable {
String text = "Try to test me...";
@Override
public DataFlavor[] getTransferDataFlavors() {
DataFlavor flavors[] = {DataFlavor.plainTextFlavor};
return flavors;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
if (flavor.match(DataFlavor.plainTextFlavor)) {
return true;
}
return false;
}
@Override
public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException, IOException {
byte[] textBytes = null;
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
String encoding = flavor.getParameter("charset");
if (encoding == null) {
textBytes = text.getBytes();
} else {
textBytes = text.getBytes(encoding);
}
return new ByteArrayInputStream(textBytes);
}
}

View File

@ -0,0 +1,50 @@
/*
* 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 4370469
@summary tests that selectBestTextFlavor doesn't throw NPE
@author prs@sparc.spb.su: area=
@run main SelectBestFlavorNPETest
*/
import java.awt.datatransfer.DataFlavor;
public class SelectBestFlavorNPETest {
public static void main(String[] args) {
DataFlavor flavor1 = new DataFlavor("text/plain; charset=unicode; class=java.io.InputStream",
"Flavor 1");
DataFlavor flavor2 = new DataFlavor("text/plain; class=java.io.InputStream", "Flavor 2");
DataFlavor[] flavors = new DataFlavor[]{flavor1, flavor2};
try {
DataFlavor best = DataFlavor.selectBestTextFlavor(flavors);
System.out.println("best=" + best);
} catch (NullPointerException e1) {
throw new RuntimeException("Test FAILED because of NPE in selectBestTextFlavor");
}
}
}

View File

@ -0,0 +1,73 @@
/*
* 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 4386360
@summary tests that DataFlavor.selectBestTextFlavor() returns null when passed
is a null array or an empty array or an array which doesn't contain
a text flavor in a supported encoding.
@author das@sparc.spb.su area=datatransfer
@run main SelectBestTextFlavorBadArrayTest
*/
import java.awt.datatransfer.DataFlavor;
import java.util.Stack;
import java.util.stream.Collectors;
public class SelectBestTextFlavorBadArrayTest {
public static void main(String[] args) {
final String[] failureMessages = {
"DataFlavor.selectBestTextFlavor(null) doesn't return null.",
"DataFlavor.selectBestTextFlavor() doesn't return null for an empty array.",
"DataFlavor.selectBestTextFlavor() shouldn't return flavor in an unsupported encoding."
};
Stack<String> failures = new Stack<>();
DataFlavor flavor = DataFlavor.selectBestTextFlavor(null);
if (flavor != null) {
failures.push(failureMessages[0]);
}
flavor = DataFlavor.selectBestTextFlavor(new DataFlavor[0]);
if (flavor != null) {
failures.push(failureMessages[1]);
}
try {
flavor = DataFlavor.selectBestTextFlavor(new DataFlavor[]
{ new DataFlavor("text/plain; charset=unsupported; class=java.io.InputStream") });
} catch (ClassNotFoundException e) {
e.printStackTrace();
failures.push("Exception thrown: " + e.toString());
}
if (flavor != null) {
failures.push(failureMessages[2]);
}
if (failures.size() > 0) {
String failureReport = failures.stream().collect(Collectors.joining("\n"));
throw new RuntimeException("TEST FAILED: \n" + failureReport);
}
}
}

View File

@ -0,0 +1,47 @@
/*
* 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 4250768
@summary tests that DataFlavor.toString() does not throw NPE
@author prs@sparc.spb.su: area=
@run main ToStringNullPointerTest
*/
import java.awt.datatransfer.DataFlavor;
public class ToStringNullPointerTest {
static DataFlavor df1;
public static void main(String[] args) {
df1 = new DataFlavor();
try {
String thisDF = df1.toString();
} catch (NullPointerException e) {
throw new RuntimeException("Test FAILED: it still throws NPE!");
}
}
}

View File

@ -0,0 +1,94 @@
/*
* 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 4493189
@summary tests that addUnencodedNativeForFlavor()/addFlavorForUnencodedNative()
do not allow to duplicate mappings
@author das@sparc.spb.su area=datatransfer
@run main DuplicateMappingTest
*/
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.util.Iterator;
public class DuplicateMappingTest {
public static void main(String[] args) throws Exception {
final String nativeString = "NATIVE";
final DataFlavor dataFlavor = new DataFlavor();
final SystemFlavorMap fm =
(SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
fm.addUnencodedNativeForFlavor(dataFlavor, nativeString);
fm.addUnencodedNativeForFlavor(dataFlavor, nativeString);
final java.util.List natives =
fm.getNativesForFlavor(dataFlavor);
boolean found = false;
for (final Iterator i = natives.iterator(); i.hasNext(); ) {
if (nativeString.equals(i.next())) {
if (found) {
throw new RuntimeException("getNativesForFlavor() returns:" +
natives);
} else {
found = true;
}
}
}
if (!found) {
throw new RuntimeException("getNativesForFlavor() returns:" +
natives);
}
fm.addFlavorForUnencodedNative(nativeString, dataFlavor);
fm.addFlavorForUnencodedNative(nativeString, dataFlavor);
final java.util.List flavors =
fm.getFlavorsForNative(nativeString);
found = false;
for (final Iterator i = flavors.iterator(); i.hasNext(); ) {
if (dataFlavor.equals(i.next())) {
if (found) {
throw new RuntimeException("getFlavorsForNative() returns:" +
flavors);
} else {
found = true;
}
}
}
if (!found) {
throw new RuntimeException("getFlavorsForNative() returns:" +
natives);
}
}
}

View File

@ -0,0 +1,169 @@
/*
* 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 4493178
@summary tests that getNativesForFlavor() synthesizes an encoded String native
only if there are no mappings for the DataFlavor and the mappings
were not explicitly removed
@author das@sparc.spb.su area=datatransfer
@run main GetNativesForFlavorTest
*/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.util.Iterator;
public class GetNativesForFlavorTest {
final static SystemFlavorMap fm =
(SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
public static void main(String[] args) throws Exception {
// 1.Check that the encoded native is not added if there are other
// natives for this DataFlavor.
test1();
// 2.Check that the encoded native is not added if all mappings were
// explicitly removed for this DataFlavor.
test2();
// 3.Check that only the encoded native is added for text DataFlavors
// that has no mappings and that DataFlavor is properly encoded.
test3();
// 4.Verifies that the encoded native is added only for DataFlavors
// that has no mappings and that DataFlavor is properly encoded.
test4();
}
/**
* Verifies that the encoded native is not added if there are other
* natives mapped to this DataFlavor.
*/
public static void test1() throws ClassNotFoundException {
final DataFlavor flavor =
new DataFlavor("text/plain-TEST; charset=Unicode");
final java.util.List natives = fm.getNativesForFlavor(flavor);
if (natives.size() > 1) {
for (final Iterator i = natives.iterator(); i.hasNext(); ) {
String element = (String) i.next();
if (SystemFlavorMap.isJavaMIMEType(element)) {
throw new RuntimeException("getFlavorsForNative() returns: "
+ natives);
}
}
}
}
/**
* Verifies that the encoded native is not added if all mappings were
* explicitly removed for this DataFlavor.
*/
public static void test2() throws ClassNotFoundException {
final DataFlavor flavor =
new DataFlavor("text/plain-TEST; charset=Unicode");
fm.setNativesForFlavor(flavor, new String[0]);
final java.util.List natives = fm.getNativesForFlavor(flavor);
if (!natives.isEmpty()) {
throw new RuntimeException("getFlavorsForNative() returns:" +
natives);
}
}
/**
* Verifies that only the encoded native is added for text DataFlavors
* that has no mappings and that DataFlavor is properly encoded.
*/
public static void test3() throws ClassNotFoundException {
//
final DataFlavor flavor =
new DataFlavor("text/plain-TEST-nocharset; class=java.nio.ByteBuffer");
final java.util.List natives = fm.getNativesForFlavor(flavor);
boolean encodedNativeFound = false;
if (natives.size() == 0) {
throw new RuntimeException("getFlavorsForNative() returns:" +
natives);
}
if (natives.size() == 1) {
String element = (String) natives.get(0);
if (SystemFlavorMap.isJavaMIMEType(element)) {
final DataFlavor decodedFlavor =
SystemFlavorMap.decodeDataFlavor(element);
if (!flavor.equals(decodedFlavor)) {
System.err.println("DataFlavor is not properly incoded:");
System.err.println(" encoded flavor: " + flavor);
System.err.println(" decoded flavor: " + decodedFlavor);
throw new RuntimeException("getFlavorsForNative() returns:"
+ natives);
}
}
} else {
for (final Iterator i = natives.iterator(); i.hasNext(); ) {
String element = (String) i.next();
if (SystemFlavorMap.isJavaMIMEType(element)) {
throw new RuntimeException("getFlavorsForNative() returns:"
+ natives);
}
}
}
}
/**
* Verifies that the encoded native is added only for DataFlavors
* that has no mappings and that DataFlavor is properly encoded.
*/
public static void test4() throws ClassNotFoundException {
final DataFlavor flavor =
new DataFlavor("unknown/unknown");
final java.util.List natives = fm.getNativesForFlavor(flavor);
if (natives.size() == 1) {
String element = (String) natives.get(0);
if (SystemFlavorMap.isJavaMIMEType(element)) {
final DataFlavor decodedFlavor =
SystemFlavorMap.decodeDataFlavor(element);
if (!flavor.equals(decodedFlavor)) {
System.err.println("DataFlavor is not properly incoded:");
System.err.println(" encoded flavor: " + flavor);
System.err.println(" decoded flavor: " + decodedFlavor);
throw new RuntimeException("getFlavorsForNative() returns:"
+ natives);
}
}
} else {
throw new RuntimeException("getFlavorsForNative() returns:"
+ natives);
}
}
}

View File

@ -0,0 +1,67 @@
/*
* 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 4478912
@summary tests that getNativesForFlavor()/getFlavorsForNative() return the
same list as was set with setNativesForFlavor()/setFlavorsForNative()
@author das@sparc.spb.su area=datatransfer
@run main SetNativesForFlavorTest
*/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
public class SetNativesForFlavorTest {
public static void main(String[] args) throws Exception {
final String nativeString = "NATIVE";
final SystemFlavorMap fm =
(SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
fm.setNativesForFlavor(DataFlavor.plainTextFlavor,
new String[] { nativeString });
final java.util.List natives =
fm.getNativesForFlavor(DataFlavor.plainTextFlavor);
if (natives.size() != 1 || !natives.contains(nativeString)) {
throw new RuntimeException("getNativesForFlavor() returns:" +
natives);
}
final DataFlavor dataFlavor =
new DataFlavor("text/unknown; class=java.lang.String");
fm.setFlavorsForNative(nativeString, new DataFlavor[] { dataFlavor });
final java.util.List flavors = fm.getFlavorsForNative(nativeString);
if (flavors.size() != 1 || !flavors.contains(dataFlavor)) {
throw new RuntimeException("getFlavorsForNative() returns:" +
flavors);
}
}
}

View File

@ -0,0 +1,42 @@
/*
* 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.awt.geom.Path2D;
/**
* @test
* @bug 8042103
* @summary Path2D.moveTo() should work if empty initial capacity was set.
* @author Sergey Bylokhov
*/
public final class EmptyCapacity {
public static void main(final String[] args) {
final Path2D path1 = new Path2D.Double(Path2D.WIND_EVEN_ODD, 0);
path1.moveTo(10, 10);
path1.lineTo(20, 20);
final Path2D path2 = new Path2D.Float(Path2D.WIND_EVEN_ODD, 0);
path2.moveTo(10, 10);
path2.lineTo(20, 20);
}
}

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