提交 5dece1d3 编写于 作者: L lana

Merge

/* /*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -34,7 +34,6 @@ import javax.swing.border.Border; ...@@ -34,7 +34,6 @@ import javax.swing.border.Border;
import javax.swing.event.*; import javax.swing.event.*;
import javax.swing.plaf.*; import javax.swing.plaf.*;
import javax.swing.plaf.basic.*; import javax.swing.plaf.basic.*;
import com.apple.laf.ClientPropertyApplicator;
import com.apple.laf.ClientPropertyApplicator.Property; import com.apple.laf.ClientPropertyApplicator.Property;
import apple.laf.JRSUIConstants.Size; import apple.laf.JRSUIConstants.Size;
...@@ -142,35 +141,46 @@ public class AquaComboBoxUI extends BasicComboBoxUI implements Sizeable { ...@@ -142,35 +141,46 @@ public class AquaComboBoxUI extends BasicComboBoxUI implements Sizeable {
return new AquaComboBoxEditor(); return new AquaComboBoxEditor();
} }
class AquaComboBoxEditor extends BasicComboBoxEditor implements UIResource, DocumentListener { final class AquaComboBoxEditor extends BasicComboBoxEditor
protected AquaComboBoxEditor() { implements UIResource, DocumentListener {
AquaComboBoxEditor() {
super(); super();
editor = new AquaCustomComboTextField(); editor = new AquaCustomComboTextField();
editor.addFocusListener(this); editor.addFocusListener(this);
editor.getDocument().addDocumentListener(this); editor.getDocument().addDocumentListener(this);
} }
@Override
public void focusGained(final FocusEvent e) { public void focusGained(final FocusEvent e) {
if (arrowButton != null) {
arrowButton.repaint(); arrowButton.repaint();
} }
}
@Override
public void focusLost(final FocusEvent e) { public void focusLost(final FocusEvent e) {
if (arrowButton != null) {
arrowButton.repaint(); arrowButton.repaint();
} }
}
@Override
public void changedUpdate(final DocumentEvent e) { public void changedUpdate(final DocumentEvent e) {
editorTextChanged(); editorTextChanged();
} }
@Override
public void insertUpdate(final DocumentEvent e) { public void insertUpdate(final DocumentEvent e) {
editorTextChanged(); editorTextChanged();
} }
@Override
public void removeUpdate(final DocumentEvent e) { public void removeUpdate(final DocumentEvent e) {
editorTextChanged(); editorTextChanged();
} }
protected void editorTextChanged() { private void editorTextChanged() {
if (!popup.isVisible()) return; if (!popup.isVisible()) return;
final Object text = editor.getText(); final Object text = editor.getText();
......
...@@ -53,7 +53,7 @@ public abstract class CGraphicsConfig extends GraphicsConfiguration ...@@ -53,7 +53,7 @@ public abstract class CGraphicsConfig extends GraphicsConfiguration
@Override @Override
public Rectangle getBounds() { public Rectangle getBounds() {
final Rectangle2D nativeBounds = nativeGetBounds(device.getCoreGraphicsScreen()); final Rectangle2D nativeBounds = nativeGetBounds(device.getCGDisplayID());
return nativeBounds.getBounds(); // does integer rounding return nativeBounds.getBounds(); // does integer rounding
} }
......
/* /*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,11 +25,12 @@ ...@@ -25,11 +25,12 @@
package sun.awt; package sun.awt;
import java.awt.AWTPermission;
import java.awt.DisplayMode;
import java.awt.GraphicsConfiguration; import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice; import java.awt.GraphicsDevice;
import java.awt.Insets;
import java.awt.Window; import java.awt.Window;
import java.awt.AWTPermission;
import java.awt.DisplayMode;
import java.util.Objects; import java.util.Objects;
import sun.java2d.opengl.CGLGraphicsConfig; import sun.java2d.opengl.CGLGraphicsConfig;
...@@ -58,9 +59,12 @@ public final class CGraphicsDevice extends GraphicsDevice { ...@@ -58,9 +59,12 @@ public final class CGraphicsDevice extends GraphicsDevice {
} }
/** /**
* Returns CGDirectDisplayID, which is the same id as @"NSScreenNumber" in
* NSScreen.
*
* @return CoreGraphics display id. * @return CoreGraphics display id.
*/ */
public int getCoreGraphicsScreen() { public int getCGDisplayID() {
return displayID; return displayID;
} }
...@@ -107,8 +111,9 @@ public final class CGraphicsDevice extends GraphicsDevice { ...@@ -107,8 +111,9 @@ public final class CGraphicsDevice extends GraphicsDevice {
return nativeGetYResolution(displayID); return nativeGetYResolution(displayID);
} }
private static native double nativeGetXResolution(int displayID); public Insets getScreenInsets() {
private static native double nativeGetYResolution(int displayID); return nativeGetScreenInsets(displayID);
}
/** /**
* Enters full-screen mode, or returns to windowed mode. * Enters full-screen mode, or returns to windowed mode.
...@@ -214,9 +219,15 @@ public final class CGraphicsDevice extends GraphicsDevice { ...@@ -214,9 +219,15 @@ public final class CGraphicsDevice extends GraphicsDevice {
return nativeGetDisplayModes(displayID); return nativeGetDisplayModes(displayID);
} }
private native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate); private static native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate);
private static native DisplayMode nativeGetDisplayMode(int displayID);
private static native DisplayMode[] nativeGetDisplayModes(int displayID);
private native DisplayMode nativeGetDisplayMode(int displayID); private static native double nativeGetXResolution(int displayID);
private static native double nativeGetYResolution(int displayID);
private native DisplayMode[] nativeGetDisplayModes(int displayID); private static native Insets nativeGetScreenInsets(int displayID);
} }
...@@ -80,10 +80,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig ...@@ -80,10 +80,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig
private ContextCapabilities oglCaps; private ContextCapabilities oglCaps;
private OGLContext context; private OGLContext context;
private final Object disposerReferent = new Object(); private final Object disposerReferent = new Object();
public static native int getDefaultPixFmt(int screennum);
private static native boolean initCGL(); private static native boolean initCGL();
private static native long getCGLConfigInfo(int screennum, int visualnum, private static native long getCGLConfigInfo(int displayID, int visualnum,
int swapInterval); int swapInterval);
private static native int getOGLCapabilities(long configInfo); private static native int getOGLCapabilities(long configInfo);
...@@ -137,15 +135,16 @@ public final class CGLGraphicsConfig extends CGraphicsConfig ...@@ -137,15 +135,16 @@ public final class CGLGraphicsConfig extends CGraphicsConfig
// Java-level context and flush the queue... // Java-level context and flush the queue...
OGLContext.invalidateCurrentContext(); OGLContext.invalidateCurrentContext();
cfginfo = getCGLConfigInfo(device.getCoreGraphicsScreen(), pixfmt, cfginfo = getCGLConfigInfo(device.getCGDisplayID(), pixfmt,
kOpenGLSwapInterval); kOpenGLSwapInterval);
if (cfginfo != 0L) {
OGLContext.setScratchSurface(cfginfo); OGLContext.setScratchSurface(cfginfo);
rq.flushAndInvokeNow(new Runnable() { rq.flushAndInvokeNow(new Runnable() {
public void run() { public void run() {
ids[0] = OGLContext.getOGLIdString(); ids[0] = OGLContext.getOGLIdString();
} }
}); });
}
} finally { } finally {
rq.unlock(); rq.unlock();
} }
...@@ -253,8 +252,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig ...@@ -253,8 +252,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig
@Override @Override
public String toString() { public String toString() {
int screen = getDevice().getCoreGraphicsScreen(); int displayID = getDevice().getCGDisplayID();
return ("CGLGraphicsConfig[dev="+screen+",pixfmt="+pixfmt+"]"); return ("CGLGraphicsConfig[dev="+displayID+",pixfmt="+pixfmt+"]");
} }
@Override @Override
...@@ -413,8 +412,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig ...@@ -413,8 +412,8 @@ public final class CGLGraphicsConfig extends CGraphicsConfig
@Override @Override
public void addDeviceEventListener(AccelDeviceEventListener l) { public void addDeviceEventListener(AccelDeviceEventListener l) {
int screen = getDevice().getCoreGraphicsScreen(); int displayID = getDevice().getCGDisplayID();
AccelDeviceEventNotifier.addListener(l, screen); AccelDeviceEventNotifier.addListener(l, displayID);
} }
@Override @Override
......
...@@ -439,7 +439,7 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent> ...@@ -439,7 +439,7 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
} }
@Override @Override
public final Graphics getGraphics() { public Graphics getGraphics() {
final Graphics g = getOnscreenGraphics(); final Graphics g = getOnscreenGraphics();
if (g != null) { if (g != null) {
synchronized (getPeerTreeLock()){ synchronized (getPeerTreeLock()){
...@@ -1227,10 +1227,10 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent> ...@@ -1227,10 +1227,10 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
} }
protected void sendEventToDelegate(final AWTEvent e) { protected void sendEventToDelegate(final AWTEvent e) {
synchronized (getDelegateLock()) {
if (getDelegate() == null || !isShowing() || !isEnabled()) { if (getDelegate() == null || !isShowing() || !isEnabled()) {
return; return;
} }
synchronized (getDelegateLock()) {
AWTEvent delegateEvent = createDelegateEvent(e); AWTEvent delegateEvent = createDelegateEvent(e);
if (delegateEvent != null) { if (delegateEvent != null) {
AWTAccessor.getComponentAccessor() AWTAccessor.getComponentAccessor()
...@@ -1244,7 +1244,12 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent> ...@@ -1244,7 +1244,12 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
} }
} }
protected AWTEvent createDelegateEvent(AWTEvent e) { /**
* Changes the target of the AWTEvent from awt component to appropriate
* swing delegate.
*/
private AWTEvent createDelegateEvent(final AWTEvent e) {
// TODO modifiers should be changed to getModifiers()|getModifiersEx()?
AWTEvent delegateEvent = null; AWTEvent delegateEvent = null;
if (e instanceof MouseWheelEvent) { if (e instanceof MouseWheelEvent) {
MouseWheelEvent me = (MouseWheelEvent) e; MouseWheelEvent me = (MouseWheelEvent) e;
......
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.dnd.DropTarget;
import sun.awt.CausedFocusEvent;
import sun.awt.LightweightFrame;
public class LWLightweightFramePeer extends LWWindowPeer {
public LWLightweightFramePeer(LightweightFrame target,
PlatformComponent platformComponent,
PlatformWindow platformWindow)
{
super(target, platformComponent, platformWindow, LWWindowPeer.PeerType.LW_FRAME);
}
private LightweightFrame getLwTarget() {
return (LightweightFrame)getTarget();
}
@Override
public Graphics getGraphics() {
return getLwTarget().getGraphics();
}
@Override
protected void setVisibleImpl(final boolean visible) {
}
@Override
public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
if (!focusAllowedFor()) {
return false;
}
if (getPlatformWindow().rejectFocusRequest(cause)) {
return false;
}
Window opposite = LWKeyboardFocusManagerPeer.getInstance().
getCurrentFocusedWindow();
changeFocusedWindow(true, opposite);
return true;
}
@Override
public Point getLocationOnScreen() {
Rectangle bounds = getBounds();
return new Point(bounds.x, bounds.y); // todo
}
@Override
public Insets getInsets() {
return new Insets(0, 0, 0, 0);
}
@Override
public void setBounds(int x, int y, int w, int h, int op) {
setBounds(x, y, w, h, op, true, false);
}
@Override
public void updateCursorImmediately() {
// TODO: tries to switch to the awt/fx toolkit thread and causes a deadlock on macosx
}
@Override
public void addDropTarget(DropTarget dt) {
}
@Override
public void removeDropTarget(DropTarget dt) {
}
@Override
public void grab() {
getLwTarget().grabFocus();
}
@Override
public void ungrab() {
getLwTarget().ungrabFocus();
}
}
...@@ -218,6 +218,23 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { ...@@ -218,6 +218,23 @@ public abstract class LWToolkit extends SunToolkit implements Runnable {
return peer; return peer;
} }
private LWLightweightFramePeer createDelegatedLwPeer(LightweightFrame target,
PlatformComponent platformComponent,
PlatformWindow platformWindow)
{
LWLightweightFramePeer peer = new LWLightweightFramePeer(target, platformComponent, platformWindow);
targetCreatedPeer(target, peer);
peer.initialize();
return peer;
}
@Override
public FramePeer createLightweightFrame(LightweightFrame target) {
PlatformComponent platformComponent = createLwPlatformComponent();
PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.LW_FRAME);
return createDelegatedLwPeer(target, platformComponent, platformWindow);
}
@Override @Override
public WindowPeer createWindow(Window target) { public WindowPeer createWindow(Window target) {
PlatformComponent platformComponent = createPlatformComponent(); PlatformComponent platformComponent = createPlatformComponent();
...@@ -502,6 +519,8 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { ...@@ -502,6 +519,8 @@ public abstract class LWToolkit extends SunToolkit implements Runnable {
protected abstract PlatformComponent createPlatformComponent(); protected abstract PlatformComponent createPlatformComponent();
protected abstract PlatformComponent createLwPlatformComponent();
protected abstract FileDialogPeer createFileDialogPeer(FileDialog target); protected abstract FileDialogPeer createFileDialogPeer(FileDialog target);
// ---- UTILITY METHODS ---- // // ---- UTILITY METHODS ---- //
......
...@@ -48,7 +48,8 @@ public class LWWindowPeer ...@@ -48,7 +48,8 @@ public class LWWindowPeer
FRAME, FRAME,
DIALOG, DIALOG,
EMBEDDED_FRAME, EMBEDDED_FRAME,
VIEW_EMBEDDED_FRAME VIEW_EMBEDDED_FRAME,
LW_FRAME
} }
private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer"); private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer");
...@@ -1090,7 +1091,7 @@ public class LWWindowPeer ...@@ -1090,7 +1091,7 @@ public class LWWindowPeer
return platformWindow.requestWindowFocus(); return platformWindow.requestWindowFocus();
} }
private boolean focusAllowedFor() { protected boolean focusAllowedFor() {
Window window = getTarget(); Window window = getTarget();
// TODO: check if modal blocked // TODO: check if modal blocked
return window.isVisible() && window.isEnabled() && isFocusableWindow(); return window.isVisible() && window.isEnabled() && isFocusableWindow();
...@@ -1113,10 +1114,15 @@ public class LWWindowPeer ...@@ -1113,10 +1114,15 @@ public class LWWindowPeer
return !(window instanceof Dialog || window instanceof Frame); return !(window instanceof Dialog || window instanceof Frame);
} }
@Override
public void emulateActivation(boolean activate) {
changeFocusedWindow(activate, null);
}
/* /*
* Changes focused window on java level. * Changes focused window on java level.
*/ */
private void changeFocusedWindow(boolean becomesFocused, Window opposite) { protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
if (focusLog.isLoggable(PlatformLogger.FINE)) { if (focusLog.isLoggable(PlatformLogger.FINE)) {
focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this); focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
} }
......
...@@ -128,6 +128,15 @@ final class CDropTargetContextPeer extends SunDropTargetContextPeer { ...@@ -128,6 +128,15 @@ final class CDropTargetContextPeer extends SunDropTargetContextPeer {
} }
} }
@Override
protected int postDropTargetEvent(Component component, int x, int y, int dropAction,
int actions, long[] formats, long nativeCtxt, int eventID,
boolean dispatchType) {
// On MacOS X all the DnD events should be synchronous
return super.postDropTargetEvent(component, x, y, dropAction, actions, formats, nativeCtxt,
eventID, SunDropTargetContextPeer.DISPATCH_SYNC);
}
// Signal drop complete: // Signal drop complete:
protected void doDropDone(boolean success, int dropAction, boolean isLocal) { protected void doDropDone(boolean success, int dropAction, boolean isLocal) {
long nativeDropTarget = this.getNativeDragContext(); long nativeDropTarget = this.getNativeDragContext();
......
...@@ -35,7 +35,7 @@ import sun.lwawt.PlatformWindow; ...@@ -35,7 +35,7 @@ import sun.lwawt.PlatformWindow;
* On OSX {@code CPlatformComponent} stores pointer to the native CAlayer which * On OSX {@code CPlatformComponent} stores pointer to the native CAlayer which
* can be used from JAWT. * can be used from JAWT.
*/ */
final class CPlatformComponent extends CFRetainedResource class CPlatformComponent extends CFRetainedResource
implements PlatformComponent { implements PlatformComponent {
private volatile PlatformWindow platformWindow; private volatile PlatformWindow platformWindow;
......
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.lwawt.PlatformWindow;
class CPlatformLWComponent extends CPlatformComponent {
CPlatformLWComponent() {
super();
}
@Override
public long getPointer() {
return 0;
}
@Override
public void initialize(final PlatformWindow platformWindow) {
}
@Override
public void setBounds(final int x, final int y, final int w, final int h) {
}
@Override
public void dispose() {
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.lwawt.LWWindowPeer;
import sun.java2d.SurfaceData;
public class CPlatformLWView extends CPlatformView {
public CPlatformLWView() {
super();
}
@Override
public void initialize(LWWindowPeer peer, CPlatformResponder responder) {
initializeBase(peer, responder);
}
@Override
public long getAWTView() {
return 0;
}
@Override
public boolean isOpaque() {
return true;
}
@Override
public void setBounds(int x, int y, int width, int height) {
}
@Override
public void enterFullScreenMode() {
}
@Override
public void exitFullScreenMode() {
}
@Override
public SurfaceData replaceSurfaceData() {
return null;
}
@Override
public SurfaceData getSurfaceData() {
return null;
}
@Override
public void dispose() {
}
@Override
public long getWindowLayerPtr() {
return 0;
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.Insets;
import java.awt.MenuBar;
import java.awt.Point;
import java.awt.Window;
import sun.awt.CausedFocusEvent;
import sun.java2d.SurfaceData;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformWindow;
public class CPlatformLWWindow extends CPlatformWindow {
@Override
public void initialize(Window target, LWWindowPeer peer, PlatformWindow owner) {
initializeBase(target, peer, owner, new CPlatformLWView());
}
@Override
public void toggleFullScreen() {
}
@Override
public void setMenuBar(MenuBar mb) {
}
@Override
public void dispose() {
}
@Override
public FontMetrics getFontMetrics(Font f) {
return null;
}
@Override
public Insets getInsets() {
return new Insets(0, 0, 0, 0);
}
@Override
public Point getLocationOnScreen() {
return null;
}
@Override
public GraphicsDevice getGraphicsDevice() {
return null;
}
@Override
public SurfaceData getScreenSurface() {
return null;
}
@Override
public SurfaceData replaceSurfaceData() {
return null;
}
@Override
public void setBounds(int x, int y, int w, int h) {
if (getPeer() != null) {
getPeer().notifyReshape(x, y, w, h);
}
}
@Override
public void setVisible(boolean visible) {
}
@Override
public void setTitle(String title) {
}
@Override
public void updateIconImages() {
}
@Override
public long getNSWindowPtr() {
return 0;
}
@Override
public SurfaceData getSurfaceData() {
return null;
}
@Override
public void toBack() {
}
@Override
public void toFront() {
}
@Override
public void setResizable(final boolean resizable) {
}
@Override
public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
}
@Override
public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
return false;
}
@Override
public boolean requestWindowFocus() {
return true;
}
@Override
public boolean isActive() {
return true;
}
@Override
public void updateFocusableWindowState() {
}
@Override
public Graphics transformGraphics(Graphics g) {
return null;
}
@Override
public void setAlwaysOnTop(boolean isAlwaysOnTop) {
}
@Override
public PlatformWindow getTopmostPlatformWindowUnderMouse(){
return null;
}
@Override
public void setOpacity(float opacity) {
}
@Override
public void setOpaque(boolean isOpaque) {
}
@Override
public void enterFullScreenMode() {
}
@Override
public void exitFullScreenMode() {
}
@Override
public void setWindowState(int windowState) {
}
@Override
public LWWindowPeer getPeer() {
return super.getPeer();
}
@Override
public CPlatformView getContentView() {
return super.getContentView();
}
@Override
public long getLayerPtr() {
return 0;
}
}
...@@ -54,8 +54,7 @@ public class CPlatformView extends CFRetainedResource { ...@@ -54,8 +54,7 @@ public class CPlatformView extends CFRetainedResource {
} }
public void initialize(LWWindowPeer peer, CPlatformResponder responder) { public void initialize(LWWindowPeer peer, CPlatformResponder responder) {
this.peer = peer; initializeBase(peer, responder);
this.responder = responder;
if (!LWCToolkit.getSunAwtDisableCALayers()) { if (!LWCToolkit.getSunAwtDisableCALayers()) {
this.windowLayer = new CGLLayer(peer); this.windowLayer = new CGLLayer(peer);
...@@ -63,6 +62,11 @@ public class CPlatformView extends CFRetainedResource { ...@@ -63,6 +62,11 @@ public class CPlatformView extends CFRetainedResource {
setPtr(nativeCreateView(0, 0, 0, 0, getWindowLayerPtr())); setPtr(nativeCreateView(0, 0, 0, 0, getWindowLayerPtr()));
} }
protected void initializeBase(LWWindowPeer peer, CPlatformResponder responder) {
this.peer = peer;
this.responder = responder;
}
public long getAWTView() { public long getAWTView() {
return ptr; return ptr;
} }
......
...@@ -30,6 +30,7 @@ import java.awt.Dialog.ModalityType; ...@@ -30,6 +30,7 @@ import java.awt.Dialog.ModalityType;
import java.awt.event.*; import java.awt.event.*;
import java.awt.peer.WindowPeer; import java.awt.peer.WindowPeer;
import java.beans.*; import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.util.List; import java.util.List;
import javax.swing.*; import javax.swing.*;
...@@ -44,7 +45,7 @@ import com.apple.laf.*; ...@@ -44,7 +45,7 @@ import com.apple.laf.*;
import com.apple.laf.ClientPropertyApplicator.Property; import com.apple.laf.ClientPropertyApplicator.Property;
import com.sun.awt.AWTUtilities; import com.sun.awt.AWTUtilities;
public final class CPlatformWindow extends CFRetainedResource implements PlatformWindow { public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h); private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data); private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr); private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
...@@ -218,11 +219,7 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor ...@@ -218,11 +219,7 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor
*/ */
@Override // PlatformWindow @Override // PlatformWindow
public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) { public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
this.peer = _peer; initializeBase(_target, _peer, _owner, new CPlatformView());
this.target = _target;
if (_owner instanceof CPlatformWindow) {
this.owner = (CPlatformWindow)_owner;
}
final int styleBits = getInitialStyleBits(); final int styleBits = getInitialStyleBits();
...@@ -231,7 +228,6 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor ...@@ -231,7 +228,6 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor
String warningString = target.getWarningString(); String warningString = target.getWarningString();
responder = new CPlatformResponder(peer, false); responder = new CPlatformResponder(peer, false);
contentView = new CPlatformView();
contentView.initialize(peer, responder); contentView.initialize(peer, responder);
final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0); final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
...@@ -253,6 +249,15 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor ...@@ -253,6 +249,15 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor
validateSurface(); validateSurface();
} }
protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
this.peer = peer;
this.target = target;
if (owner instanceof CPlatformWindow) {
this.owner = (CPlatformWindow)owner;
}
this.contentView = view;
}
private int getInitialStyleBits() { private int getInitialStyleBits() {
// defaults style bits // defaults style bits
int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE; int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
...@@ -857,7 +862,16 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor ...@@ -857,7 +862,16 @@ public final class CPlatformWindow extends CFRetainedResource implements Platfor
private void flushBuffers() { private void flushBuffers() {
if (isVisible() && !nativeBounds.isEmpty()) { if (isVisible() && !nativeBounds.isEmpty()) {
LWCToolkit.getLWCToolkit().flushPendingEventsOnAppkit(target); try {
LWCToolkit.invokeAndWait(new Runnable() {
@Override
public void run() {
//Posting an empty to flush the EventQueue without blocking the main thread
}
}, target);
} catch (InterruptedException | InvocationTargetException e) {
e.printStackTrace();
}
} }
} }
......
...@@ -65,7 +65,7 @@ class CRobot implements RobotPeer { ...@@ -65,7 +65,7 @@ class CRobot implements RobotPeer {
mouseLastX = x; mouseLastX = x;
mouseLastY = y; mouseLastY = y;
mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY, mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
mouseButtonsState, true, true); mouseButtonsState, true, true);
} }
...@@ -79,7 +79,7 @@ class CRobot implements RobotPeer { ...@@ -79,7 +79,7 @@ class CRobot implements RobotPeer {
public void mousePress(int buttons) { public void mousePress(int buttons) {
mouseButtonsState |= buttons; mouseButtonsState |= buttons;
mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY, mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
buttons, true, false); buttons, true, false);
} }
...@@ -93,7 +93,7 @@ class CRobot implements RobotPeer { ...@@ -93,7 +93,7 @@ class CRobot implements RobotPeer {
public void mouseRelease(int buttons) { public void mouseRelease(int buttons) {
mouseButtonsState &= ~buttons; mouseButtonsState &= ~buttons;
mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY, mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
buttons, false, false); buttons, false, false);
} }
...@@ -163,7 +163,7 @@ class CRobot implements RobotPeer { ...@@ -163,7 +163,7 @@ class CRobot implements RobotPeer {
} }
private native void initRobot(); private native void initRobot();
private native void mouseEvent(int screen, int lastX, int lastY, private native void mouseEvent(int displayID, int lastX, int lastY,
int buttonsState, int buttonsState,
boolean isButtonsDownState, boolean isButtonsDownState,
boolean isMouseMove); boolean isMouseMove);
......
...@@ -25,27 +25,33 @@ ...@@ -25,27 +25,33 @@
package sun.lwawt.macosx; package sun.lwawt.macosx;
import sun.awt.Mutex;
import sun.awt.datatransfer.ToolkitThreadBlockedHandler; import sun.awt.datatransfer.ToolkitThreadBlockedHandler;
final class CToolkitThreadBlockedHandler implements ToolkitThreadBlockedHandler { final class CToolkitThreadBlockedHandler extends Mutex implements ToolkitThreadBlockedHandler {
private final LWCToolkit toolkit = (LWCToolkit)java.awt.Toolkit.getDefaultToolkit(); private long awtRunLoopMediator = 0;
private final boolean processEvents;
public void lock() { CToolkitThreadBlockedHandler() {
} super();
this.processEvents = true;
public void unlock() {
}
protected boolean isOwned() {
return false;
} }
public void enter() { public void enter() {
// Execute the next AppKit event while we are waiting for system to if (!isOwned()) {
// finish our request - this will save us from biting our own tail throw new IllegalMonitorStateException();
toolkit.executeNextAppKitEvent(); }
awtRunLoopMediator = LWCToolkit.createAWTRunLoopMediator();
unlock();
LWCToolkit.doAWTRunLoop(awtRunLoopMediator, processEvents);
lock();
} }
public void exit() { public void exit() {
if (!isOwned()) {
throw new IllegalMonitorStateException();
}
LWCToolkit.stopAWTRunLoop(awtRunLoopMediator);
awtRunLoopMediator = 0;
} }
} }
/* /*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -63,8 +63,6 @@ public final class LWCToolkit extends LWToolkit { ...@@ -63,8 +63,6 @@ public final class LWCToolkit extends LWToolkit {
private static native void initIDs(); private static native void initIDs();
static native void executeNextAppKitEvent();
private static CInputMethodDescriptor sInputMethodDescriptor; private static CInputMethodDescriptor sInputMethodDescriptor;
static { static {
...@@ -160,6 +158,8 @@ public final class LWCToolkit extends LWToolkit { ...@@ -160,6 +158,8 @@ public final class LWCToolkit extends LWToolkit {
return new CPlatformEmbeddedFrame(); return new CPlatformEmbeddedFrame();
} else if (peerType == PeerType.VIEW_EMBEDDED_FRAME) { } else if (peerType == PeerType.VIEW_EMBEDDED_FRAME) {
return new CViewPlatformEmbeddedFrame(); return new CViewPlatformEmbeddedFrame();
} else if (peerType == PeerType.LW_FRAME) {
return new CPlatformLWWindow();
} else { } else {
assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME); assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME);
return new CPlatformWindow(); return new CPlatformWindow();
...@@ -171,6 +171,11 @@ public final class LWCToolkit extends LWToolkit { ...@@ -171,6 +171,11 @@ public final class LWCToolkit extends LWToolkit {
return new CPlatformComponent(); return new CPlatformComponent();
} }
@Override
protected PlatformComponent createLwPlatformComponent() {
return new CPlatformLWComponent();
}
@Override @Override
protected FileDialogPeer createFileDialogPeer(FileDialog target) { protected FileDialogPeer createFileDialogPeer(FileDialog target) {
return new CFileDialog(target); return new CFileDialog(target);
...@@ -346,22 +351,7 @@ public final class LWCToolkit extends LWToolkit { ...@@ -346,22 +351,7 @@ public final class LWCToolkit extends LWToolkit {
@Override @Override
public Insets getScreenInsets(final GraphicsConfiguration gc) { public Insets getScreenInsets(final GraphicsConfiguration gc) {
final CGraphicsConfig cgc = (CGraphicsConfig) gc; return ((CGraphicsConfig) gc).getDevice().getScreenInsets();
final int displayId = cgc.getDevice().getCoreGraphicsScreen();
Rectangle fullScreen, workArea;
final long screen = CWrapper.NSScreen.screenByDisplayId(displayId);
try {
fullScreen = CWrapper.NSScreen.frame(screen).getBounds();
workArea = CWrapper.NSScreen.visibleFrame(screen).getBounds();
} finally {
CWrapper.NSObject.release(screen);
}
// Convert between Cocoa's coordinate system and Java.
int bottom = workArea.y - fullScreen.y;
int top = fullScreen.height - workArea.height - bottom;
int left = workArea.x - fullScreen.x;
int right = fullScreen.width - workArea.width - left;
return new Insets(top, left, bottom, right);
} }
@Override @Override
...@@ -495,30 +485,6 @@ public final class LWCToolkit extends LWToolkit { ...@@ -495,30 +485,6 @@ public final class LWCToolkit extends LWToolkit {
synchronized(ret) { return ret[0]; } synchronized(ret) { return ret[0]; }
} }
/**
* Just a wrapper for LWCToolkit.invokeAndWait. Posts an empty event to the
* appropriate event queue and waits for it to finish.
*/
public static void flushPendingEventsOnAppkit(final Component component) {
try {
invokeAndWait(new Runnable() {
@Override
public void run() {
}
}, component);
} catch (Exception e) {
e.printStackTrace();
}
}
// Kicks an event over to the appropriate eventqueue and waits for it to finish
// To avoid deadlocking, we manually run the NSRunLoop while waiting
// Any selector invoked using ThreadUtilities performOnMainThread will be processed in doAWTRunLoop
// The CInvocationEvent will call LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual runloop
public static void invokeAndWait(Runnable event, Component component) throws InterruptedException, InvocationTargetException {
invokeAndWait(event, component, true);
}
public static <T> T invokeAndWait(final Callable<T> callable, Component component) throws Exception { public static <T> T invokeAndWait(final Callable<T> callable, Component component) throws Exception {
final CallableWrapper<T> wrapper = new CallableWrapper<T>(callable); final CallableWrapper<T> wrapper = new CallableWrapper<T>(callable);
invokeAndWait(wrapper, component); invokeAndWait(wrapper, component);
...@@ -548,10 +514,27 @@ public final class LWCToolkit extends LWToolkit { ...@@ -548,10 +514,27 @@ public final class LWCToolkit extends LWToolkit {
} }
} }
public static void invokeAndWait(Runnable event, Component component, boolean detectDeadlocks) throws InterruptedException, InvocationTargetException { // Kicks an event over to the appropriate eventqueue and waits for it to finish
long mediator = createAWTRunLoopMediator(); // To avoid deadlocking, we manually run the NSRunLoop while waiting
// Any selector invoked using ThreadUtilities performOnMainThread will be processed in doAWTRunLoop
// The InvocationEvent will call LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual runloop
// Does not dispatch native events while in the loop
public static void invokeAndWait(Runnable event, Component component) throws InterruptedException, InvocationTargetException {
final long mediator = createAWTRunLoopMediator();
InvocationEvent invocationEvent = new CPeerEvent(event, mediator); InvocationEvent invocationEvent =
new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event) {
@Override
public void dispatch() {
try {
super.dispatch();
} finally {
if (mediator != 0) {
stopAWTRunLoop(mediator);
}
}
}
};
if (component != null) { if (component != null) {
AppContext appContext = SunToolkit.targetToAppContext(component); AppContext appContext = SunToolkit.targetToAppContext(component);
...@@ -564,7 +547,7 @@ public final class LWCToolkit extends LWToolkit { ...@@ -564,7 +547,7 @@ public final class LWCToolkit extends LWToolkit {
((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent); ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent);
} }
doAWTRunLoop(mediator, true, detectDeadlocks); doAWTRunLoop(mediator, false);
Throwable eventException = invocationEvent.getException(); Throwable eventException = invocationEvent.getException();
if (eventException != null) { if (eventException != null) {
...@@ -576,7 +559,8 @@ public final class LWCToolkit extends LWToolkit { ...@@ -576,7 +559,8 @@ public final class LWCToolkit extends LWToolkit {
} }
public static void invokeLater(Runnable event, Component component) throws InvocationTargetException { public static void invokeLater(Runnable event, Component component) throws InvocationTargetException {
final InvocationEvent invocationEvent = new CPeerEvent(event, 0); final InvocationEvent invocationEvent =
new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event);
if (component != null) { if (component != null) {
final AppContext appContext = SunToolkit.targetToAppContext(component); final AppContext appContext = SunToolkit.targetToAppContext(component);
...@@ -681,31 +665,6 @@ public final class LWCToolkit extends LWToolkit { ...@@ -681,31 +665,6 @@ public final class LWCToolkit extends LWToolkit {
return false; return false;
} }
// Extends PeerEvent because we want to pass long an ObjC mediator object and because we want these events to be posted early
// Typically, rather than relying on the notifier to call notifyAll(), we use the mediator to stop the runloop
public static class CPeerEvent extends PeerEvent {
private long _mediator = 0;
public CPeerEvent(Runnable runnable, long mediator) {
super(Toolkit.getDefaultToolkit(), runnable, null, true, 0);
_mediator = mediator;
}
public void dispatch() {
try {
super.dispatch();
} finally {
if (_mediator != 0) {
LWCToolkit.stopAWTRunLoop(_mediator);
}
}
}
}
// Call through to native methods
public static void doAWTRunLoop(long mediator, boolean awtMode) { doAWTRunLoop(mediator, awtMode, true); }
public static void doAWTRunLoop(long mediator) { doAWTRunLoop(mediator, true); }
private static Boolean sunAwtDisableCALayers = null; private static Boolean sunAwtDisableCALayers = null;
/** /**
...@@ -730,12 +689,20 @@ public final class LWCToolkit extends LWToolkit { ...@@ -730,12 +689,20 @@ public final class LWCToolkit extends LWToolkit {
* Native methods section * Native methods section
************************/ ************************/
// These are public because they are accessed from WebKitPluginObject in JavaDeploy static native long createAWTRunLoopMediator();
// Basic usage: /**
// createAWTRunLoopMediator. Start client code on another thread. doAWTRunLoop. When client code is finished, stopAWTRunLoop. * Method to run a nested run-loop. The nested loop is spinned in the javaRunLoop mode, so selectors sent
public static native long createAWTRunLoopMediator(); * by [JNFRunLoop performOnMainThreadWaiting] are processed.
public static native void doAWTRunLoop(long mediator, boolean awtMode, boolean detectDeadlocks); * @param mediator a native pointer to the mediator object created by createAWTRunLoopMediator
public static native void stopAWTRunLoop(long mediator); * @param processEvents if true - dispatches event while in the nested loop. Used in DnD.
* Additional attention is needed when using this feature as we short-circuit normal event
* processing which could break Appkit.
* (One known example is when the window is resized with the mouse)
*
* if false - all events come after exit form the nested loop
*/
static native void doAWTRunLoop(long mediator, boolean processEvents);
static native void stopAWTRunLoop(long mediator);
private native boolean nativeSyncQueue(long timeout); private native boolean nativeSyncQueue(long timeout);
......
...@@ -668,7 +668,7 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -668,7 +668,7 @@ AWT_ASSERT_APPKIT_THREAD;
- (void) setDropTarget:(CDropTarget *)target { - (void) setDropTarget:(CDropTarget *)target {
self._dropTarget = target; self._dropTarget = target;
[ThreadUtilities performOnMainThread:@selector(controlModelControlValid) onObject:self._dropTarget withObject:nil waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(controlModelControlValid) on:self._dropTarget withObject:nil waitUntilDone:YES];
} }
/******************************** BEGIN NSDraggingSource Interface ********************************/ /******************************** BEGIN NSDraggingSource Interface ********************************/
...@@ -1215,7 +1215,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); ...@@ -1215,7 +1215,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod");
fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n"); fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n");
#endif // IM_DEBUG #endif // IM_DEBUG
[ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) onObject:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) on:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES];
[self unmarkText]; [self unmarkText];
} }
......
...@@ -567,10 +567,9 @@ JNIEXPORT void JNICALL Java_com_apple_eawt__1AppEventHandler_nativeRegisterForNo ...@@ -567,10 +567,9 @@ JNIEXPORT void JNICALL Java_com_apple_eawt__1AppEventHandler_nativeRegisterForNo
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(_registerForNotification:) [ThreadUtilities performOnMainThread:@selector(_registerForNotification:)
onObject:[ApplicationDelegate class] on:[ApplicationDelegate class]
withObject:[NSNumber numberWithInt:notificationType] withObject:[NSNumber numberWithInt:notificationType]
waitUntilDone:NO waitUntilDone:NO]; // AWT_THREADING Safe (non-blocking)
awtMode:NO]; // AWT_THREADING Safe (non-blocking)
JNF_COCOA_EXIT(env); JNF_COCOA_EXIT(env);
} }
......
...@@ -120,7 +120,7 @@ static CClipboard *sClipboard = nil; ...@@ -120,7 +120,7 @@ static CClipboard *sClipboard = nil;
fClipboardOwner = JNFNewGlobalRef(inEnv, inClipboard); fClipboardOwner = JNFNewGlobalRef(inEnv, inClipboard);
} }
} }
[ThreadUtilities performOnMainThread:@selector(_nativeDeclareTypes:) onObject:self withObject:inTypes waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_nativeDeclareTypes:) on:self withObject:inTypes waitUntilDone:YES];
} }
- (void) _nativeDeclareTypes:(NSArray *)inTypes { - (void) _nativeDeclareTypes:(NSArray *)inTypes {
...@@ -135,7 +135,7 @@ static CClipboard *sClipboard = nil; ...@@ -135,7 +135,7 @@ static CClipboard *sClipboard = nil;
- (NSArray *) javaGetTypes { - (NSArray *) javaGetTypes {
NSMutableArray *args = [NSMutableArray arrayWithCapacity:1]; NSMutableArray *args = [NSMutableArray arrayWithCapacity:1];
[ThreadUtilities performOnMainThread:@selector(_nativeGetTypes:) onObject:self withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_nativeGetTypes:) on:self withObject:args waitUntilDone:YES];
//NSLog(@"CClipboard getTypes returns %@", [args lastObject]); //NSLog(@"CClipboard getTypes returns %@", [args lastObject]);
return [args lastObject]; return [args lastObject];
...@@ -152,7 +152,7 @@ static CClipboard *sClipboard = nil; ...@@ -152,7 +152,7 @@ static CClipboard *sClipboard = nil;
- (void) javaSetData:(NSData *)inData forType:(NSString *) inFormat { - (void) javaSetData:(NSData *)inData forType:(NSString *) inFormat {
CClipboardUpdate *newUpdate = [[CClipboardUpdate alloc] initWithData:inData withFormat:inFormat]; CClipboardUpdate *newUpdate = [[CClipboardUpdate alloc] initWithData:inData withFormat:inFormat];
[ThreadUtilities performOnMainThread:@selector(_nativeSetData:) onObject:self withObject:newUpdate waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_nativeSetData:) on:self withObject:newUpdate waitUntilDone:YES];
[newUpdate release]; [newUpdate release];
//NSLog(@"CClipboard javaSetData forType %@", inFormat); //NSLog(@"CClipboard javaSetData forType %@", inFormat);
...@@ -170,7 +170,7 @@ static CClipboard *sClipboard = nil; ...@@ -170,7 +170,7 @@ static CClipboard *sClipboard = nil;
- (NSData *) javaGetDataForType:(NSString *) inFormat { - (NSData *) javaGetDataForType:(NSString *) inFormat {
NSMutableArray *args = [NSMutableArray arrayWithObject:inFormat]; NSMutableArray *args = [NSMutableArray arrayWithObject:inFormat];
[ThreadUtilities performOnMainThread:@selector(_nativeGetDataForType:) onObject:self withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_nativeGetDataForType:) on:self withObject:args waitUntilDone:YES];
//NSLog(@"CClipboard javaGetDataForType %@ returns an NSData", inFormat); //NSLog(@"CClipboard javaGetDataForType %@ returns an NSData", inFormat);
return [args lastObject]; return [args lastObject];
......
...@@ -390,8 +390,7 @@ extern JNFClassInfo jc_CDropTargetContextPeer; ...@@ -390,8 +390,7 @@ extern JNFClassInfo jc_CDropTargetContextPeer;
// Release dragging data if any when Java's AWT event thread is all finished. // Release dragging data if any when Java's AWT event thread is all finished.
// Make sure dragging data is released on the native event thread. // Make sure dragging data is released on the native event thread.
[ThreadUtilities performOnMainThread:@selector(safeReleaseDraggingData:) onObject:self [ThreadUtilities performOnMainThread:@selector(safeReleaseDraggingData:) on:self withObject:draggingSequenceNumberID waitUntilDone:NO];
withObject:draggingSequenceNumberID waitUntilDone:NO awtMode:NO];
} }
- (jint)currentJavaActions { - (jint)currentJavaActions {
......
/* /*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
* questions. * questions.
*/ */
#include "LWCToolkit.h" #import "LWCToolkit.h"
#import "ThreadUtilities.h"
/* /*
* Convert the mode string to the more convinient bits per pixel value * Convert the mode string to the more convinient bits per pixel value
...@@ -146,6 +147,47 @@ Java_sun_awt_CGraphicsDevice_nativeGetYResolution ...@@ -146,6 +147,47 @@ Java_sun_awt_CGraphicsDevice_nativeGetYResolution
return dpi; return dpi;
} }
/*
* Class: sun_awt_CGraphicsDevice
* Method: nativeGetScreenInsets
* Signature: (I)D
*/
JNIEXPORT jobject JNICALL
Java_sun_awt_CGraphicsDevice_nativeGetScreenInsets
(JNIEnv *env, jclass class, jint displayID)
{
jobject ret = NULL;
__block NSRect frame = NSZeroRect;
__block NSRect visibleFrame = NSZeroRect;
JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
NSArray *screens = [NSScreen screens];
for (NSScreen *screen in screens) {
NSDictionary *screenInfo = [screen deviceDescription];
NSNumber *screenID = [screenInfo objectForKey:@"NSScreenNumber"];
if ([screenID pointerValue] == displayID){
frame = [screen frame];
visibleFrame = [screen visibleFrame];
break;
}
}
}];
// Convert between Cocoa's coordinate system and Java.
jint bottom = visibleFrame.origin.y - frame.origin.y;
jint top = frame.size.height - visibleFrame.size.height - bottom;
jint left = visibleFrame.origin.x - frame.origin.x;
jint right = frame.size.width - visibleFrame.size.width - left;
static JNF_CLASS_CACHE(jc_Insets, "java/awt/Insets");
static JNF_CTOR_CACHE(jc_Insets_ctor, jc_Insets, "(IIII)V");
ret = JNFNewObject(env, jc_Insets_ctor, top, left, bottom, right);
JNF_COCOA_EXIT(env);
return ret;
}
/* /*
* Class: sun_awt_CGraphicsDevice * Class: sun_awt_CGraphicsDevice
* Method: nativeSetDisplayMode * Method: nativeSetDisplayMode
......
...@@ -55,11 +55,11 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -55,11 +55,11 @@ AWT_ASSERT_APPKIT_THREAD;
//- (void)finalize { [super finalize]; } //- (void)finalize { [super finalize]; }
- (void)addJavaSubmenu:(CMenu *)submenu { - (void)addJavaSubmenu:(CMenu *)submenu {
[ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) onObject:self withObject:submenu waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) on:self withObject:submenu waitUntilDone:YES];
} }
- (void)addJavaMenuItem:(CMenuItem *)theMenuItem { - (void)addJavaMenuItem:(CMenuItem *)theMenuItem {
[ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) onObject:self withObject:theMenuItem waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) on:self withObject:theMenuItem waitUntilDone:YES];
} }
- (void)addNativeItem_OnAppKitThread:(CMenuItem *)itemModified { - (void)addNativeItem_OnAppKitThread:(CMenuItem *)itemModified {
...@@ -70,7 +70,7 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -70,7 +70,7 @@ AWT_ASSERT_APPKIT_THREAD;
- (void)setJavaMenuTitle:(NSString *)title { - (void)setJavaMenuTitle:(NSString *)title {
if (title) { if (title) {
[ThreadUtilities performOnMainThread:@selector(setNativeMenuTitle_OnAppKitThread:) onObject:self withObject:title waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(setNativeMenuTitle_OnAppKitThread:) on:self withObject:title waitUntilDone:YES];
} }
} }
...@@ -93,7 +93,7 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -93,7 +93,7 @@ AWT_ASSERT_APPKIT_THREAD;
- (void)deleteJavaItem:(jint)index { - (void)deleteJavaItem:(jint)index {
[ThreadUtilities performOnMainThread:@selector(deleteNativeJavaItem_OnAppKitThread:) onObject:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(deleteNativeJavaItem_OnAppKitThread:) on:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES];
} }
- (void)deleteNativeJavaItem_OnAppKitThread:(NSNumber *)number { - (void)deleteNativeJavaItem_OnAppKitThread:(NSNumber *)number {
...@@ -139,7 +139,7 @@ CMenu * createCMenu (jobject cPeerObjGlobal) { ...@@ -139,7 +139,7 @@ CMenu * createCMenu (jobject cPeerObjGlobal) {
// We use an array here only to be able to get a return value // We use an array here only to be able to get a return value
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil]; NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
[ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) onObject:[CMenu alloc] withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenu alloc] withObject:args waitUntilDone:YES];
aCMenu = (CMenu *)[args objectAtIndex: 0]; aCMenu = (CMenu *)[args objectAtIndex: 0];
......
...@@ -197,7 +197,7 @@ static BOOL sSetupHelpMenu = NO; ...@@ -197,7 +197,7 @@ static BOOL sSetupHelpMenu = NO;
if (self == sActiveMenuBar) { if (self == sActiveMenuBar) {
NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:-1], nil]; NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:-1], nil];
[ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) onObject:self withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) on:self withObject:args waitUntilDone:YES];
[args release]; [args release];
} }
} }
...@@ -216,7 +216,7 @@ static BOOL sSetupHelpMenu = NO; ...@@ -216,7 +216,7 @@ static BOOL sSetupHelpMenu = NO;
if (self == sActiveMenuBar) { if (self == sActiveMenuBar) {
NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:index], nil]; NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:index], nil];
[ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) onObject:self withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) on:self withObject:args waitUntilDone:YES];
[args release]; [args release];
} }
} }
...@@ -286,7 +286,7 @@ static BOOL sSetupHelpMenu = NO; ...@@ -286,7 +286,7 @@ static BOOL sSetupHelpMenu = NO;
- (void) javaDeleteMenu: (jint)index { - (void) javaDeleteMenu: (jint)index {
if (self == sActiveMenuBar) { if (self == sActiveMenuBar) {
[ThreadUtilities performOnMainThread:@selector(nativeDeleteMenu_OnAppKitThread:) onObject:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(nativeDeleteMenu_OnAppKitThread:) on:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES];
} }
@synchronized(self) { @synchronized(self) {
...@@ -388,7 +388,7 @@ Java_sun_lwawt_macosx_CMenuBar_nativeCreateMenuBar ...@@ -388,7 +388,7 @@ Java_sun_lwawt_macosx_CMenuBar_nativeCreateMenuBar
// We use an array here only to be able to get a return value // We use an array here only to be able to get a return value
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil]; NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
[ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) onObject:[CMenuBar alloc] withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenuBar alloc] withObject:args waitUntilDone:YES];
aCMenuBar = (CMenuBar *)[args objectAtIndex: 0]; aCMenuBar = (CMenuBar *)[args objectAtIndex: 0];
......
...@@ -386,7 +386,7 @@ JNF_COCOA_ENTER(env); ...@@ -386,7 +386,7 @@ JNF_COCOA_ENTER(env);
args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO], nil]; args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO], nil];
} }
[ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) onObject:[CMenuItem alloc] withObject:args waitUntilDone:YES awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) on:[CMenuItem alloc] withObject:args waitUntilDone:YES];
aCMenuItem = (CMenuItem *)[args objectAtIndex: 0]; aCMenuItem = (CMenuItem *)[args objectAtIndex: 0];
......
...@@ -135,7 +135,7 @@ Java_sun_lwawt_macosx_CRobot_initRobot ...@@ -135,7 +135,7 @@ Java_sun_lwawt_macosx_CRobot_initRobot
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_mouseEvent Java_sun_lwawt_macosx_CRobot_mouseEvent
(JNIEnv *env, jobject peer, (JNIEnv *env, jobject peer,
jint screenIndex, jint mouseLastX, jint mouseLastY, jint buttonsState, jint displayID, jint mouseLastX, jint mouseLastY, jint buttonsState,
jboolean isButtonsDownState, jboolean isMouseMove) jboolean isButtonsDownState, jboolean isMouseMove)
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
...@@ -149,8 +149,6 @@ Java_sun_lwawt_macosx_CRobot_mouseEvent ...@@ -149,8 +149,6 @@ Java_sun_lwawt_macosx_CRobot_mouseEvent
CGError err = kCGErrorSuccess; CGError err = kCGErrorSuccess;
CGDirectDisplayID displayID =
FindCGDirectDisplayIDForScreenIndex(screenIndex);
CGRect globalDeviceBounds = CGDisplayBounds(displayID); CGRect globalDeviceBounds = CGDisplayBounds(displayID);
// Set unknown mouse location, if needed. // Set unknown mouse location, if needed.
......
...@@ -1113,20 +1113,12 @@ static NSObject *sAttributeNamesLOCK = nil; ...@@ -1113,20 +1113,12 @@ static NSObject *sAttributeNamesLOCK = nil;
JNIEnv *env = [ThreadUtilities getJNIEnv]; JNIEnv *env = [ThreadUtilities getJNIEnv];
id value = nil; id value = nil;
// This code frequently gets called indirectly by Java when VoiceOver is active.
// Basically, we just have to know when we going to be a bad state, and do something "special".
// Note that while NSApplication isn't technically correct, we post a focus changed notification
// (which will call this method, but with the correct codepath) shortly afterwards. See +postFocusChanged.
if (sInPerformFromJava) {
return [NSApplication sharedApplication];
} else {
jobject focused = JNFCallStaticObjectMethod(env, jm_getFocusOwner, fComponent); // AWT_THREADING Safe (AWTRunLoop) jobject focused = JNFCallStaticObjectMethod(env, jm_getFocusOwner, fComponent); // AWT_THREADING Safe (AWTRunLoop)
if (focused != NULL) { if (focused != NULL) {
if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) { if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) {
value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView]; value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView];
} }
} }
}
if (value == nil) { if (value == nil) {
value = self; value = self;
...@@ -1149,7 +1141,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessibility_focusChanged ...@@ -1149,7 +1141,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessibility_focusChanged
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(postFocusChanged:) onObject:[JavaComponentAccessibility class] withObject:nil waitUntilDone:NO awtMode:NO]; [ThreadUtilities performOnMainThread:@selector(postFocusChanged:) on:[JavaComponentAccessibility class] withObject:nil waitUntilDone:NO];
JNF_COCOA_EXIT(env); JNF_COCOA_EXIT(env);
} }
...@@ -1164,7 +1156,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_valueChanged ...@@ -1164,7 +1156,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_valueChanged
(JNIEnv *env, jclass jklass, jlong element) (JNIEnv *env, jclass jklass, jlong element)
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(postValueChanged) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO]; [ThreadUtilities performOnMainThread:@selector(postValueChanged) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
JNF_COCOA_EXIT(env); JNF_COCOA_EXIT(env);
} }
...@@ -1177,7 +1169,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_selectionChanged ...@@ -1177,7 +1169,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_selectionChanged
(JNIEnv *env, jclass jklass, jlong element) (JNIEnv *env, jclass jklass, jlong element)
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(postSelectionChanged) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO]; [ThreadUtilities performOnMainThread:@selector(postSelectionChanged) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
JNF_COCOA_EXIT(env); JNF_COCOA_EXIT(env);
} }
...@@ -1191,7 +1183,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_unregisterFromCocoaAXSy ...@@ -1191,7 +1183,7 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_unregisterFromCocoaAXSy
(JNIEnv *env, jclass jklass, jlong element) (JNIEnv *env, jclass jklass, jlong element)
{ {
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(unregisterFromCocoaAXSystem) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO]; [ThreadUtilities performOnMainThread:@selector(unregisterFromCocoaAXSystem) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
JNF_COCOA_EXIT(env); JNF_COCOA_EXIT(env);
} }
......
...@@ -44,8 +44,6 @@ extern jint* gButtonDownMasks; ...@@ -44,8 +44,6 @@ extern jint* gButtonDownMasks;
+ (void) eventCountPlusPlus; + (void) eventCountPlusPlus;
@end @end
CGDirectDisplayID FindCGDirectDisplayIDForScreenIndex(jint screenIndex);
/* /*
* Utility Macros * Utility Macros
*/ */
......
...@@ -177,39 +177,6 @@ Java_sun_lwawt_macosx_LWCToolkit_beep ...@@ -177,39 +177,6 @@ Java_sun_lwawt_macosx_LWCToolkit_beep
NSBeep(); // produces both sound and visual flash, if configured in System Preferences NSBeep(); // produces both sound and visual flash, if configured in System Preferences
} }
CGDirectDisplayID
FindCGDirectDisplayIDForScreenIndex(jint screenIndex)
{
// most common case - just one monitor
CGDirectDisplayID screenID = CGMainDisplayID();
CGDisplayCount displayCount = 0;
CGGetOnlineDisplayList(0, NULL, &displayCount);
if ((displayCount > 1) &&
(screenIndex >= 0) &&
(screenIndex < (jint)displayCount))
{
if (displayCount < 10) {
// stack allocated optimization for less than 10 monitors
CGDirectDisplayID onlineDisplays[displayCount];
CGGetOnlineDisplayList(displayCount, onlineDisplays, &displayCount);
screenID = (CGDirectDisplayID)onlineDisplays[screenIndex];
} else {
CGDirectDisplayID *onlineDisplays =
malloc(displayCount*sizeof(CGDirectDisplayID));
if (onlineDisplays != NULL) {
CGGetOnlineDisplayList(displayCount, onlineDisplays,
&displayCount);
screenID = (CGDirectDisplayID)onlineDisplays[screenIndex];
free(onlineDisplays);
}
}
}
return screenID;
}
/* /*
* Class: sun_lwawt_macosx_LWCToolkit * Class: sun_lwawt_macosx_LWCToolkit
* Method: initIDs * Method: initIDs
...@@ -332,7 +299,7 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -332,7 +299,7 @@ AWT_ASSERT_APPKIT_THREAD;
* Signature: (JZZ)V * Signature: (JZZ)V
*/ */
JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_doAWTRunLoop JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_doAWTRunLoop
(JNIEnv *env, jclass clz, jlong mediator, jboolean awtMode, jboolean detectDeadlocks) (JNIEnv *env, jclass clz, jlong mediator, jboolean processEvents)
{ {
AWT_ASSERT_APPKIT_THREAD; AWT_ASSERT_APPKIT_THREAD;
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
...@@ -341,25 +308,24 @@ JNF_COCOA_ENTER(env); ...@@ -341,25 +308,24 @@ JNF_COCOA_ENTER(env);
if (mediatorObject == nil) return; if (mediatorObject == nil) return;
if (!sInPerformFromJava || !detectDeadlocks) {
NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
NSDate *distantFuture = [NSDate distantFuture];
NSString *mode = (awtMode) ? [JNFRunLoop javaRunLoopMode] : NSDefaultRunLoopMode;
BOOL isRunning = YES;
while (isRunning && ![mediatorObject shouldEndRunLoop]) {
// Don't use acceptInputForMode because that doesn't setup autorelease pools properly // Don't use acceptInputForMode because that doesn't setup autorelease pools properly
isRunning = [currentRunLoop runMode:mode beforeDate:distantFuture]; BOOL isRunning = true;
while (![mediatorObject shouldEndRunLoop] && isRunning) {
isRunning = [[NSRunLoop currentRunLoop] runMode:[JNFRunLoop javaRunLoopMode]
beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.010]];
if (processEvents) {
//We do not spin a runloop here as date is nil, so does not matter which mode to use
NSEvent *event;
if ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
untilDate:nil
inMode:NSDefaultRunLoopMode
dequeue:YES]) != nil) {
[NSApp sendEvent:event];
} }
} }
#ifndef PRODUCT_BUILD
if (sInPerformFromJava) {
NSLog(@"Apple AWT: Short-circuiting CToolkit.invokeAndWait trampoline deadlock!!!!!");
NSLog(@"\tPlease file a bug report with this message and a reproducible test case.");
} }
#endif
CFRelease(mediatorObject); CFRelease(mediatorObject);
...@@ -379,7 +345,7 @@ JNF_COCOA_ENTER(env); ...@@ -379,7 +345,7 @@ JNF_COCOA_ENTER(env);
AWTRunLoopObject* mediatorObject = (AWTRunLoopObject*)jlong_to_ptr(mediator); AWTRunLoopObject* mediatorObject = (AWTRunLoopObject*)jlong_to_ptr(mediator);
[ThreadUtilities performOnMainThread:@selector(endRunLoop) onObject:mediatorObject withObject:nil waitUntilDone:NO awtMode:YES]; [ThreadUtilities performOnMainThread:@selector(endRunLoop) on:mediatorObject withObject:nil waitUntilDone:NO];
CFRelease(mediatorObject); CFRelease(mediatorObject);
...@@ -463,20 +429,3 @@ Java_sun_font_FontManager_populateFontFileNameMap ...@@ -463,20 +429,3 @@ Java_sun_font_FontManager_populateFontFileNameMap
} }
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: executeNextAppKitEvent
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_executeNextAppKitEvent
(JNIEnv *env, jclass cls)
{
// Simply get the next event in native loop and pass it to execution
// We'll be called repeatedly so there's no need to block here
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
NSApplication * app = [NSApplication sharedApplication];
NSEvent * event = [app nextEventMatchingMask: 0xFFFFFFFF untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
if (event != nil) {
[app sendEvent: event];
}
}
...@@ -192,12 +192,12 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_initCGL ...@@ -192,12 +192,12 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_initCGL
JNIEXPORT jlong JNICALL JNIEXPORT jlong JNICALL
Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
(JNIEnv *env, jclass cglgc, (JNIEnv *env, jclass cglgc,
jint screennum, jint pixfmt, jint swapInterval) jint displayID, jint pixfmt, jint swapInterval)
{ {
jlong ret = 0L; jlong ret = 0L;
JNF_COCOA_ENTER(env); JNF_COCOA_ENTER(env);
NSMutableArray * retArray = [NSMutableArray arrayWithCapacity:3]; NSMutableArray * retArray = [NSMutableArray arrayWithCapacity:3];
[retArray addObject: [NSNumber numberWithInt: (int)screennum]]; [retArray addObject: [NSNumber numberWithInt: (int)displayID]];
[retArray addObject: [NSNumber numberWithInt: (int)pixfmt]]; [retArray addObject: [NSNumber numberWithInt: (int)pixfmt]];
[retArray addObject: [NSNumber numberWithInt: (int)swapInterval]]; [retArray addObject: [NSNumber numberWithInt: (int)swapInterval]];
if ([NSThread isMainThread]) { if ([NSThread isMainThread]) {
...@@ -217,7 +217,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo ...@@ -217,7 +217,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
+ (void) _getCGLConfigInfo: (NSMutableArray *)argValue { + (void) _getCGLConfigInfo: (NSMutableArray *)argValue {
AWT_ASSERT_APPKIT_THREAD; AWT_ASSERT_APPKIT_THREAD;
jint screennum = (jint)[(NSNumber *)[argValue objectAtIndex: 0] intValue]; jint displayID = (jint)[(NSNumber *)[argValue objectAtIndex: 0] intValue];
jint pixfmt = (jint)[(NSNumber *)[argValue objectAtIndex: 1] intValue]; jint pixfmt = (jint)[(NSNumber *)[argValue objectAtIndex: 1] intValue];
jint swapInterval = (jint)[(NSNumber *)[argValue objectAtIndex: 2] intValue]; jint swapInterval = (jint)[(NSNumber *)[argValue objectAtIndex: 2] intValue];
JNIEnv *env = [ThreadUtilities getJNIEnvUncached]; JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
...@@ -230,16 +230,11 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo ...@@ -230,16 +230,11 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
CGOpenGLDisplayMask glMask = (CGOpenGLDisplayMask)pixfmt; CGOpenGLDisplayMask glMask = (CGOpenGLDisplayMask)pixfmt;
if (sharedContext == NULL) { if (sharedContext == NULL) {
if (glMask == 0) { if (glMask == 0) {
CGDirectDisplayID id = glMask = CGDisplayIDToOpenGLDisplayMask(displayID);
FindCGDirectDisplayIDForScreenIndex(screennum);
glMask = CGDisplayIDToOpenGLDisplayMask(id);
} }
NSOpenGLPixelFormatAttribute attrs[] = { NSOpenGLPixelFormatAttribute attrs[] = {
NSOpenGLPFAClosestPolicy, NSOpenGLPFAClosestPolicy,
NSOpenGLPFANoRecovery,
NSOpenGLPFAAccelerated,
NSOpenGLPFAFullScreen,
NSOpenGLPFAWindow, NSOpenGLPFAWindow,
NSOpenGLPFAPixelBuffer, NSOpenGLPFAPixelBuffer,
NSOpenGLPFADoubleBuffer, NSOpenGLPFADoubleBuffer,
...@@ -412,7 +407,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo ...@@ -412,7 +407,7 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
return; return;
} }
memset(cglinfo, 0, sizeof(CGLGraphicsConfigInfo)); memset(cglinfo, 0, sizeof(CGLGraphicsConfigInfo));
cglinfo->screen = screennum; cglinfo->screen = displayID;
cglinfo->pixfmt = sharedPixelFormat; cglinfo->pixfmt = sharedPixelFormat;
cglinfo->context = oglc; cglinfo->context = oglc;
...@@ -422,17 +417,6 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo ...@@ -422,17 +417,6 @@ Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
} }
@end //GraphicsConfigUtil @end //GraphicsConfigUtil
JNIEXPORT jint JNICALL
Java_sun_java2d_opengl_CGLGraphicsConfig_getDefaultPixFmt
(JNIEnv *env, jclass cglgc, jint screennum)
{
J2dTraceLn(J2D_TRACE_INFO, "CGLGraphicsConfig_getDefaultPixFmt");
CGDirectDisplayID id = FindCGDirectDisplayIDForScreenIndex(screennum);
return (jint)CGDisplayIDToOpenGLDisplayMask(id);
}
JNIEXPORT jint JNICALL JNIEXPORT jint JNICALL
Java_sun_java2d_opengl_CGLGraphicsConfig_getOGLCapabilities Java_sun_java2d_opengl_CGLGraphicsConfig_getOGLCapabilities
(JNIEnv *env, jclass cglgc, jlong configInfo) (JNIEnv *env, jclass cglgc, jlong configInfo)
......
...@@ -122,19 +122,12 @@ do { \ ...@@ -122,19 +122,12 @@ do { \
#endif /* AWT_THREAD_ASSERTS */ #endif /* AWT_THREAD_ASSERTS */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// This tracks if we are current inside of a performOnMainThread that is both waiting and in the AWTRunLoopMode
extern BOOL sInPerformFromJava;
// This is an empty Obj-C object just so that -performSelectorOnMainThread
// can be used, and to use the Obj-C +initialize feature.
__attribute__((visibility("default"))) __attribute__((visibility("default")))
@interface ThreadUtilities : NSObject { } @interface ThreadUtilities { }
+ (JNIEnv*)getJNIEnv; + (JNIEnv*)getJNIEnv;
+ (JNIEnv*)getJNIEnvUncached; + (JNIEnv*)getJNIEnvUncached;
+ (void)performOnMainThread:(SEL)aSelector onObject:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait awtMode:(BOOL)inAWT;
//Wrappers for the corresponding JNFRunLoop methods with a check for main thread //Wrappers for the corresponding JNFRunLoop methods with a check for main thread
+ (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block; + (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block;
+ (void)performOnMainThread:(SEL)aSelector on:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait; + (void)performOnMainThread:(SEL)aSelector on:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait;
......
...@@ -34,85 +34,6 @@ ...@@ -34,85 +34,6 @@
JavaVM *jvm = NULL; JavaVM *jvm = NULL;
static JNIEnv *appKitEnv = NULL; static JNIEnv *appKitEnv = NULL;
static NSArray *sPerformModes = nil;
static NSArray *sAWTPerformModes = nil;
static BOOL sLoggingEnabled = YES;
#ifdef AWT_THREAD_ASSERTS_ENV_ASSERT
int sAWTThreadAsserts = 0;
#endif /* AWT_THREAD_ASSERTS_ENV_ASSERT */
BOOL sInPerformFromJava = NO;
// This class is used so that performSelectorOnMainThread can be
// controlled a little more easily by us. It has 2 roles.
// The first is to set/unset a flag (sInPerformFromJava) that code can
// check to see if we are in a synchronous perform initiated by a java thread.
// The second is to implement the CocoaComponent backward compatibility mode.
@interface CPerformer : NSObject {
id fTarget;
SEL fSelector;
id fArg;
BOOL fWait;
}
- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg wait:(BOOL)wait;
- (void) perform;
@end
@implementation CPerformer
- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg {
return [self initWithTarget:target selector:selector arg:arg wait:YES];
}
- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg wait:(BOOL)wait {
self = [super init];
if (self != nil) {
fTarget = [target retain];
fSelector = selector;
fArg = [arg retain];
// Only set sInPerformFromJava if this is a synchronous perform
fWait = wait;
}
return self;
}
- (void) dealloc {
[fTarget release];
[fArg release];
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (void) perform {
AWT_ASSERT_APPKIT_THREAD;
// If this is the first time we're going from java thread -> appkit thread,
// set sInPerformFromJava for the duration of the invocation
BOOL nestedPerform = sInPerformFromJava;
if (fWait) {
sInPerformFromJava = YES;
}
// Actually do the work (cheat to avoid a method call)
@try {
objc_msgSend(fTarget, fSelector, fArg);
//[fTarget performSelector:fSelector withObject:fArg];
} @catch (NSException *e) {
NSLog(@"*** CPerformer: ignoring exception '%@' raised during perform of selector '%@' on target '%@' with args '%@'", e, NSStringFromSelector(fSelector), fTarget, fArg);
} @finally {
// If we actually set sInPerformFromJava, unset it now
if (!nestedPerform && fWait) {
sInPerformFromJava = NO;
}
}
}
@end
@implementation ThreadUtilities @implementation ThreadUtilities
+ (JNIEnv*)getJNIEnv { + (JNIEnv*)getJNIEnv {
...@@ -129,36 +50,6 @@ AWT_ASSERT_APPKIT_THREAD; ...@@ -129,36 +50,6 @@ AWT_ASSERT_APPKIT_THREAD;
return env; return env;
} }
+ (void)initialize {
// Headless: BOTH
// Embedded: BOTH
// Multiple Calls: NO
// Caller: Obj-C class initialization
// Thread: ?
if (sPerformModes == nil) {
// Create list of Run Loop modes to perform on
// The default performSelector, with no mode argument, runs in Default,
// ModalPanel, and EventTracking modes
sPerformModes = [[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, nil];
sAWTPerformModes = [[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, [JNFRunLoop javaRunLoopMode], nil];
#ifdef AWT_THREAD_ASSERTS_ENV_ASSERT
sAWTThreadAsserts = (getenv("COCOA_AWT_DISABLE_THREAD_ASSERTS") == NULL);
#endif /* AWT_THREAD_ASSERTS_ENV_ASSERT */
}
}
// These methods can behave slightly differently than the normal
// performSelector... In particular, we define a special runloop mode
// (AWTRunLoopMode) so that we can "block" the main thread against the
// java event thread without deadlocking. See CToolkit.invokeAndWait.
+ (void)performOnMainThread:(SEL)aSelector onObject:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait awtMode:(BOOL)inAWT {
CPerformer *performer = [[CPerformer alloc] initWithTarget:target selector:aSelector arg:arg wait:wait];
[performer performSelectorOnMainThread:@selector(perform) withObject:nil waitUntilDone:wait modes:((inAWT) ? sAWTPerformModes : sPerformModes)]; // AWT_THREADING Safe (cover method)
[performer release];
}
+ (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block { + (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block {
if ([NSThread isMainThread] && wait == YES) { if ([NSThread isMainThread] && wait == YES) {
block(); block();
......
...@@ -277,7 +277,7 @@ public class CheckboxMenuItem extends MenuItem implements ItemSelectable, Access ...@@ -277,7 +277,7 @@ public class CheckboxMenuItem extends MenuItem implements ItemSelectable, Access
* @since 1.4 * @since 1.4
*/ */
public synchronized ItemListener[] getItemListeners() { public synchronized ItemListener[] getItemListeners() {
return (ItemListener[])(getListeners(ItemListener.class)); return getListeners(ItemListener.class);
} }
/** /**
......
...@@ -163,11 +163,11 @@ public class Cursor implements java.io.Serializable { ...@@ -163,11 +163,11 @@ public class Cursor implements java.io.Serializable {
* hashtable, filesystem dir prefix, filename, and properties for custom cursors support * hashtable, filesystem dir prefix, filename, and properties for custom cursors support
*/ */
private static final Hashtable systemCustomCursors = new Hashtable(1); private static final Hashtable<String,Cursor> systemCustomCursors = new Hashtable<>(1);
private static final String systemCustomCursorDirPrefix = initCursorDir(); private static final String systemCustomCursorDirPrefix = initCursorDir();
private static String initCursorDir() { private static String initCursorDir() {
String jhome = (String) java.security.AccessController.doPrivileged( String jhome = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("java.home")); new sun.security.action.GetPropertyAction("java.home"));
return jhome + return jhome +
File.separator + "lib" + File.separator + "images" + File.separator + "lib" + File.separator + "images" +
...@@ -298,7 +298,7 @@ public class Cursor implements java.io.Serializable { ...@@ -298,7 +298,7 @@ public class Cursor implements java.io.Serializable {
static public Cursor getSystemCustomCursor(final String name) static public Cursor getSystemCustomCursor(final String name)
throws AWTException, HeadlessException { throws AWTException, HeadlessException {
GraphicsEnvironment.checkHeadless(); GraphicsEnvironment.checkHeadless();
Cursor cursor = (Cursor)systemCustomCursors.get(name); Cursor cursor = systemCustomCursors.get(name);
if (cursor == null) { if (cursor == null) {
synchronized(systemCustomCursors) { synchronized(systemCustomCursors) {
...@@ -319,11 +319,11 @@ public class Cursor implements java.io.Serializable { ...@@ -319,11 +319,11 @@ public class Cursor implements java.io.Serializable {
final String fileName = final String fileName =
systemCustomCursorProperties.getProperty(key); systemCustomCursorProperties.getProperty(key);
String localized = (String)systemCustomCursorProperties.getProperty(prefix + DotNameSuffix); String localized = systemCustomCursorProperties.getProperty(prefix + DotNameSuffix);
if (localized == null) localized = name; if (localized == null) localized = name;
String hotspot = (String)systemCustomCursorProperties.getProperty(prefix + DotHotspotSuffix); String hotspot = systemCustomCursorProperties.getProperty(prefix + DotHotspotSuffix);
if (hotspot == null) if (hotspot == null)
throw new AWTException("no hotspot property defined for cursor: " + name); throw new AWTException("no hotspot property defined for cursor: " + name);
...@@ -348,9 +348,9 @@ public class Cursor implements java.io.Serializable { ...@@ -348,9 +348,9 @@ public class Cursor implements java.io.Serializable {
final int fy = y; final int fy = y;
final String flocalized = localized; final String flocalized = localized;
cursor = (Cursor) java.security.AccessController.doPrivileged( cursor = java.security.AccessController.<Cursor>doPrivileged(
new java.security.PrivilegedExceptionAction() { new java.security.PrivilegedExceptionAction<Cursor>() {
public Object run() throws Exception { public Cursor run() throws Exception {
Toolkit toolkit = Toolkit.getDefaultToolkit(); Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage( Image image = toolkit.getImage(
systemCustomCursorDirPrefix + fileName); systemCustomCursorDirPrefix + fileName);
...@@ -447,8 +447,8 @@ public class Cursor implements java.io.Serializable { ...@@ -447,8 +447,8 @@ public class Cursor implements java.io.Serializable {
systemCustomCursorProperties = new Properties(); systemCustomCursorProperties = new Properties();
try { try {
AccessController.doPrivileged( AccessController.<Object>doPrivileged(
new java.security.PrivilegedExceptionAction() { new java.security.PrivilegedExceptionAction<Object>() {
public Object run() throws Exception { public Object run() throws Exception {
FileInputStream fis = null; FileInputStream fis = null;
try { try {
......
...@@ -171,7 +171,7 @@ public class EventQueue { ...@@ -171,7 +171,7 @@ public class EventQueue {
* The modifiers field of the current event, if the current event is an * The modifiers field of the current event, if the current event is an
* InputEvent or ActionEvent. * InputEvent or ActionEvent.
*/ */
private WeakReference currentEvent; private WeakReference<AWTEvent> currentEvent;
/* /*
* Non-zero if a thread is waiting in getNextEvent(int) for an event of * Non-zero if a thread is waiting in getNextEvent(int) for an event of
...@@ -809,7 +809,7 @@ public class EventQueue { ...@@ -809,7 +809,7 @@ public class EventQueue {
pushPopLock.lock(); pushPopLock.lock();
try { try {
return (Thread.currentThread() == dispatchThread) return (Thread.currentThread() == dispatchThread)
? ((AWTEvent)currentEvent.get()) ? currentEvent.get()
: null; : null;
} finally { } finally {
pushPopLock.unlock(); pushPopLock.unlock();
...@@ -1167,7 +1167,7 @@ public class EventQueue { ...@@ -1167,7 +1167,7 @@ public class EventQueue {
return; return;
} }
currentEvent = new WeakReference(e); currentEvent = new WeakReference<>(e);
// This series of 'instanceof' checks should be replaced with a // This series of 'instanceof' checks should be replaced with a
// polymorphic type (for example, an interface which declares a // polymorphic type (for example, an interface which declares a
......
...@@ -66,7 +66,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -66,7 +66,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
AWTAccessor.setMenuAccessor( AWTAccessor.setMenuAccessor(
new AWTAccessor.MenuAccessor() { new AWTAccessor.MenuAccessor() {
public Vector getItems(Menu menu) { public Vector<MenuComponent> getItems(Menu menu) {
return menu.items; return menu.items;
} }
}); });
...@@ -78,7 +78,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -78,7 +78,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
* @serial * @serial
* @see #countItems() * @see #countItems()
*/ */
Vector items = new Vector(); Vector<MenuComponent> items = new Vector<>();
/** /**
* This field indicates whether the menu has the * This field indicates whether the menu has the
...@@ -313,7 +313,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -313,7 +313,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
} }
int nitems = getItemCount(); int nitems = getItemCount();
Vector tempItems = new Vector(); Vector<MenuItem> tempItems = new Vector<>();
/* Remove the item at index, nitems-index times /* Remove the item at index, nitems-index times
storing them in a temporary vector in the storing them in a temporary vector in the
...@@ -330,7 +330,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -330,7 +330,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
already in the correct order in the temp vector. already in the correct order in the temp vector.
*/ */
for (int i = 0; i < tempItems.size() ; i++) { for (int i = 0; i < tempItems.size() ; i++) {
add((MenuItem)tempItems.elementAt(i)); add(tempItems.elementAt(i));
} }
} }
} }
...@@ -379,7 +379,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -379,7 +379,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
} }
int nitems = getItemCount(); int nitems = getItemCount();
Vector tempItems = new Vector(); Vector<MenuItem> tempItems = new Vector<>();
/* Remove the item at index, nitems-index times /* Remove the item at index, nitems-index times
storing them in a temporary vector in the storing them in a temporary vector in the
...@@ -396,7 +396,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -396,7 +396,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
already in the correct order in the temp vector. already in the correct order in the temp vector.
*/ */
for (int i = 0; i < tempItems.size() ; i++) { for (int i = 0; i < tempItems.size() ; i++) {
add((MenuItem)tempItems.elementAt(i)); add(tempItems.elementAt(i));
} }
} }
} }
...@@ -475,13 +475,13 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { ...@@ -475,13 +475,13 @@ public class Menu extends MenuItem implements MenuContainer, Accessible {
return null; return null;
} }
synchronized Enumeration shortcuts() { synchronized Enumeration<MenuShortcut> shortcuts() {
Vector shortcuts = new Vector(); Vector<MenuShortcut> shortcuts = new Vector<>();
int nitems = getItemCount(); int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) { for (int i = 0 ; i < nitems ; i++) {
MenuItem mi = getItem(i); MenuItem mi = getItem(i);
if (mi instanceof Menu) { if (mi instanceof Menu) {
Enumeration e = ((Menu)mi).shortcuts(); Enumeration<MenuShortcut> e = ((Menu)mi).shortcuts();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
shortcuts.addElement(e.nextElement()); shortcuts.addElement(e.nextElement());
} }
......
...@@ -81,7 +81,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible ...@@ -81,7 +81,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
return menuBar.helpMenu; return menuBar.helpMenu;
} }
public Vector getMenus(MenuBar menuBar) { public Vector<Menu> getMenus(MenuBar menuBar) {
return menuBar.menus; return menuBar.menus;
} }
}); });
...@@ -94,7 +94,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible ...@@ -94,7 +94,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
* @serial * @serial
* @see #countMenus() * @see #countMenus()
*/ */
Vector menus = new Vector(); Vector<Menu> menus = new Vector<>();
/** /**
* This menu is a special menu dedicated to * This menu is a special menu dedicated to
...@@ -309,7 +309,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible ...@@ -309,7 +309,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
* be called on the toolkit thread. * be called on the toolkit thread.
*/ */
final Menu getMenuImpl(int i) { final Menu getMenuImpl(int i) {
return (Menu)menus.elementAt(i); return menus.elementAt(i);
} }
/** /**
...@@ -321,10 +321,10 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible ...@@ -321,10 +321,10 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
* @since JDK1.1 * @since JDK1.1
*/ */
public synchronized Enumeration<MenuShortcut> shortcuts() { public synchronized Enumeration<MenuShortcut> shortcuts() {
Vector shortcuts = new Vector(); Vector<MenuShortcut> shortcuts = new Vector<>();
int nmenus = getMenuCount(); int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) { for (int i = 0 ; i < nmenus ; i++) {
Enumeration e = getMenu(i).shortcuts(); Enumeration<MenuShortcut> e = getMenu(i).shortcuts();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
shortcuts.addElement(e.nextElement()); shortcuts.addElement(e.nextElement());
} }
...@@ -438,7 +438,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible ...@@ -438,7 +438,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
// HeadlessException will be thrown from MenuComponent's readObject // HeadlessException will be thrown from MenuComponent's readObject
s.defaultReadObject(); s.defaultReadObject();
for (int i = 0; i < menus.size(); i++) { for (int i = 0; i < menus.size(); i++) {
Menu m = (Menu)menus.elementAt(i); Menu m = menus.elementAt(i);
m.parent = this; m.parent = this;
} }
} }
......
...@@ -290,7 +290,7 @@ public abstract class MenuComponent implements java.io.Serializable { ...@@ -290,7 +290,7 @@ public abstract class MenuComponent implements java.io.Serializable {
public void setFont(Font f) { public void setFont(Font f) {
font = f; font = f;
//Fixed 6312943: NullPointerException in method MenuComponent.setFont(Font) //Fixed 6312943: NullPointerException in method MenuComponent.setFont(Font)
MenuComponentPeer peer = (MenuComponentPeer)this.peer; MenuComponentPeer peer = this.peer;
if (peer != null) { if (peer != null) {
peer.setFont(f); peer.setFont(f);
} }
...@@ -303,7 +303,7 @@ public abstract class MenuComponent implements java.io.Serializable { ...@@ -303,7 +303,7 @@ public abstract class MenuComponent implements java.io.Serializable {
*/ */
public void removeNotify() { public void removeNotify() {
synchronized (getTreeLock()) { synchronized (getTreeLock()) {
MenuComponentPeer p = (MenuComponentPeer)this.peer; MenuComponentPeer p = this.peer;
if (p != null) { if (p != null) {
Toolkit.getEventQueue().removeSourceEvents(this, true); Toolkit.getEventQueue().removeSourceEvents(this, true);
this.peer = null; this.peer = null;
......
...@@ -564,7 +564,7 @@ public class MenuItem extends MenuComponent implements Accessible { ...@@ -564,7 +564,7 @@ public class MenuItem extends MenuComponent implements Accessible {
* @since 1.4 * @since 1.4
*/ */
public synchronized ActionListener[] getActionListeners() { public synchronized ActionListener[] getActionListeners() {
return (ActionListener[])(getListeners(ActionListener.class)); return getListeners(ActionListener.class);
} }
/** /**
......
...@@ -92,7 +92,7 @@ public class RenderingHints ...@@ -92,7 +92,7 @@ public class RenderingHints
* {@code equals()} method. * {@code equals()} method.
*/ */
public abstract static class Key { public abstract static class Key {
private static HashMap identitymap = new HashMap(17); private static HashMap<Object,Object> identitymap = new HashMap<>(17);
private String getIdentity() { private String getIdentity() {
// Note that the identity string is dependent on 3 variables: // Note that the identity string is dependent on 3 variables:
...@@ -138,7 +138,7 @@ public class RenderingHints ...@@ -138,7 +138,7 @@ public class RenderingHints
} }
// Note: Use a weak reference to avoid holding on to extra // Note: Use a weak reference to avoid holding on to extra
// objects and classes after they should be unloaded. // objects and classes after they should be unloaded.
identitymap.put(identity, new WeakReference(k)); identitymap.put(identity, new WeakReference<Key>(k));
} }
private int privatekey; private int privatekey;
...@@ -195,7 +195,7 @@ public class RenderingHints ...@@ -195,7 +195,7 @@ public class RenderingHints
} }
} }
HashMap hintmap = new HashMap(7); HashMap<Object,Object> hintmap = new HashMap<>(7);
/** /**
* Antialiasing hint key. * Antialiasing hint key.
...@@ -1267,12 +1267,13 @@ public class RenderingHints ...@@ -1267,12 +1267,13 @@ public class RenderingHints
* object. * object.
* @return a clone of this instance. * @return a clone of this instance.
*/ */
@SuppressWarnings("unchecked")
public Object clone() { public Object clone() {
RenderingHints rh; RenderingHints rh;
try { try {
rh = (RenderingHints) super.clone(); rh = (RenderingHints) super.clone();
if (hintmap != null) { if (hintmap != null) {
rh.hintmap = (HashMap) hintmap.clone(); rh.hintmap = (HashMap<Object,Object>) hintmap.clone();
} }
} catch (CloneNotSupportedException e) { } catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable // this shouldn't happen, since we are Cloneable
......
...@@ -71,7 +71,7 @@ public class Clipboard { ...@@ -71,7 +71,7 @@ public class Clipboard {
* *
* @since 1.5 * @since 1.5
*/ */
private Set currentDataFlavors; private Set<DataFlavor> currentDataFlavors;
/** /**
* Creates a clipboard object. * Creates a clipboard object.
...@@ -313,7 +313,7 @@ public class Clipboard { ...@@ -313,7 +313,7 @@ public class Clipboard {
if (flavorListeners == null) { if (flavorListeners == null) {
return; return;
} }
Set prevDataFlavors = currentDataFlavors; Set<DataFlavor> prevDataFlavors = currentDataFlavors;
currentDataFlavors = getAvailableDataFlavorSet(); currentDataFlavors = getAvailableDataFlavorSet();
if (prevDataFlavors.equals(currentDataFlavors)) { if (prevDataFlavors.equals(currentDataFlavors)) {
return; return;
...@@ -339,8 +339,8 @@ public class Clipboard { ...@@ -339,8 +339,8 @@ public class Clipboard {
* *
* @since 1.5 * @since 1.5
*/ */
private Set getAvailableDataFlavorSet() { private Set<DataFlavor> getAvailableDataFlavorSet() {
Set set = new HashSet(); Set<DataFlavor> set = new HashSet<>();
Transferable contents = getContents(null); Transferable contents = getContents(null);
if (contents != null) { if (contents != null) {
DataFlavor[] flavors = contents.getTransferDataFlavors(); DataFlavor[] flavors = contents.getTransferDataFlavors();
......
...@@ -165,7 +165,7 @@ public class DragGestureEvent extends EventObject { ...@@ -165,7 +165,7 @@ public class DragGestureEvent extends EventObject {
* <P> * <P>
* @return an Iterator for the events comprising the gesture * @return an Iterator for the events comprising the gesture
*/ */
@SuppressWarnings("unchecked")
public Iterator<InputEvent> iterator() { return events.iterator(); } public Iterator<InputEvent> iterator() { return events.iterator(); }
/** /**
...@@ -184,7 +184,7 @@ public class DragGestureEvent extends EventObject { ...@@ -184,7 +184,7 @@ public class DragGestureEvent extends EventObject {
* <P> * <P>
* @return an array of the events comprising the gesture * @return an array of the events comprising the gesture
*/ */
@SuppressWarnings("unchecked")
public Object[] toArray(Object[] array) { return events.toArray(array); } public Object[] toArray(Object[] array) { return events.toArray(array); }
/** /**
...@@ -333,7 +333,6 @@ public class DragGestureEvent extends EventObject { ...@@ -333,7 +333,6 @@ public class DragGestureEvent extends EventObject {
component = (Component)f.get("component", null); component = (Component)f.get("component", null);
origin = (Point)f.get("origin", null); origin = (Point)f.get("origin", null);
action = f.get("action", 0); action = f.get("action", 0);
// Pre-1.4 support. 'events' was previously non-transient // Pre-1.4 support. 'events' was previously non-transient
try { try {
events = (List)f.get("events", null); events = (List)f.get("events", null);
...@@ -351,7 +350,7 @@ public class DragGestureEvent extends EventObject { ...@@ -351,7 +350,7 @@ public class DragGestureEvent extends EventObject {
/* /*
* fields * fields
*/ */
@SuppressWarnings("rawtypes")
private transient List events; private transient List events;
/** /**
......
...@@ -297,7 +297,7 @@ public abstract class DragGestureRecognizer implements Serializable { ...@@ -297,7 +297,7 @@ public abstract class DragGestureRecognizer implements Serializable {
* @return the initial event that triggered the drag gesture * @return the initial event that triggered the drag gesture
*/ */
public InputEvent getTriggerEvent() { return events.isEmpty() ? null : (InputEvent)events.get(0); } public InputEvent getTriggerEvent() { return events.isEmpty() ? null : events.get(0); }
/** /**
* Reset the Recognizer, if its currently recognizing a gesture, ignore * Reset the Recognizer, if its currently recognizing a gesture, ignore
......
...@@ -600,7 +600,7 @@ public class DragSource implements Serializable { ...@@ -600,7 +600,7 @@ public class DragSource implements Serializable {
* @since 1.4 * @since 1.4
*/ */
public DragSourceListener[] getDragSourceListeners() { public DragSourceListener[] getDragSourceListeners() {
return (DragSourceListener[])getListeners(DragSourceListener.class); return getListeners(DragSourceListener.class);
} }
/** /**
...@@ -660,8 +660,7 @@ public class DragSource implements Serializable { ...@@ -660,8 +660,7 @@ public class DragSource implements Serializable {
* @since 1.4 * @since 1.4
*/ */
public DragSourceMotionListener[] getDragSourceMotionListeners() { public DragSourceMotionListener[] getDragSourceMotionListeners() {
return (DragSourceMotionListener[]) return getListeners(DragSourceMotionListener.class);
getListeners(DragSourceMotionListener.class);
} }
/** /**
...@@ -896,8 +895,8 @@ public class DragSource implements Serializable { ...@@ -896,8 +895,8 @@ public class DragSource implements Serializable {
* @since 1.5 * @since 1.5
*/ */
public static int getDragThreshold() { public static int getDragThreshold() {
int ts = ((Integer)AccessController.doPrivileged( int ts = AccessController.doPrivileged(
new GetIntegerAction("awt.dnd.drag.threshold", 0))).intValue(); new GetIntegerAction("awt.dnd.drag.threshold", 0)).intValue();
if (ts > 0) { if (ts > 0) {
return ts; return ts;
} else { } else {
......
...@@ -36,6 +36,8 @@ package java.awt.dnd; ...@@ -36,6 +36,8 @@ package java.awt.dnd;
public class InvalidDnDOperationException extends IllegalStateException { public class InvalidDnDOperationException extends IllegalStateException {
private static final long serialVersionUID = 5156676500247816278L;
static private String dft_msg = "The operation requested cannot be performed by the DnD system since it is not in the appropriate state"; static private String dft_msg = "The operation requested cannot be performed by the DnD system since it is not in the appropriate state";
/** /**
......
...@@ -876,6 +876,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -876,6 +876,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* they have not been cached. * they have not been cached.
* @see #getType * @see #getType
*/ */
@SuppressWarnings("fallthrough")
private void calculateType() { private void calculateType() {
int ret = TYPE_IDENTITY; int ret = TYPE_IDENTITY;
boolean sgn0, sgn1; boolean sgn0, sgn1;
...@@ -1038,6 +1039,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -1038,6 +1039,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* @see #TYPE_UNIFORM_SCALE * @see #TYPE_UNIFORM_SCALE
* @since 1.2 * @since 1.2
*/ */
@SuppressWarnings("fallthrough")
public double getDeterminant() { public double getDeterminant() {
switch (state) { switch (state) {
default: default:
...@@ -1250,6 +1252,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -1250,6 +1252,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
m02 = tx * m00 + ty * m01 + m02; m02 = tx * m00 + ty * m01 + m02;
m12 = tx * m10 + ty * m11 + m12; m12 = tx * m10 + ty * m11 + m12;
...@@ -1631,6 +1634,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -1631,6 +1634,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* Y axis direction * Y axis direction
* @since 1.2 * @since 1.2
*/ */
@SuppressWarnings("fallthrough")
public void scale(double sx, double sy) { public void scale(double sx, double sy) {
int state = this.state; int state = this.state;
switch (state) { switch (state) {
...@@ -1705,6 +1709,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -1705,6 +1709,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
case (APPLY_SHEAR | APPLY_SCALE): case (APPLY_SHEAR | APPLY_SCALE):
double M0, M1; double M0, M1;
...@@ -2224,6 +2229,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2224,6 +2229,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* @see #preConcatenate * @see #preConcatenate
* @since 1.2 * @since 1.2
*/ */
@SuppressWarnings("fallthrough")
public void concatenate(AffineTransform Tx) { public void concatenate(AffineTransform Tx) {
double M0, M1; double M0, M1;
double T00, T01, T10, T11; double T00, T01, T10, T11;
...@@ -2432,6 +2438,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2432,6 +2438,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* @see #concatenate * @see #concatenate
* @since 1.2 * @since 1.2
*/ */
@SuppressWarnings("fallthrough")
public void preConcatenate(AffineTransform Tx) { public void preConcatenate(AffineTransform Tx) {
double M0, M1; double M0, M1;
double T00, T01, T10, T11; double T00, T01, T10, T11;
...@@ -2655,6 +2662,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2655,6 +2662,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return null;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
det = m00 * m11 - m01 * m10; det = m00 * m11 - m01 * m10;
if (Math.abs(det) <= Double.MIN_VALUE) { if (Math.abs(det) <= Double.MIN_VALUE) {
...@@ -2751,6 +2759,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2751,6 +2759,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -2885,6 +2894,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2885,6 +2894,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return null;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
ptDst.setLocation(x * m00 + y * m01 + m02, ptDst.setLocation(x * m00 + y * m01 + m02,
x * m10 + y * m11 + m12); x * m10 + y * m11 + m12);
...@@ -2968,6 +2978,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -2968,6 +2978,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
dst.setLocation(x * m00 + y * m01 + m02, dst.setLocation(x * m00 + y * m01 + m02,
x * m10 + y * m11 + m12); x * m10 + y * m11 + m12);
...@@ -3043,6 +3054,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3043,6 +3054,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -3157,6 +3169,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3157,6 +3169,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -3252,6 +3265,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3252,6 +3265,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -3347,6 +3361,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3347,6 +3361,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -3436,6 +3451,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3436,6 +3451,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* inverted. * inverted.
* @since 1.2 * @since 1.2
*/ */
@SuppressWarnings("fallthrough")
public Point2D inverseTransform(Point2D ptSrc, Point2D ptDst) public Point2D inverseTransform(Point2D ptSrc, Point2D ptDst)
throws NoninvertibleTransformException throws NoninvertibleTransformException
{ {
...@@ -3547,6 +3563,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3547,6 +3563,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
M00 = m00; M01 = m01; M02 = m02; M00 = m00; M01 = m01; M02 = m02;
M10 = m10; M11 = m11; M12 = m12; M10 = m10; M11 = m11; M12 = m12;
...@@ -3679,6 +3696,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3679,6 +3696,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return null;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
case (APPLY_SHEAR | APPLY_SCALE): case (APPLY_SHEAR | APPLY_SCALE):
ptDst.setLocation(x * m00 + y * m01, x * m10 + y * m11); ptDst.setLocation(x * m00 + y * m01, x * m10 + y * m11);
...@@ -3754,6 +3772,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -3754,6 +3772,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
default: default:
stateError(); stateError();
/* NOTREACHED */ /* NOTREACHED */
return;
case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE): case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
case (APPLY_SHEAR | APPLY_SCALE): case (APPLY_SHEAR | APPLY_SCALE):
M00 = m00; M01 = m01; M00 = m00; M01 = m01;
......
...@@ -125,4 +125,10 @@ public interface FramePeer extends WindowPeer { ...@@ -125,4 +125,10 @@ public interface FramePeer extends WindowPeer {
// into an EmbeddedFramePeer which would extend FramePeer // into an EmbeddedFramePeer which would extend FramePeer
Rectangle getBoundsPrivate(); Rectangle getBoundsPrivate();
/**
* Requests the peer to emulate window activation.
*
* @param activate activate or deactivate the window
*/
void emulateActivation(boolean activate);
} }
...@@ -27,8 +27,6 @@ package java.awt.peer; ...@@ -27,8 +27,6 @@ package java.awt.peer;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage;
/** /**
* The peer interface for {@link Window}. * The peer interface for {@link Window}.
* *
......
/* /*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -109,10 +109,6 @@ public class PropertyDescriptor extends FeatureDescriptor { ...@@ -109,10 +109,6 @@ public class PropertyDescriptor extends FeatureDescriptor {
if (writeMethodName != null && getWriteMethod() == null) { if (writeMethodName != null && getWriteMethod() == null) {
throw new IntrospectionException("Method not found: " + writeMethodName); throw new IntrospectionException("Method not found: " + writeMethodName);
} }
boundInitialization(beanClass);
}
private void boundInitialization(Class<?> beanClass) {
// If this class or one of its base classes allow PropertyChangeListener, // If this class or one of its base classes allow PropertyChangeListener,
// then we assume that any properties we discover are "bound". // then we assume that any properties we discover are "bound".
// See Introspector.getTargetPropertyInfo() method. // See Introspector.getTargetPropertyInfo() method.
...@@ -163,7 +159,6 @@ public class PropertyDescriptor extends FeatureDescriptor { ...@@ -163,7 +159,6 @@ public class PropertyDescriptor extends FeatureDescriptor {
setReadMethod(read); setReadMethod(read);
setWriteMethod(write); setWriteMethod(write);
this.baseName = base; this.baseName = base;
boundInitialization(bean);
} }
/** /**
......
...@@ -387,13 +387,14 @@ public class JFrame extends Frame implements WindowConstants, ...@@ -387,13 +387,14 @@ public class JFrame extends Frame implements WindowConstants,
operation != EXIT_ON_CLOSE) { operation != EXIT_ON_CLOSE) {
throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE"); throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE");
} }
if (this.defaultCloseOperation != operation) {
if (operation == EXIT_ON_CLOSE) { if (operation == EXIT_ON_CLOSE) {
SecurityManager security = System.getSecurityManager(); SecurityManager security = System.getSecurityManager();
if (security != null) { if (security != null) {
security.checkExit(0); security.checkExit(0);
} }
} }
if (this.defaultCloseOperation != operation) {
int oldValue = this.defaultCloseOperation; int oldValue = this.defaultCloseOperation;
this.defaultCloseOperation = operation; this.defaultCloseOperation = operation;
firePropertyChange("defaultCloseOperation", oldValue, operation); firePropertyChange("defaultCloseOperation", oldValue, operation);
......
...@@ -356,7 +356,7 @@ public class SwingUtilities implements SwingConstants ...@@ -356,7 +356,7 @@ public class SwingUtilities implements SwingConstants
sourceEvent.getYOnScreen(), sourceEvent.getYOnScreen(),
sourceEvent.getClickCount(), sourceEvent.getClickCount(),
sourceEvent.isPopupTrigger(), sourceEvent.isPopupTrigger(),
MouseEvent.NOBUTTON ); sourceEvent.getButton());
} }
return newEvent; return newEvent;
} }
......
...@@ -159,6 +159,10 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -159,6 +159,10 @@ public class FormView extends ComponentView implements ActionListener {
attr.getAttribute(StyleConstants.NameAttribute); attr.getAttribute(StyleConstants.NameAttribute);
JComponent c = null; JComponent c = null;
Object model = attr.getAttribute(StyleConstants.ModelAttribute); Object model = attr.getAttribute(StyleConstants.ModelAttribute);
// Remove listeners previously registered in shared model
// when a new UI component is replaced. See bug 7189299.
removeStaleListenerForModel(model);
if (t == HTML.Tag.INPUT) { if (t == HTML.Tag.INPUT) {
c = createInputComponent(attr, model); c = createInputComponent(attr, model);
} else if (t == HTML.Tag.SELECT) { } else if (t == HTML.Tag.SELECT) {
...@@ -310,6 +314,63 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -310,6 +314,63 @@ public class FormView extends ComponentView implements ActionListener {
return c; return c;
} }
private void removeStaleListenerForModel(Object model) {
if (model instanceof DefaultButtonModel) {
// case of JButton whose model is DefaultButtonModel
// Need to remove stale ActionListener, ChangeListener and
// ItemListener that are instance of AbstractButton$Handler.
DefaultButtonModel buttonModel = (DefaultButtonModel) model;
String listenerClass = "javax.swing.AbstractButton$Handler";
for (ActionListener listener : buttonModel.getActionListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeActionListener(listener);
}
}
for (ChangeListener listener : buttonModel.getChangeListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeChangeListener(listener);
}
}
for (ItemListener listener : buttonModel.getItemListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeItemListener(listener);
}
}
} else if (model instanceof AbstractListModel) {
// case of JComboBox and JList
// For JList, the stale ListDataListener is instance
// BasicListUI$Handler.
// For JComboBox, there are 2 stale ListDataListeners, which are
// BasicListUI$Handler and BasicComboBoxUI$Handler.
AbstractListModel listModel = (AbstractListModel) model;
String listenerClass1 =
"javax.swing.plaf.basic.BasicListUI$Handler";
String listenerClass2 =
"javax.swing.plaf.basic.BasicComboBoxUI$Handler";
for (ListDataListener listener : listModel.getListDataListeners()) {
if (listenerClass1.equals(listener.getClass().getName())
|| listenerClass2.equals(listener.getClass().getName()))
{
listModel.removeListDataListener(listener);
}
}
} else if (model instanceof AbstractDocument) {
// case of JPasswordField, JTextField and JTextArea
// All have 2 stale DocumentListeners.
String listenerClass1 =
"javax.swing.plaf.basic.BasicTextUI$UpdateHandler";
String listenerClass2 =
"javax.swing.text.DefaultCaret$Handler";
AbstractDocument docModel = (AbstractDocument) model;
for (DocumentListener listener : docModel.getDocumentListeners()) {
if (listenerClass1.equals(listener.getClass().getName())
|| listenerClass2.equals(listener.getClass().getName()))
{
docModel.removeDocumentListener(listener);
}
}
}
}
/** /**
* Determines the maximum span for this view along an * Determines the maximum span for this view along an
...@@ -347,7 +408,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -347,7 +408,7 @@ public class FormView extends ComponentView implements ActionListener {
/** /**
* Responsible for processeing the ActionEvent. * Responsible for processing the ActionEvent.
* If the element associated with the FormView, * If the element associated with the FormView,
* has a type of "submit", "reset", "text" or "password" * has a type of "submit", "reset", "text" or "password"
* then the action is processed. In the case of a "submit" * then the action is processed. In the case of a "submit"
......
...@@ -582,5 +582,8 @@ public abstract class EmbeddedFrame extends Frame ...@@ -582,5 +582,8 @@ public abstract class EmbeddedFrame extends Frame
public void repositionSecurityWarning() { public void repositionSecurityWarning() {
} }
public void emulateActivation(boolean activate) {
}
} }
} // class EmbeddedFrame } // class EmbeddedFrame
...@@ -64,6 +64,11 @@ public class HToolkit extends SunToolkit ...@@ -64,6 +64,11 @@ public class HToolkit extends SunToolkit
throw new HeadlessException(); throw new HeadlessException();
} }
public FramePeer createLightweightFrame(LightweightFrame target)
throws HeadlessException {
throw new HeadlessException();
}
public FramePeer createFrame(Frame target) public FramePeer createFrame(Frame target)
throws HeadlessException { throws HeadlessException {
throw new HeadlessException(); throw new HeadlessException();
......
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuBar;
import java.awt.MenuComponent;
import java.awt.Toolkit;
import java.awt.peer.FramePeer;
/**
* The class provides basic functionality for a lightweight frame
* implementation. A subclass is expected to provide painting to an
* offscreen image and access to it. Thus it can be used for lightweight
* embedding.
*
* @author Artem Ananiev
* @author Anton Tarasov
*/
@SuppressWarnings("serial")
public abstract class LightweightFrame extends Frame {
/**
* Constructs a new, initially invisible {@code LightweightFrame}
* instance.
*/
public LightweightFrame() {
setUndecorated(true);
setResizable(true);
setEnabled(true);
}
/**
* Blocks introspection of a parent window by this child.
*
* @return null
*/
@Override public final Container getParent() { return null; }
@Override public Graphics getGraphics() { return null; }
@Override public final boolean isResizable() { return true; }
// Block modification of any frame attributes, since they aren't
// applicable for a lightweight frame.
@Override public final void setTitle(String title) {}
@Override public final void setIconImage(Image image) {}
@Override public final void setIconImages(java.util.List<? extends Image> icons) {}
@Override public final void setMenuBar(MenuBar mb) {}
@Override public final void setResizable(boolean resizable) {}
@Override public final void remove(MenuComponent m) {}
@Override public final void toFront() {}
@Override public final void toBack() {}
@Override public void addNotify() {
synchronized (getTreeLock()) {
if (getPeer() == null) {
SunToolkit stk = (SunToolkit)Toolkit.getDefaultToolkit();
try {
setPeer(stk.createLightweightFrame(this));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
super.addNotify();
}
}
private void setPeer(final FramePeer p) {
AWTAccessor.getComponentAccessor().setPeer(this, p);
}
/**
* Requests the peer to emulate activation or deactivation of the
* frame. Peers should override this method if they are to implement
* this functionality.
*
* @param activate if <code>true</code>, activates the frame;
* otherwise, deactivates the frame
*/
public void emulateActivation(boolean activate) {
((FramePeer)getPeer()).emulateActivation(activate);
}
/**
* Delegates the focus grab action to the client (embedding) application.
* The method is called by the AWT grab machinery.
*
* @see SunToolkit#grab(java.awt.Window)
*/
public abstract void grabFocus();
/**
* Delegates the focus ungrab action to the client (embedding) application.
* The method is called by the AWT grab machinery.
*
* @see SunToolkit#ungrab(java.awt.Window)
*/
public abstract void ungrabFocus();
}
...@@ -131,6 +131,9 @@ public abstract class SunToolkit extends Toolkit ...@@ -131,6 +131,9 @@ public abstract class SunToolkit extends Toolkit
public abstract FramePeer createFrame(Frame target) public abstract FramePeer createFrame(Frame target)
throws HeadlessException; throws HeadlessException;
public abstract FramePeer createLightweightFrame(LightweightFrame target)
throws HeadlessException;
public abstract DialogPeer createDialog(Dialog target) public abstract DialogPeer createDialog(Dialog target)
throws HeadlessException; throws HeadlessException;
......
...@@ -1873,7 +1873,7 @@ search: ...@@ -1873,7 +1873,7 @@ search:
*/ */
public class ReencodingInputStream extends InputStream { public class ReencodingInputStream extends InputStream {
protected BufferedReader wrapped; protected BufferedReader wrapped;
protected final char[] in = new char[1]; protected final char[] in = new char[2];
protected byte[] out; protected byte[] out;
protected CharsetEncoder encoder; protected CharsetEncoder encoder;
...@@ -1926,7 +1926,7 @@ search: ...@@ -1926,7 +1926,7 @@ search:
try { try {
encoder = Charset.forName(targetEncoding).newEncoder(); encoder = Charset.forName(targetEncoding).newEncoder();
out = new byte[(int)(encoder.maxBytesPerChar() + 0.5)]; out = new byte[(int)(encoder.maxBytesPerChar() * 2 + 0.5)];
inBuf = CharBuffer.wrap(in); inBuf = CharBuffer.wrap(in);
outBuf = ByteBuffer.wrap(out); outBuf = ByteBuffer.wrap(out);
} catch (IllegalCharsetNameException e) { } catch (IllegalCharsetNameException e) {
...@@ -1950,12 +1950,7 @@ search: ...@@ -1950,12 +1950,7 @@ search:
} }
} }
public int read() throws IOException { private int readChar() throws IOException {
if (eos) {
return -1;
}
if (index >= limit) {
int c = wrapped.read(); int c = wrapped.read();
if (c == -1) { // -1 is EOS if (c == -1) { // -1 is EOS
...@@ -1971,10 +1966,34 @@ search: ...@@ -1971,10 +1966,34 @@ search:
c = '\n' & 0xFFFF; c = '\n' & 0xFFFF;
} }
in[0] = (char)c; return c;
}
public int read() throws IOException {
if (eos) {
return -1;
}
if (index >= limit) {
// deal with supplementary characters
int c = readChar();
if (c == -1) {
return -1;
}
in[0] = (char) c;
in[1] = 0;
inBuf.limit(1);
if (Character.isHighSurrogate((char) c)) {
c = readChar();
if (c != -1) {
in[1] = (char) c;
inBuf.limit(2);
}
}
inBuf.rewind(); inBuf.rewind();
outBuf.rewind(); outBuf.limit(out.length).rewind();
encoder.encode(inBuf, outBuf, false); encoder.encode(inBuf, outBuf, false);
outBuf.flip(); outBuf.flip();
limit = outBuf.limit(); limit = outBuf.limit();
......
...@@ -498,7 +498,7 @@ public abstract class SunDropTargetContextPeer implements DropTargetContextPeer, ...@@ -498,7 +498,7 @@ public abstract class SunDropTargetContextPeer implements DropTargetContextPeer,
postDropTargetEvent(component, x, y, dropAction, actions, postDropTargetEvent(component, x, y, dropAction, actions,
formats, nativeCtxt, formats, nativeCtxt,
SunDropTargetEvent.MOUSE_DROPPED, SunDropTargetEvent.MOUSE_DROPPED,
SunDropTargetContextPeer.DISPATCH_SYNC); !SunDropTargetContextPeer.DISPATCH_SYNC);
} }
/** /**
......
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.LayoutFocusTraversalPolicy;
import javax.swing.RootPaneContainer;
import sun.awt.LightweightFrame;
/**
* The frame serves as a lightweight container which paints its content
* to an offscreen image and provides access to the image's data via the
* {@link LightweightContent} interface. Note, that it may not be shown
* as a standalone toplevel frame. Its purpose is to provide functionality
* for lightweight embedding.
*
* @author Artem Ananiev
* @author Anton Tarasov
*/
public final class JLightweightFrame extends LightweightFrame implements RootPaneContainer {
private final JRootPane rootPane = new JRootPane();
private LightweightContent content;
private Component component;
private JPanel contentPane;
private BufferedImage bbImage;
/**
* Constructs a new, initially invisible {@code JLightweightFrame}
* instance.
*/
public JLightweightFrame() {
super();
add(rootPane, BorderLayout.CENTER);
setBackground(new Color(0, 0, 0, 0));
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
}
/**
* Sets the {@link LightweightContent} instance for this frame.
* The {@code JComponent} object returned by the
* {@link LightweightContent#getComponent()} method is immediately
* added to the frame's content pane.
*
* @param content the {@link LightweightContent} instance
*/
public void setContent(LightweightContent content) {
this.content = content;
this.component = content.getComponent();
initInterior();
}
@Override
public Graphics getGraphics() {
if (bbImage == null) return null;
Graphics2D g = bbImage.createGraphics();
g.setBackground(getBackground());
g.setColor(getForeground());
g.setFont(getFont());
return g;
}
/**
* {@inheritDoc}
*
* @see LightweightContent#focusGrabbed()
*/
@Override
public void grabFocus() {
if (content != null) content.focusGrabbed();
}
/**
* {@inheritDoc}
*
* @see LightweightContent#focusUngrabbed()
*/
@Override
public void ungrabFocus() {
if (content != null) content.focusUngrabbed();
}
private void initInterior() {
contentPane = new JPanel() {
@Override
public void paint(Graphics g) {
content.paintLock();
try {
super.paint(g);
final Rectangle clip = g.getClipBounds() != null ?
g.getClipBounds() : new Rectangle(0, 0, contentPane.getWidth(), contentPane.getHeight());
clip.x = Math.max(0, clip.x);
clip.y = Math.max(0, clip.y);
clip.width = Math.min(contentPane.getWidth(), clip.width);
clip.height = Math.min(contentPane.getHeight(), clip.height);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
content.imageUpdated(clip.x, clip.y, clip.width, clip.height);
}
});
} finally {
content.paintUnlock();
}
}
@Override
protected boolean isPaintingOrigin() {
return true;
}
};
contentPane.setLayout(new BorderLayout());
contentPane.add(component);
setContentPane(contentPane);
}
@SuppressWarnings("deprecation")
@Override public void reshape(int x, int y, int width, int height) {
super.reshape(x, y, width, height);
if (width == 0 || height == 0) {
return;
}
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;
} 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();
}
}
DataBufferInt dataBuf = (DataBufferInt)bbImage.getRaster().getDataBuffer();
content.imageBufferReset(dataBuf.getData(), 0, 0, width, height, bbImage.getWidth());
} else {
content.imageReshaped(0, 0, width, height);
}
}
} finally {
content.paintUnlock();
}
}
@Override
public JRootPane getRootPane() {
return rootPane;
}
@Override
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
@Override
public Container getContentPane() {
return getRootPane().getContentPane();
}
@Override
public void setLayeredPane(JLayeredPane layeredPane) {
getRootPane().setLayeredPane(layeredPane);
}
@Override
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
@Override
public void setGlassPane(Component glassPane) {
getRootPane().setGlassPane(glassPane);
}
@Override
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.swing;
import javax.swing.JComponent;
/**
* The interface by means of which the {@link JLightweightFrame} class
* communicates to its client application.
* <p>
* The client application implements this interface so it can response
* to requests and process notifications from {@code JLightweightFrame}.
* An implementation of this interface is associated with a {@code
* JLightweightFrame} instance via the {@link JLightweightFrame#setContent}
* method.
*
* A hierarchy of components contained in the {@code JComponent} instance
* returned by the {@link #getComponent} method should not contain any
* heavyweight components, otherwise {@code JLightweightFrame} may fail
* to paint it.
*
* @author Artem Ananiev
* @author Anton Tarasov
* @author Jim Graham
*/
public interface LightweightContent {
/**
* The client application overrides this method to return the {@code
* JComponent} instance which the {@code JLightweightFrame} container
* will paint as its lightweight content. A hierarchy of components
* contained in this component should not contain any heavyweight objects.
*
* @return the component to paint
*/
public JComponent getComponent();
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that it acquires the paint lock. The client application
* should implement the locking mechanism in order to synchronize access
* to the content image data, shared between {@code JLightweightFrame}
* and the client application.
*
* @see #paintUnlock
*/
public void paintLock();
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that it releases the paint lock. The client application
* should implement the locking mechanism in order to synchronize access
* to the content image data, shared between {@code JLightweightFrame}
* and the client application.
*
* @see #paintLock
*/
public void paintUnlock();
/**
* {@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.
* <p>
* The {@code width} and {@code height} matches the 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.
*
* @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 linestride the line stride of the pixel buffer
*/
public void imageBufferReset(int[] data,
int x, int y,
int width, int height,
int linestride);
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that the content image bounds have been changed within the
* image's pixel buffer.
*
* @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
*
* @see #imageBufferReset
*/
public void imageReshaped(int x, int y, int width, int height);
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that a part of the content image, or the whole image has
* been updated. The method reports bounds of the rectangular dirty region.
* The {@code dirtyX} and {@code dirtyY} is the origin of the dirty
* rectangle, which is relative to the origin of the content, appearing
* at {@code data[(y + dirtyY] * linestride + (x + dirtyX)]} in the pixel
* buffer (see {@link #imageBufferReset}). All indices
* {@code data[(y + dirtyY + j) * linestride + (x + dirtyX + i)]} where
* {@code (0 <= i < dirtyWidth)} and {@code (0 <= j < dirtyHeight)}
* will represent valid pixel data, {@code (i, j)} in the coordinate space
* of the dirty rectangle.
*
* @param dirtyX the x coordinate of the dirty rectangle,
* relative to the image origin
* @param dirtyY the y coordinate of the dirty rectangle,
* relative to the image origin
* @param dirtyWidth the width of the dirty rectangle
* @param dirtyHeight the height of the dirty rectangle
*
* @see #imageBufferReset
* @see #imageReshaped
*/
public void imageUpdated(int dirtyX, int dirtyY,
int dirtyWidth, int dirtyHeight);
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that the frame has grabbed focus.
*/
public void focusGrabbed();
/**
* {@code JLightweightFrame} calls this method to notify the client
* application that the frame has ungrabbed focus.
*/
public void focusUngrabbed();
}
...@@ -641,4 +641,6 @@ class XFramePeer extends XDecoratedPeer implements FramePeer { ...@@ -641,4 +641,6 @@ class XFramePeer extends XDecoratedPeer implements FramePeer {
public Rectangle getBoundsPrivate() { public Rectangle getBoundsPrivate() {
return getBounds(); return getBounds();
} }
public void emulateActivation(boolean doActivate) {}
} }
...@@ -419,6 +419,10 @@ public final class XToolkit extends UNIXToolkit implements Runnable { ...@@ -419,6 +419,10 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
return peer; return peer;
} }
public FramePeer createLightweightFrame(LightweightFrame target) {
return null;
}
public FramePeer createFrame(Frame target) { public FramePeer createFrame(Frame target) {
FramePeer peer = new XFramePeer(target); FramePeer peer = new XFramePeer(target);
targetCreatedPeer(target, peer); targetCreatedPeer(target, peer);
......
...@@ -226,15 +226,15 @@ public class WEmbeddedFrame extends EmbeddedFrame { ...@@ -226,15 +226,15 @@ public class WEmbeddedFrame extends EmbeddedFrame {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void synthesizeWindowActivation(final boolean doActivate) { public void synthesizeWindowActivation(final boolean activate) {
if (!doActivate || EventQueue.isDispatchThread()) { if (!activate || EventQueue.isDispatchThread()) {
((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(doActivate); ((WFramePeer)getPeer()).emulateActivation(activate);
} else { } else {
// To avoid focus concurrence b/w IE and EmbeddedFrame // To avoid focus concurrence b/w IE and EmbeddedFrame
// activation is postponed by means of posting it to EDT. // activation is postponed by means of posting it to EDT.
EventQueue.invokeLater(new Runnable() { EventQueue.invokeLater(new Runnable() {
public void run() { public void run() {
((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(true); ((WFramePeer)getPeer()).emulateActivation(true);
} }
}); });
} }
......
...@@ -65,8 +65,6 @@ public class WEmbeddedFramePeer extends WFramePeer { ...@@ -65,8 +65,6 @@ public class WEmbeddedFramePeer extends WFramePeer {
public native Rectangle getBoundsPrivate(); public native Rectangle getBoundsPrivate();
public native void synthesizeWmActivate(boolean doActivate);
@Override @Override
public boolean isAccelCapable() { public boolean isAccelCapable() {
// REMIND: Temp workaround for issues with using HW acceleration // REMIND: Temp workaround for issues with using HW acceleration
......
...@@ -200,4 +200,11 @@ class WFramePeer extends WWindowPeer implements FramePeer { ...@@ -200,4 +200,11 @@ class WFramePeer extends WWindowPeer implements FramePeer {
public Rectangle getBoundsPrivate() { public Rectangle getBoundsPrivate() {
return getBounds(); return getBounds();
} }
// TODO: implement it in peers. WLightweightFramePeer may implement lw version.
public void emulateActivation(boolean activate) {
synthesizeWmActivate(activate);
}
private native void synthesizeWmActivate(boolean activate);
} }
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.windows;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import sun.awt.LightweightFrame;
public class WLightweightFramePeer extends WFramePeer {
public WLightweightFramePeer(LightweightFrame target) {
super(target);
}
private LightweightFrame getLwTarget() {
return (LightweightFrame)target;
}
@Override
public Graphics getGraphics() {
return getLwTarget().getGraphics();
}
@Override
public void show() {
super.show();
postEvent(new ComponentEvent((Component)getTarget(), ComponentEvent.COMPONENT_SHOWN));
}
@Override
public void hide() {
super.hide();
postEvent(new ComponentEvent((Component)getTarget(), ComponentEvent.COMPONENT_HIDDEN));
}
@Override
public void reshape(int x, int y, int width, int height) {
super.reshape(x, y, width, height);
postEvent(new ComponentEvent((Component) getTarget(), ComponentEvent.COMPONENT_MOVED));
postEvent(new ComponentEvent((Component) getTarget(), ComponentEvent.COMPONENT_RESIZED));
}
@Override
public void handleEvent(java.awt.AWTEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
emulateActivation(true);
}
super.handleEvent(e);
}
@Override
public void grab() {
getLwTarget().grabFocus();
}
@Override
public void ungrab() {
getLwTarget().ungrabFocus();
}
}
...@@ -37,6 +37,7 @@ import java.beans.PropertyChangeListener; ...@@ -37,6 +37,7 @@ import java.beans.PropertyChangeListener;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import sun.awt.AWTAutoShutdown; import sun.awt.AWTAutoShutdown;
import sun.awt.LightweightFrame;
import sun.awt.SunToolkit; import sun.awt.SunToolkit;
import sun.awt.Win32GraphicsDevice; import sun.awt.Win32GraphicsDevice;
import sun.awt.Win32GraphicsEnvironment; import sun.awt.Win32GraphicsEnvironment;
...@@ -398,6 +399,12 @@ public class WToolkit extends SunToolkit implements Runnable { ...@@ -398,6 +399,12 @@ public class WToolkit extends SunToolkit implements Runnable {
return peer; return peer;
} }
public FramePeer createLightweightFrame(LightweightFrame target) {
FramePeer peer = new WLightweightFramePeer(target);
targetCreatedPeer(target, peer);
return peer;
}
public CanvasPeer createCanvas(Canvas target) { public CanvasPeer createCanvas(Canvas target) {
CanvasPeer peer = new WCanvasPeer(target); CanvasPeer peer = new WCanvasPeer(target);
targetCreatedPeer(target, peer); targetCreatedPeer(target, peer);
......
...@@ -105,6 +105,7 @@ AwtFrame::AwtFrame() { ...@@ -105,6 +105,7 @@ AwtFrame::AwtFrame() {
m_parentWnd = NULL; m_parentWnd = NULL;
menuBar = NULL; menuBar = NULL;
m_isEmbedded = FALSE; m_isEmbedded = FALSE;
m_isLightweight = FALSE;
m_ignoreWmSize = FALSE; m_ignoreWmSize = FALSE;
m_isMenuDropped = FALSE; m_isMenuDropped = FALSE;
m_isInputMethodWindow = FALSE; m_isInputMethodWindow = FALSE;
...@@ -170,14 +171,13 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent) ...@@ -170,14 +171,13 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent)
* area of the browser is a Java Frame for parenting purposes, but * area of the browser is a Java Frame for parenting purposes, but
* really a Windows child window * really a Windows child window
*/ */
BOOL isEmbeddedInstance = FALSE;
BOOL isEmbedded = FALSE;
cls = env->FindClass("sun/awt/EmbeddedFrame"); cls = env->FindClass("sun/awt/EmbeddedFrame");
if (cls == NULL) { if (cls) {
return NULL; isEmbeddedInstance = env->IsInstanceOf(target, cls);
} }
INT_PTR handle; INT_PTR handle;
jboolean isEmbeddedInstance = env->IsInstanceOf(target, cls);
jboolean isEmbedded = FALSE;
if (isEmbeddedInstance) { if (isEmbeddedInstance) {
handle = static_cast<INT_PTR>(env->GetLongField(target, AwtFrame::handleID)); handle = static_cast<INT_PTR>(env->GetLongField(target, AwtFrame::handleID));
if (handle != 0) { if (handle != 0) {
...@@ -186,6 +186,13 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent) ...@@ -186,6 +186,13 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent)
} }
frame->m_isEmbedded = isEmbedded; frame->m_isEmbedded = isEmbedded;
BOOL isLightweight = FALSE;
cls = env->FindClass("sun/awt/LightweightFrame");
if (cls) {
isLightweight = env->IsInstanceOf(target, cls);
}
frame->m_isLightweight = isLightweight;
if (isEmbedded) { if (isEmbedded) {
hwndParent = (HWND)handle; hwndParent = (HWND)handle;
RECT rect; RECT rect;
...@@ -230,6 +237,23 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent) ...@@ -230,6 +237,23 @@ AwtFrame* AwtFrame::Create(jobject self, jobject parent)
rect.bottom-rect.top); rect.bottom-rect.top);
frame->InitPeerGraphicsConfig(env, self); frame->InitPeerGraphicsConfig(env, self);
AwtToolkit::GetInstance().RegisterEmbedderProcessId(hwndParent); AwtToolkit::GetInstance().RegisterEmbedderProcessId(hwndParent);
} else if (isLightweight) {
frame->m_isUndecorated = true;
frame->m_peerObject = env->NewGlobalRef(self);
frame->RegisterClass();
DWORD exStyle = 0;
DWORD style = WS_POPUP;
frame->CreateHWnd(env, L"",
style,
exStyle,
0, 0, 0, 0,
0,
NULL,
::GetSysColor(COLOR_WINDOWTEXT),
::GetSysColor(COLOR_WINDOWFRAME),
self);
} else { } else {
jint state = env->CallIntMethod(self, AwtFrame::getExtendedStateMID); jint state = env->CallIntMethod(self, AwtFrame::getExtendedStateMID);
DWORD exStyle; DWORD exStyle;
...@@ -345,16 +369,20 @@ LRESULT AwtFrame::ProxyWindowProc(UINT message, WPARAM wParam, LPARAM lParam, Ms ...@@ -345,16 +369,20 @@ LRESULT AwtFrame::ProxyWindowProc(UINT message, WPARAM wParam, LPARAM lParam, Ms
case WM_SETFOCUS: case WM_SETFOCUS:
if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain
if (!sm_suppressFocusAndActivation && IsEmbeddedFrame()) { if (!sm_suppressFocusAndActivation) {
if (IsLightweightFrame() || IsEmbeddedFrame()) {
AwtSetActiveWindow(); AwtSetActiveWindow();
} }
}
mr = mrConsume; mr = mrConsume;
break; break;
case WM_KILLFOCUS: case WM_KILLFOCUS:
if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain
if (!sm_suppressFocusAndActivation && IsEmbeddedFrame()) { if (!sm_suppressFocusAndActivation) {
if (IsLightweightFrame() || IsEmbeddedFrame()) {
AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL); AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL);
}
} else if (sm_restoreFocusAndActivation) { } else if (sm_restoreFocusAndActivation) {
if (AwtComponent::GetFocusedWindow() != NULL) { if (AwtComponent::GetFocusedWindow() != NULL) {
...@@ -640,6 +668,10 @@ AwtFrame::Show() ...@@ -640,6 +668,10 @@ AwtFrame::Show()
HWND hwnd = GetHWnd(); HWND hwnd = GetHWnd();
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
if (IsLightweightFrame()) {
return;
}
DTRACE_PRINTLN3("AwtFrame::Show:%s%s%s", DTRACE_PRINTLN3("AwtFrame::Show:%s%s%s",
m_iconic ? " iconic" : "", m_iconic ? " iconic" : "",
m_zoomed ? " zoomed" : "", m_zoomed ? " zoomed" : "",
...@@ -992,6 +1024,9 @@ BOOL AwtFrame::AwtSetActiveWindow(BOOL isMouseEventCause, UINT hittest) ...@@ -992,6 +1024,9 @@ BOOL AwtFrame::AwtSetActiveWindow(BOOL isMouseEventCause, UINT hittest)
// b) focus is requested to some of the frame's child. // b) focus is requested to some of the frame's child.
m_actualFocusedWindow = NULL; m_actualFocusedWindow = NULL;
} }
if (IsLightweightFrame()) {
return TRUE;
}
return AwtWindow::AwtSetActiveWindow(isMouseEventCause); return AwtWindow::AwtSetActiveWindow(isMouseEventCause);
} }
...@@ -1873,7 +1908,7 @@ Java_sun_awt_windows_WEmbeddedFramePeer_getBoundsPrivate(JNIEnv *env, jobject se ...@@ -1873,7 +1908,7 @@ Java_sun_awt_windows_WEmbeddedFramePeer_getBoundsPrivate(JNIEnv *env, jobject se
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_sun_awt_windows_WEmbeddedFramePeer_synthesizeWmActivate(JNIEnv *env, jobject self, jboolean doActivate) Java_sun_awt_windows_WFramePeer_synthesizeWmActivate(JNIEnv *env, jobject self, jboolean doActivate)
{ {
TRY; TRY;
......
...@@ -72,6 +72,8 @@ public: ...@@ -72,6 +72,8 @@ public:
/* Returns whether this frame is embedded in an external native frame. */ /* Returns whether this frame is embedded in an external native frame. */
INLINE BOOL IsEmbeddedFrame() { return m_isEmbedded; } INLINE BOOL IsEmbeddedFrame() { return m_isEmbedded; }
/* Returns whether this frame is lightweight. */
INLINE virtual BOOL IsLightweightFrame() { return m_isLightweight; }
INLINE BOOL IsSimpleWindow() { return FALSE; } INLINE BOOL IsSimpleWindow() { return FALSE; }
...@@ -169,6 +171,9 @@ private: ...@@ -169,6 +171,9 @@ private:
/* The frame is an EmbeddedFrame. */ /* The frame is an EmbeddedFrame. */
BOOL m_isEmbedded; BOOL m_isEmbedded;
/* The frame is a LightweightFrame */
BOOL m_isLightweight;
/* used so that calls to ::MoveWindow in SetMenuBar don't propogate /* used so that calls to ::MoveWindow in SetMenuBar don't propogate
because they are immediately followed by calls to Component.resize */ because they are immediately followed by calls to Component.resize */
BOOL m_ignoreWmSize; BOOL m_ignoreWmSize;
......
...@@ -143,6 +143,7 @@ public: ...@@ -143,6 +143,7 @@ public:
INLINE HICON GetHIcon() {return m_hIcon;}; INLINE HICON GetHIcon() {return m_hIcon;};
INLINE HICON GetHIconSm() {return m_hIconSm;}; INLINE HICON GetHIconSm() {return m_hIconSm;};
INLINE BOOL IsIconInherited() {return m_iconInherited;}; INLINE BOOL IsIconInherited() {return m_iconInherited;};
INLINE virtual BOOL IsLightweightFrame() {return FALSE;}
/* Post events to the EventQueue */ /* Post events to the EventQueue */
void SendComponentEvent(jint eventId); void SendComponentEvent(jint eventId);
...@@ -193,8 +194,10 @@ public: ...@@ -193,8 +194,10 @@ public:
// Execute on Toolkit only. // Execute on Toolkit only.
INLINE static LRESULT SynthesizeWmActivate(BOOL doActivate, HWND targetHWnd, HWND oppositeHWnd) { INLINE static LRESULT SynthesizeWmActivate(BOOL doActivate, HWND targetHWnd, HWND oppositeHWnd) {
AwtWindow *win = static_cast<AwtWindow*>(AwtComponent::GetComponent(targetHWnd));
if (doActivate && if (doActivate &&
(!::IsWindowVisible(targetHWnd) || ::IsIconic(::GetAncestor(targetHWnd, GA_ROOT)))) (!::IsWindowVisible(targetHWnd) || ::IsIconic(::GetAncestor(targetHWnd, GA_ROOT))) &&
(win == NULL || !win->IsLightweightFrame()))
{ {
// The activation is rejected if either: // The activation is rejected if either:
// - The toplevel is not visible // - The toplevel is not visible
......
<html>
<!--
Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
or visit www.oracle.com if you need additional information or have any
questions.
-->
<!--
@test
@bug 6243382 8006070
@summary Dragging of mouse outside of a List and Choice area don't work properly on XAWT
@author Dmitry.Cherepanov@SUN.COM area=awt.list
@run applet/manual=yesno MouseDraggedOutCauseScrollingTest.html
-->
<head>
<title> ManualYesNoTest </title>
</head>
<body>
<h1>ManualYesNoTest<br>Bug ID: </h1>
<p> See the dialog box (usually in upper left corner) for instructions</p>
<APPLET CODE="MouseDraggedOutCauseScrollingTest.class" WIDTH=200 HEIGHT=200></APPLET>
</body>
</html>
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
test
@bug 6243382 8006070
@summary Dragging of mouse outside of a List and Choice area don't work properly on XAWT
@author Dmitry.Cherepanov@SUN.COM area=awt.list
@run applet/manual=yesno MouseDraggedOutCauseScrollingTest.html
*/
import java.applet.Applet;
import java.awt.*;
public class MouseDraggedOutCauseScrollingTest extends Applet
{
Choice choice;
List singleList;
List multipleList;
public void init()
{
this.setLayout (new GridLayout (1, 3));
choice = new Choice();
singleList = new List(3, false);
multipleList = new List(3, true);
choice.add("Choice");
for (int i = 1; i < 100; i++){
choice.add(""+i);
}
singleList.add("Single list");
for (int i = 1; i < 100; i++)
singleList.add(""+i);
multipleList.add("Multiple list");
for (int i = 1; i < 100; i++)
multipleList.add(""+i);
this.add(choice);
this.add(singleList);
this.add(multipleList);
String toolkitName = Toolkit.getDefaultToolkit().getClass().getName();
if (!toolkitName.equals("sun.awt.X11.XToolkit")) {
String[] instructions =
{
"This test is not applicable to the current platform. Press PASS"
};
Sysout.createDialogWithInstructions( instructions );
} else {
String[] instructions =
{
"0) Please note, that this is only Motif/XAWT test. At first, make the applet active",
"1.1) Click on the choice",
"1.2) Press the left button of the mouse and keep on any item of the choice, for example 5",
"1.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
"1.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling UP of the list and selected item changes on the upper. If not, the test failed",
"1.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling DOWN of the list and selected item changes on the lower. If not, the test failed",
"-----------------------------------",
"2.1) Click on the single list",
"2.2) Press the left button of the mouse and keep on any item of the list, for example 5",
"2.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
"2.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling UP of the list and selected item changes on the upper. If not, the test failed",
"2.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling DOWN of the list and selected item changes on the lower. If not, the test failed",
"-----------------------------------",
"3.1) Click on the multiple list",
"3.2) Press the left button of the mouse and keep on any item of the list, for example 5",
"3.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
"3.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling of the list NO OCCURED and selected item NO CHANGES on the upper. If not, the test failed",
"3.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling of the list NO OCCURED and selected item NO CHANGES on the lower. If not, the test failed",
"4) Test passed."
};
Sysout.createDialogWithInstructions( instructions );
}
}//End init()
public void start ()
{
setSize (400,100);
setVisible(true);
validate();
}// start()
}// class ManualYesNoTest
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* 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 6430802 8008379
@summary WM should not hang after show()/close()
@author anthony.petrov@sun.com: area=awt.modal
@run main/manual ModalDialogMultiscreenTest
*/
/**
* ModalDialogMultiscreenTest.java
*
* summary: Tests whether a WM will hang on show()/close() a modal dialog in multiscreen mode
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ModalDialogMultiscreenTest
{
private static class ButtonActionListener implements ActionListener {
JFrame frame;
JDialog dialog;
public ButtonActionListener(JFrame frame, JDialog dialog) {
this.frame = frame;
this.dialog = dialog;
}
public void actionPerformed(ActionEvent e) {
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
}
public static class TestDialog extends JDialog {
public TestDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
super(owner, title, modal, gc);
setSize(200, 100);
JButton button = new JButton("Close");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
getContentPane().add(button);
}
}
private static void init()
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
Sysout.createDialog( );
if (gs.length < 2) {
System.out.println("Not multi-head environment, test not valid!");
ModalDialogMultiscreenTest.pass( );
}
String[] instructions =
{
"The test should be run on a multi-head X (non-xinerama) systems.",
"Otherwise click the Pass button right now.",
"You will see an open Frame on each screen your system has.",
"The frame has an 'Open dialog' button.",
"Clicking the button opens a modal dialog with a Close button.",
"The test procedure:",
"1. Open a dialog and close it with appropriate buttons.",
"2. Switch to another screen ($ DISPLAY=X.Y xprop)",
"3. Repeat steps 1-2 several times (about 3*<number-of-screens>)",
"If the test doesn't cause the window manager to hang, it's passed."
};
Sysout.printInstructions( instructions );
for (int i = 0; i < gs.length; i++) {
JFrame frame = new JFrame("Frame "+i,gs[i].getDefaultConfiguration());
JButton button = new JButton("Open Dialog");
button.setMinimumSize(new Dimension(200, 100));
button.setPreferredSize(new Dimension(200, 100));
button.setSize(new Dimension(200, 100));
button.addActionListener(new ButtonActionListener(frame, new TestDialog(frame, "Dialog #"+i, true, gs[i].getDefaultConfiguration())));
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
}//End init()
//ap203012: NO MORE CHANGES BELOW THIS LINE
/*****************************************************
* Standard Test Machinery Section
* DO NOT modify anything in this section -- it's a
* standard chunk of code which has all of the
* synchronisation necessary for the test harness.
* By keeping it the same in all tests, it is easier
* to read and understand someone else's test, as
* well as insuring that all tests behave correctly
* with the test harness.
* There is a section following this for test-defined
* classes
******************************************************/
private static boolean theTestPassed = false;
private static boolean testGeneratedInterrupt = false;
private static String failureMessage = "";
private static Thread mainThread = null;
private static int sleepTime = 300000;
public static void main( String args[] ) throws InterruptedException
{
mainThread = Thread.currentThread();
try
{
init();
}
catch( TestPassedException e )
{
//The test passed, so just return from main and harness will
// interepret this return as a pass
return;
}
//At this point, neither test passed nor test failed has been
// called -- either would have thrown an exception and ended the
// test, so we know we have multiple threads.
//Test involves other threads, so sleep and wait for them to
// called pass() or fail()
try
{
Thread.sleep( sleepTime );
//Timed out, so fail the test
throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
}
catch (InterruptedException e)
{
if( ! testGeneratedInterrupt ) throw e;
//reset flag in case hit this code more than once for some reason (just safety)
testGeneratedInterrupt = false;
if ( theTestPassed == false )
{
throw new RuntimeException( failureMessage );
}
}
}//main
public static synchronized void setTimeoutTo( int seconds )
{
sleepTime = seconds * 1000;
}
public static synchronized void pass()
{
Sysout.println( "The test passed." );
Sysout.println( "The test is over, hit Ctl-C to stop Java VM" );
//first check if this is executing in main thread
if ( mainThread == Thread.currentThread() )
{
//Still in the main thread, so set the flag just for kicks,
// and throw a test passed exception which will be caught
// and end the test.
theTestPassed = true;
throw new TestPassedException();
}
//pass was called from a different thread, so set the flag and interrupt
// the main thead.
theTestPassed = true;
testGeneratedInterrupt = true;
mainThread.interrupt();
}//pass()
public static synchronized void fail()
{
//test writer didn't specify why test failed, so give generic
fail( "it just plain failed! :-)" );
}
public static synchronized void fail( String whyFailed )
{
Sysout.println( "The test failed: " + whyFailed );
Sysout.println( "The test is over, hit Ctl-C to stop Java VM" );
//check if this called from main thread
if ( mainThread == Thread.currentThread() )
{
//If main thread, fail now 'cause not sleeping
throw new RuntimeException( whyFailed );
}
theTestPassed = false;
testGeneratedInterrupt = true;
failureMessage = whyFailed;
mainThread.interrupt();
}//fail()
}// class ModalDialogMultiscreenTest
//This exception is used to exit from any level of call nesting
// when it's determined that the test has passed, and immediately
// end the test.
class TestPassedException extends RuntimeException
{
}
//*********** End Standard Test Machinery Section **********
//************ Begin classes defined for the test ****************
// make listeners in a class defined here, and instantiate them in init()
/* Example of a class which may be written as part of a test
class NewClass implements anInterface
{
static int newVar = 0;
public void eventDispatched(AWTEvent e)
{
//Counting events to see if we get enough
eventCount++;
if( eventCount == 20 )
{
//got enough events, so pass
ModalDialogMultiscreenTest.pass();
}
else if( tries == 20 )
{
//tried too many times without getting enough events so fail
ModalDialogMultiscreenTest.fail();
}
}// eventDispatched()
}// NewClass class
*/
//************** End classes defined for the test *******************
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog implements ActionListener
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
Panel buttonP = new Panel();
Button passB = new Button( "pass" );
Button failB = new Button( "fail" );
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
passB = new Button( "pass" );
passB.setActionCommand( "pass" );
passB.addActionListener( this );
buttonP.add( "East", passB );
failB = new Button( "fail" );
failB.setActionCommand( "fail" );
failB.addActionListener( this );
buttonP.add( "West", failB );
add( "South", buttonP );
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
//catch presses of the passed and failed buttons.
//simply call the standard pass() or fail() static methods of
//ModalDialogMultiscreenTest
public void actionPerformed( ActionEvent e )
{
if( e.getActionCommand() == "pass" )
{
ModalDialogMultiscreenTest.pass();
}
else
{
ModalDialogMultiscreenTest.fail();
}
}
}// TestDialog class
/* /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -22,8 +22,8 @@ ...@@ -22,8 +22,8 @@
*/ */
/* /*
@test %I% %E% @test
@bug 6572263 6571808 @bug 6572263 6571808 8005920
@summary PIT:FileDialog minimized to taskbar(through 'Show Desktop')selecting the fileDialog using windowList @summary PIT:FileDialog minimized to taskbar(through 'Show Desktop')selecting the fileDialog using windowList
@author dmitry.cherepanov: area=awt.modal @author dmitry.cherepanov: area=awt.modal
@run main/manual Winkey @run main/manual Winkey
...@@ -48,12 +48,14 @@ public class Winkey ...@@ -48,12 +48,14 @@ public class Winkey
String[] instructions = String[] instructions =
{ {
" 0. This test is for MS Windows only, if you use other OS, press \"pass\" button.",
" 1. there is a frame with a 'show modal' button, ", " 1. there is a frame with a 'show modal' button, ",
" 2. press the button to show a modal dialog, ", " 2. press the button to show a modal dialog, ",
" 3. the modal dialog will be shown over the frame, ", " 3. the modal dialog will be shown over the frame, ",
" 4. please verify that all (5.1, 5.2.1, 5.2.2) the following tests pass: ", " 4. please verify that all (5.1, 5.2.1, 5.2.2) the following tests pass: ",
" ", " ",
" 5.1. press combination Windows Key and M key to minimize all windows, ", " 5.1. press combination Windows Key and M key to minimize all windows, ",
" note that the modal dialog and modal blocked windows are NOT minimized",
" 5.2. press combination Windows Key and D key to show desktop, ", " 5.2. press combination Windows Key and D key to show desktop, ",
" 5.2.1. restore the dialog by choosing this one in the ALT-TAB list, ", " 5.2.1. restore the dialog by choosing this one in the ALT-TAB list, ",
" 5.2.2. restore the dialog by mouse click on taskbar (on java or any other item)", " 5.2.2. restore the dialog by mouse click on taskbar (on java or any other item)",
......
/* /*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,17 +23,20 @@ ...@@ -23,17 +23,20 @@
/* /*
* @test * @test
* @bug 7192955 * @bug 7192955 8000183
* @summary Tests that all properties are bound * @summary Tests that all properties are bound
* @author Sergey Malenkov * @author Sergey Malenkov
*/ */
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.List; import java.util.List;
public class Test7192955 { public class Test7192955 {
public static void main(String[] args) { public static void main(String[] args) throws IntrospectionException {
if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) { if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
throw new Error("a simple property is not bound"); throw new Error("a simple property is not bound");
} }
...@@ -43,6 +46,12 @@ public class Test7192955 { ...@@ -43,6 +46,12 @@ public class Test7192955 {
if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) { if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
throw new Error("a read-only property is not bound"); throw new Error("a read-only property is not bound");
} }
PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals("test") && pd.isBound()) {
throw new Error("a simple property is bound without superclass");
}
}
} }
public static class BaseBean { public static class BaseBean {
......
/*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Portions Copyright (c) 2013 IBM Corporation
*/
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import javax.swing.DefaultButtonModel;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.html.HTMLEditorKit;
import sun.awt.SunToolkit;
/*
* @test
* @bug 8008289
* @summary Shared ButtonModel instance should deregister previous listeners.
* @author Frank Ding
*/
public class bug7189299 {
private static JEditorPane html;
private static JFrame frame;
private static void setup() {
/**
* Note the input type is not restricted to "submit". Types "image",
* "checkbox", "radio" have the same problem.
*/
html = new JEditorPane("text/html",
"<html><body><form action=\"http://localhost.cgi\">"
+ "<input type=submit name=submit value=\"submit\"/>"
+ "</form></body></html>");
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(html, BorderLayout.CENTER);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void doTest() {
/*
* Calling updateComponentTreeUI creates a new FormView instance with
* its own associated JButton instance. The same DefaultButtonModel
* instance is used for both FormView's.
*
* The action listeners associated with (the JButton for) the first
* FormView should be unregistered from this common DefaultButtonModel,
* such that only those for the new FormView remain.
*/
SwingUtilities.updateComponentTreeUI(html);
}
private static void verifySingleDefaultButtonModelListener() {
HTMLEditorKit htmlEditorKit = (HTMLEditorKit) html.getEditorKit();
StyleContext.NamedStyle style = ((StyleContext.NamedStyle) htmlEditorKit
.getInputAttributes());
DefaultButtonModel model = ((DefaultButtonModel) style
.getAttribute(StyleConstants.ModelAttribute));
ActionListener[] listeners = model.getActionListeners();
int actionListenerNum = listeners.length;
if (actionListenerNum != 1) {
throw new RuntimeException(
"Expected single ActionListener object registered with "
+ "DefaultButtonModel; found " + actionListenerNum
+ " listeners registered.");
}
int changeListenerNum = model.getChangeListeners().length;
if (changeListenerNum != 1) {
throw new RuntimeException(
"Expected at most one ChangeListener object registered "
+ "with DefaultButtonModel; found " + changeListenerNum
+ " listeners registered.");
}
int itemListenerNum = model.getItemListeners().length;
if (itemListenerNum != 1) {
throw new RuntimeException(
"Expected at most one ItemListener object registered "
+ "with DefaultButtonModel; found " + itemListenerNum
+ " listeners registered.");
}
}
public static void main(String[] args) throws Exception {
final SunToolkit toolkit = ((SunToolkit) Toolkit.getDefaultToolkit());
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
setup();
}
});
toolkit.realSync();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
verifySingleDefaultButtonModelListener();
doTest();
verifySingleDefaultButtonModelListener();
} finally {
frame.dispose();
}
}
});
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 6877495
@summary JTextField and JTextArea does not support supplementary characters
@author Alexander Scherbatiy
@run main SuplementaryCharactersTransferTest
*/
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.datatransfer.*;
import sun.awt.datatransfer.*;
import sun.awt.datatransfer.DataTransferer.ReencodingInputStream;
public class SuplementaryCharactersTransferTest {
public static final long TEXT_FORMAT = 13;
public static void main(String[] args) throws Exception {
DataTransferer dataTransferer = new TestDataTransferer();
dataTransferer.registerTextFlavorProperties("UNICODE TEXT", "utf-16le", "\r\n", "2");
ByteTransferable transferable = new ByteTransferable();
ReencodingInputStream is = dataTransferer.new ReencodingInputStream(transferable.getByteInputStream(), TEXT_FORMAT,
DataTransferer.getTextCharset(transferable.getDataFlavor()), transferable);
byte[] bytes = transferable.getBytes();
byte[] result = new byte[bytes.length];
is.read(result);
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != result[i]) {
throw new RuntimeException("Characters are not equal!");
}
}
}
static class ByteTransferable implements Transferable, ClipboardOwner {
private final DataFlavor dataFlavor;
public ByteTransferable() throws Exception {
dataFlavor = DataFlavor.getTextPlainUnicodeFlavor();
}
public DataFlavor getDataFlavor() {
return dataFlavor;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{dataFlavor};
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(dataFlavor);
}
public byte[] getBytes() {
return new byte[]{97, 0, 64, -40, 32, -36, 98, 0};
}
public InputStream getByteInputStream() {
return new ByteArrayInputStream(getBytes());
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(dataFlavor)) {
return getByteInputStream();
} else {
throw new UnsupportedFlavorException(flavor);
}
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}
}
static class TestDataTransferer extends DataTransferer {
@Override
public String getDefaultUnicodeEncoding() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isLocaleDependentTextFormat(long format) {
return false;
}
@Override
public boolean isFileFormat(long format) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isImageFormat(long format) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected Long getFormatForNativeAsLong(String str) {
return TEXT_FORMAT;
}
@Override
protected String getNativeForFormat(long format) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected ByteArrayOutputStream convertFileListToBytes(
ArrayList<String> fileList) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected String[] dragQueryFile(byte[] bytes) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected Image platformImageBytesOrStreamToImage(InputStream str,
byte[] bytes, long format) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected byte[] imageToPlatformBytes(Image image, long format)
throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册