diff options
author | Sven Gothel <[email protected]> | 2014-02-23 14:51:06 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2014-02-23 14:51:06 +0100 |
commit | 3352601e0860584509adf2b76f993d03893ded4b (patch) | |
tree | 974fccc8c0eb2f5ad9d4ffd741dfc35869ed67b5 /src/nativewindow | |
parent | f51933f0ebe9ae030c26c066e59a728ce08b8559 (diff) | |
parent | c67de337a8aaf52e36104c3f13e273aa19d21f1f (diff) |
Merge branch 'master' into stash_glyphcache
Conflicts:
make/scripts/tests.sh
src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java
src/jogl/classes/com/jogamp/graph/curve/Region.java
src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java
src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java
src/jogl/classes/com/jogamp/graph/curve/opengl/Renderer.java
src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java
src/jogl/classes/com/jogamp/graph/font/Font.java
src/jogl/classes/com/jogamp/opengl/math/VectorUtil.java
src/jogl/classes/jogamp/graph/curve/text/GlyphShape.java
src/jogl/classes/jogamp/graph/curve/text/GlyphString.java
src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java
src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java
src/jogl/classes/jogamp/graph/font/typecast/TypecastRenderer.java
Diffstat (limited to 'src/nativewindow')
102 files changed, 8686 insertions, 2621 deletions
diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java new file mode 100644 index 000000000..c98bf5436 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java @@ -0,0 +1,39 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class DelegatedUpstreamSurfaceHookMutableSize extends UpstreamSurfaceHookMutableSize { + final UpstreamSurfaceHook upstream; + + /** + * @param upstream optional upstream UpstreamSurfaceHook used for {@link #create(ProxySurface)} and {@link #destroy(ProxySurface)}. + * @param width initial width + * @param height initial height + */ + public DelegatedUpstreamSurfaceHookMutableSize(UpstreamSurfaceHook upstream, int width, int height) { + super(width, height); + this.upstream = upstream; + } + + @Override + public final void create(ProxySurface s) { + if(null != upstream) { + upstream.create(s); + } + } + + @Override + public final void destroy(ProxySurface s) { + if(null != upstream) { + upstream.destroy(s); + } + } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ width + "x" + height + ", " + upstream + "]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java new file mode 100644 index 000000000..1557f4e51 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java @@ -0,0 +1,54 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class DelegatedUpstreamSurfaceHookWithSurfaceSize implements UpstreamSurfaceHook { + final UpstreamSurfaceHook upstream; + final NativeSurface surface; + + /** + * @param upstream optional upstream UpstreamSurfaceHook used for {@link #create(ProxySurface)} and {@link #destroy(ProxySurface)}. + * @param surface mandatory {@link NativeSurface} used for {@link #getWidth(ProxySurface)} and {@link #getHeight(ProxySurface)} + */ + public DelegatedUpstreamSurfaceHookWithSurfaceSize(UpstreamSurfaceHook upstream, NativeSurface surface) { + this.upstream = upstream; + this.surface = surface; + if(null == surface) { + throw new IllegalArgumentException("given surface is null"); + } + } + + @Override + public final void create(ProxySurface s) { + if(null != upstream) { + upstream.create(s); + } + } + + @Override + public final void destroy(ProxySurface s) { + if(null != upstream) { + upstream.destroy(s); + } + } + + @Override + public final int getWidth(ProxySurface s) { + return surface.getWidth(); + } + + @Override + public final int getHeight(ProxySurface s) { + return surface.getHeight(); + } + + @Override + public String toString() { + final String us_s = null != surface ? ( surface.getClass().getName() + ": 0x" + Long.toHexString(surface.getSurfaceHandle()) + " " +surface.getWidth() + "x" + surface.getHeight() ) : "nil"; + return getClass().getSimpleName()+"["+upstream+", "+us_s+"]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java index 2d5af86b9..8b8ccb191 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java @@ -37,7 +37,14 @@ public class MutableGraphicsConfiguration extends DefaultGraphicsConfiguration { super(screen, capsChosen, capsRequested); } + @Override public void setChosenCapabilities(CapabilitiesImmutable caps) { super.setChosenCapabilities(caps); } + + @Override + public void setScreen(AbstractGraphicsScreen screen) { + super.setScreen(screen); + } + } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java index 38bd70a90..a8dd9165c 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,17 +20,18 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.nativewindow; import com.jogamp.common.GlueGenVersion; import com.jogamp.common.util.JogampVersion; import com.jogamp.common.util.VersionUtil; + import java.util.jar.Manifest; public class NativeWindowVersion extends JogampVersion { @@ -45,9 +46,10 @@ public class NativeWindowVersion extends JogampVersion { if(null == jogampCommonVersionInfo) { // volatile: ok synchronized(NativeWindowVersion.class) { if( null == jogampCommonVersionInfo ) { - final String packageName = "javax.media.nativewindow"; - final Manifest mf = VersionUtil.getManifest(NativeWindowVersion.class.getClassLoader(), packageName); - jogampCommonVersionInfo = new NativeWindowVersion(packageName, mf); + final String packageName1 = "javax.media.nativewindow"; // atomic packaging - and identity + final String packageName2 = "javax.media.opengl"; // all packaging + final Manifest mf = VersionUtil.getManifest(NativeWindowVersion.class.getClassLoader(), new String[]{ packageName1, packageName2 } ); + jogampCommonVersionInfo = new NativeWindowVersion(packageName1, mf); } } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java new file mode 100644 index 000000000..5838c7a56 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java @@ -0,0 +1,45 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class UpstreamSurfaceHookMutableSize implements UpstreamSurfaceHook.MutableSize { + int width, height; + + /** + * @param width initial width + * @param height initial height + */ + public UpstreamSurfaceHookMutableSize(int width, int height) { + this.width = width; + this.height = height; + } + + @Override + public final void setSize(int width, int height) { + this.width = width; + this.height = height; + } + + @Override + public final int getWidth(ProxySurface s) { + return width; + } + + @Override + public final int getHeight(ProxySurface s) { + return height; + } + @Override + public void create(ProxySurface s) { /* nop */ } + + @Override + public void destroy(ProxySurface s) { /* nop */ } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ width + "x" + height + "]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java new file mode 100644 index 000000000..e6fcc049c --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java @@ -0,0 +1,36 @@ +package com.jogamp.nativewindow; + +public class UpstreamSurfaceHookMutableSizePos extends UpstreamSurfaceHookMutableSize { + int x, y; + + /** + * @param width initial width + * @param height initial height + */ + public UpstreamSurfaceHookMutableSizePos(int x, int y, int width, int height) { + super(width, height); + this.x= x; + this.y= y; + } + + // @Override + public final void setPos(int x, int y) { + this.x= x; + this.y= y; + } + + public final int getX() { + return x; + } + + public final int getY() { + return y; + } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ x + "/" + y + " " + width + "x" + height + "]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 61d5e5c0d..aa9b876dd 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -57,7 +57,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple private GraphicsConfiguration config; AbstractGraphicsConfiguration encapsulated; - public AWTGraphicsConfiguration(AWTGraphicsScreen screen, + public AWTGraphicsConfiguration(AWTGraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, GraphicsConfiguration config, AbstractGraphicsConfiguration encapsulated) { super(screen, capsChosen, capsRequested); @@ -71,16 +71,17 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple this.config = config; this.encapsulated=null; } - + /** - * @param capsChosen if null, <code>capsRequested</code> is copied and aligned - * with the graphics Capabilities of the AWT Component to produce the chosen Capabilities. + * @param capsChosen if null, <code>capsRequested</code> is copied and aligned + * with the graphics {@link Capabilities} of the AWT Component to produce the chosen {@link Capabilities}. * Otherwise the <code>capsChosen</code> is used. + * @param capsRequested if null, default {@link Capabilities} are used, otherwise the given values. */ public static AWTGraphicsConfiguration create(Component awtComp, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { final GraphicsConfiguration awtGfxConfig = awtComp.getGraphicsConfiguration(); if(null==awtGfxConfig) { - throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsConfiguration @ "+awtComp); + throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsConfiguration @ "+awtComp); } final GraphicsDevice awtGraphicsDevice = awtGfxConfig.getDevice(); if(null==awtGraphicsDevice) { @@ -91,12 +92,15 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple final AWTGraphicsDevice awtDevice = new AWTGraphicsDevice(awtGraphicsDevice, AbstractGraphicsDevice.DEFAULT_UNIT); final AWTGraphicsScreen awtScreen = new AWTGraphicsScreen(awtDevice); + if(null==capsRequested) { + capsRequested = new Capabilities(); + } if(null==capsChosen) { GraphicsConfiguration gc = awtGraphicsDevice.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsRequested, gc); } - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(awtDevice); - final AbstractGraphicsConfiguration config = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, null, awtScreen); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(awtDevice, capsChosen); + final AbstractGraphicsConfiguration config = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, null, awtScreen, VisualIDHolder.VID_UNDEFINED); if(config instanceof AWTGraphicsConfiguration) { return (AWTGraphicsConfiguration) config; } @@ -105,10 +109,11 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple } // open access to superclass method + @Override public void setChosenCapabilities(CapabilitiesImmutable capsChosen) { super.setChosenCapabilities(capsChosen); } - + @Override public Object clone() { return super.clone(); @@ -167,7 +172,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple public String toString() { return getClass().getSimpleName()+"[" + getScreen() + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ ",\n\t" + config + ",\n\tencapsulated "+encapsulated+"]"; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java index 635e6d263..a7fa53577 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java index f4ee06e28..83d6efa75 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -87,6 +87,7 @@ public class AWTGraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return new AWTGraphicsScreen(AWTGraphicsDevice.createDefault()); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java new file mode 100644 index 000000000..44163fc73 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java @@ -0,0 +1,175 @@ +/** + * Copyright 2013 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.nativewindow.awt; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PrinterJob; + +import jogamp.nativewindow.awt.AWTMisc; + +/** + * Interface describing print lifecycle to support AWT printing, + * e.g. on AWT {@link javax.media.opengl.GLAutoDrawable GLAutoDrawable}s. + * <a name="impl"><h5>Implementations</h5></a> + * <p> + * Implementing {@link javax.media.opengl.GLAutoDrawable GLAutoDrawable} classes based on AWT + * supporting {@link Component#print(Graphics)} shall implement this interface. + * </p> + * <a name="usage"><h5>Usage</h5></a> + * <p> + * Users attempting to print an AWT {@link Container} containing {@link AWTPrintLifecycle} elements + * shall consider decorating the {@link Container#printAll(Graphics)} call with<br> + * {@link #setupPrint(double, double, int, int, int) setupPrint(..)} and {@link #releasePrint()} + * on all {@link AWTPrintLifecycle} elements in the {@link Container}.<br> + * To minimize this burden, a user can use {@link Context#setupPrint(Container, double, double, int, int, int) Context.setupPrint(..)}: + * <pre> + * Container cont; + * double scaleGLMatXY = 72.0/glDPI; + * int numSamples = 0; // leave multisampling as-is + * PrinterJob job; + * ... + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(cont, scaleGLMatXY, scaleGLMatXY, numSamples); + try { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + try { + job.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + } + } }); + } finally { + ctx.releasePrint(); + } + * + * </pre> + * </p> + */ +public interface AWTPrintLifecycle { + + public static final int DEFAULT_PRINT_TILE_SIZE = 1024; + + + /** + * Shall be called before {@link PrinterJob#print()}. + * <p> + * See <a href="#usage">Usage</a>. + * </p> + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + */ + void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight); + + /** + * Shall be called after {@link PrinterJob#print()}. + * <p> + * See <a href="#usage">Usage</a>. + * </p> + */ + void releasePrint(); + + /** + * Convenient {@link AWTPrintLifecycle} context simplifying calling {@link AWTPrintLifecycle#setupPrint(double, double, int, int, int) setupPrint(..)} + * and {@link AWTPrintLifecycle#releasePrint()} on all {@link AWTPrintLifecycle} elements of a {@link Container}. + * <p> + * See <a href="#usage">Usage</a>. + * </p> + */ + public static class Context { + /** + * <p> + * See <a href="#usage">Usage</a>. + * </p> + * + * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(double, double, int, int, int) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @return the context + */ + public static Context setupPrint(Container c, double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { + final Context t = new Context(c, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight); + t.setupPrint(c); + return t; + } + + /** + * <p> + * See <a href="#usage">Usage</a>. + * </p> + */ + public void releasePrint() { + count = AWTMisc.performAction(cont, AWTPrintLifecycle.class, releaseAction); + } + + /** + * @return count of performed actions of last {@link #setupPrint(Container, double, double, int, int, int) setupPrint(..)} or {@link #releasePrint()}. + */ + public int getCount() { return count; } + + private final Container cont; + private final double scaleMatX; + private final double scaleMatY; + private final int numSamples; + private final int tileWidth; + private final int tileHeight; + private int count; + + private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).setupPrint(scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight); + } }; + private final AWTMisc.ComponentAction releaseAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).releasePrint(); + } }; + + private Context(Container c, double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { + this.cont = c; + this.scaleMatX = scaleMatX; + this.scaleMatY = scaleMatY; + this.numSamples = numSamples; + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.count = 0; + } + private void setupPrint(Container c) { + count = AWTMisc.performAction(c, AWTPrintLifecycle.class, setupAction); + } + } +} diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index d78b4ac15..aadecb455 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -33,22 +33,31 @@ import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; + import javax.media.nativewindow.WindowClosingProtocol; import jogamp.nativewindow.awt.AWTMisc; public class AWTWindowClosingProtocol implements WindowClosingProtocol { - private Component comp; - private Runnable closingOperation; - private volatile boolean closingListenerSet = false; - private Object closingListenerLock = new Object(); + private final Component comp; + private Window listenTo; + private final Runnable closingOperationClose; + private final Runnable closingOperationNOP; + private final Object closingListenerLock = new Object(); private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE; private boolean defaultCloseOperationSetByUser = false; - public AWTWindowClosingProtocol(Component comp, Runnable closingOperation) { + /** + * @param comp mandatory AWT component which AWT Window is being queried by parent traversal + * @param closingOperationClose mandatory closing operation, triggered if windowClosing and {@link WindowClosingMode#DISPOSE_ON_CLOSE} + * @param closingOperationNOP optional closing operation, triggered if windowClosing and {@link WindowClosingMode#DO_NOTHING_ON_CLOSE} + */ + public AWTWindowClosingProtocol(Component comp, Runnable closingOperationClose, Runnable closingOperationNOP) { this.comp = comp; - this.closingOperation = closingOperation; + this.listenTo = null; + this.closingOperationClose = closingOperationClose; + this.closingOperationNOP = closingOperationNOP; } class WindowClosingAdapter extends WindowAdapter { @@ -59,54 +68,46 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { if( WindowClosingMode.DISPOSE_ON_CLOSE == op ) { // we have to issue this call right away, // otherwise the window gets destroyed - closingOperation.run(); + closingOperationClose.run(); + } else if( null != closingOperationNOP ){ + closingOperationNOP.run(); } } } WindowListener windowClosingAdapter = new WindowClosingAdapter(); - final boolean addClosingListenerImpl() { - Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.addWindowListener(windowClosingAdapter); - return true; - } - return false; - } - /** - * Adds this closing listener to the components Window if exist and only one time.<br> - * Hence you may call this method every time to ensure it has been set, - * ie in case the Window parent is not available yet. + * Adds this closing listener to the components Window if exist and only one time. + * <p> + * If the closing listener is already added, and {@link IllegalStateException} is thrown. + * </p> * - * @return + * @return true if added, otherwise false. + * @throws IllegalStateException */ - public final boolean addClosingListenerOneShot() { - if(!closingListenerSet) { // volatile: ok + public final boolean addClosingListener() throws IllegalStateException { synchronized(closingListenerLock) { - if(!closingListenerSet) { - closingListenerSet=addClosingListenerImpl(); - return closingListenerSet; - } + if(null != listenTo) { + throw new IllegalStateException("WindowClosingListener already set"); + } + listenTo = AWTMisc.getWindow(comp); + if(null!=listenTo) { + listenTo.addWindowListener(windowClosingAdapter); + return true; + } } - } - return false; + return false; } public final boolean removeClosingListener() { - if(closingListenerSet) { // volatile: ok synchronized(closingListenerLock) { - if(closingListenerSet) { - Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.removeWindowListener(windowClosingAdapter); - closingListenerSet = false; - return true; - } - } + if(null != listenTo) { + listenTo.removeWindowListener(windowClosingAdapter); + listenTo = null; + return true; + } } - } - return false; + return false; } /** @@ -115,6 +116,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { * otherwise return the AWT/Swing close operation value translated to * a {@link WindowClosingProtocol} value . */ + @Override public final WindowClosingMode getDefaultCloseOperation() { synchronized(closingListenerLock) { if(defaultCloseOperationSetByUser) { @@ -125,6 +127,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { return AWTMisc.getNWClosingOperation(comp); } + @Override public final WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { synchronized(closingListenerLock) { final WindowClosingMode _op = defaultCloseOperation; diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java new file mode 100644 index 000000000..eeec66376 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -0,0 +1,297 @@ +/** + * Copyright 2013 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.nativewindow.awt; + +import java.awt.Point; +import java.awt.color.ColorSpace; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.DataBuffer; +import java.awt.image.DirectColorModel; +import java.awt.image.SampleModel; +import java.awt.image.SinglePixelPackedSampleModel; +import java.awt.image.WritableRaster; +import java.nio.IntBuffer; +import java.util.Hashtable; + +import com.jogamp.common.nio.Buffers; + +/** + * {@link DataBuffer} specialization using NIO direct buffer of type {@link DataBuffer#TYPE_INT} as storage. + */ +public final class DirectDataBufferInt extends DataBuffer { + + public static class DirectWritableRaster extends WritableRaster { + protected DirectWritableRaster(SampleModel sampleModel, DirectDataBufferInt dataBuffer, Point origin) { + super(sampleModel, dataBuffer, origin); + } + } + + public static class BufferedImageInt extends BufferedImage { + final int customImageType; + public BufferedImageInt (int customImageType, ColorModel cm, WritableRaster raster, Hashtable<?,?> properties) { + super(cm, raster, false /* isRasterPremultiplied */, properties); + this.customImageType = customImageType; + } + + /** + * @return one of the custom image-type values {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, + * {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. + */ + public int getCustomType() { + return customImageType; + } + + @Override + public String toString() { + return "BufferedImageInt@"+Integer.toHexString(hashCode()) + +": custom/internal type = "+customImageType+"/"+getType() + +" "+getColorModel()+" "+getRaster(); + } + } + + /** + * Creates a {@link BufferedImageInt} using a {@link DirectColorModel direct color model} in {@link ColorSpace#CS_sRGB sRGB color space}.<br> + * It uses a {@link DirectWritableRaster} utilizing {@link DirectDataBufferInt} storage. + * <p> + * Note that due to using the custom storage type {@link DirectDataBufferInt}, the resulting + * {@link BufferedImage}'s {@link BufferedImage#getType() image-type} is of {@link BufferedImage#TYPE_CUSTOM TYPE_CUSTOM}. + * We are not able to change this detail, since the AWT image implementation associates the {@link BufferedImage#getType() image-type} + * with a build-in storage-type. + * Use {@link BufferedImageInt#getCustomType()} to retrieve the custom image-type, which will return the <code>imageType</code> + * value passed here. + * </p> + * + * @param width + * @param height + * @param imageType one of {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. + * @param location origin, if <code>null</code> 0/0 is assumed. + * @param properties <code>Hashtable</code> of + * <code>String</code>/<code>Object</code> pairs. Used for {@link BufferedImage#getProperty(String)} etc. + * @return + */ + public static BufferedImageInt createBufferedImage(int width, int height, int imageType, Point location, Hashtable<?,?> properties) { + final ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); + final int transferType = DataBuffer.TYPE_INT; + final int bpp, rmask, gmask, bmask, amask; + final boolean alphaPreMul; + switch( imageType ) { + case BufferedImage.TYPE_INT_ARGB: + bpp = 32; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0xff000000; + alphaPreMul = false; + break; + case BufferedImage.TYPE_INT_ARGB_PRE: + bpp = 32; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0xff000000; + alphaPreMul = true; + break; + case BufferedImage.TYPE_INT_RGB: + bpp = 24; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0x0; + alphaPreMul = false; + break; + case BufferedImage.TYPE_INT_BGR: + bpp = 24; + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + amask = 0x0; + alphaPreMul = false; + break; + default: + throw new IllegalArgumentException("Unsupported imageType, must be [INT_ARGB, INT_ARGB_PRE, INT_RGB, INT_BGR], has "+imageType); + } + final ColorModel colorModel = new DirectColorModel(colorSpace, bpp, rmask, gmask, bmask, amask, alphaPreMul, transferType); + final int[] bandMasks; + if ( 0 != amask ) { + bandMasks = new int[4]; + bandMasks[3] = amask; + } + else { + bandMasks = new int[3]; + } + bandMasks[0] = rmask; + bandMasks[1] = gmask; + bandMasks[2] = bmask; + + final DirectDataBufferInt dataBuffer = new DirectDataBufferInt(width*height); + if( null == location ) { + location = new Point(0,0); + } + final SinglePixelPackedSampleModel sppsm = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), + width, height, width /* scanLineStride */, bandMasks); + // IntegerComponentRasters must haveinteger DataBuffers: + // final WritableRaster raster = new IntegerInterleavedRaster(sppsm, dataBuffer, location); + // Not public: + // final WritableRaster raster = new SunWritableRaster(sppsm, dataBuffer, location); + final WritableRaster raster = new DirectWritableRaster(sppsm, dataBuffer, location); + + return new BufferedImageInt(imageType, colorModel, raster, properties); + } + + /** Default data bank. */ + private IntBuffer data; + + /** All data banks */ + private IntBuffer bankdata[]; + + /** + * Constructs an nio integer-based {@link DataBuffer} with a single bank + * and the specified size. + * + * @param size The size of the {@link DataBuffer}. + */ + public DirectDataBufferInt(int size) { + super(TYPE_INT, size); + data = Buffers.newDirectIntBuffer(size); + bankdata = new IntBuffer[1]; + bankdata[0] = data; + } + + /** + * Constructs an nio integer-based {@link DataBuffer} with the specified number of + * banks, all of which are the specified size. + * + * @param size The size of the banks in the {@link DataBuffer}. + * @param numBanks The number of banks in the a{@link DataBuffer}. + */ + public DirectDataBufferInt(int size, int numBanks) { + super(TYPE_INT,size,numBanks); + bankdata = new IntBuffer[numBanks]; + for (int i= 0; i < numBanks; i++) { + bankdata[i] = Buffers.newDirectIntBuffer(size); + } + data = bankdata[0]; + } + + /** + * Constructs an nio integer-based {@link DataBuffer} with a single bank using the + * specified array. + * <p> + * Only the first <code>size</code> elements should be used by accessors of + * this {@link DataBuffer}. <code>dataArray</code> must be large enough to + * hold <code>size</code> elements. + * </p> + * + * @param dataArray The integer array for the {@link DataBuffer}. + * @param size The size of the {@link DataBuffer} bank. + */ + public DirectDataBufferInt(IntBuffer dataArray, int size) { + super(TYPE_INT,size); + data = dataArray; + bankdata = new IntBuffer[1]; + bankdata[0] = data; + } + + /** + * Returns the default (first) int data array in {@link DataBuffer}. + * + * @return The first integer data array. + */ + public IntBuffer getData() { + return data; + } + + /** + * Returns the data array for the specified bank. + * + * @param bank The bank whose data array you want to get. + * @return The data array for the specified bank. + */ + public IntBuffer getData(int bank) { + return bankdata[bank]; + } + + /** + * Returns the requested data array element from the first (default) bank. + * + * @param i The data array element you want to get. + * @return The requested data array element as an integer. + * @see #setElem(int, int) + * @see #setElem(int, int, int) + */ + @Override + public int getElem(int i) { + return data.get(i+offset); + } + + /** + * Returns the requested data array element from the specified bank. + * + * @param bank The bank from which you want to get a data array element. + * @param i The data array element you want to get. + * @return The requested data array element as an integer. + * @see #setElem(int, int) + * @see #setElem(int, int, int) + */ + @Override + public int getElem(int bank, int i) { + return bankdata[bank].get(i+offsets[bank]); + } + + /** + * Sets the requested data array element in the first (default) bank + * to the specified value. + * + * @param i The data array element you want to set. + * @param val The integer value to which you want to set the data array element. + * @see #getElem(int) + * @see #getElem(int, int) + */ + @Override + public void setElem(int i, int val) { + data.put(i+offset, val); + } + + /** + * Sets the requested data array element in the specified bank + * to the integer value <code>i</code>. + * @param bank The bank in which you want to set the data array element. + * @param i The data array element you want to set. + * @param val The integer value to which you want to set the specified data array element. + * @see #getElem(int) + * @see #getElem(int, int) + */ + @Override + public void setElem(int bank, int i, int val) { + bankdata[bank].put(i+offsets[bank], val); + } +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 02dd746a0..20ab7a2ee 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,7 +29,7 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. @@ -37,14 +37,25 @@ package com.jogamp.nativewindow.awt; +import com.jogamp.common.os.Platform; +import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.nativewindow.MutableGraphicsConfiguration; import java.awt.Component; import java.awt.Container; +import java.awt.Cursor; +import java.awt.Window; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; import java.applet.Applet; + import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; @@ -53,11 +64,14 @@ import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.SurfaceUpdatedListener; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.PixelRectangle; import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; import jogamp.nativewindow.SurfaceUpdatedHelper; +import jogamp.nativewindow.awt.AWTMisc; import jogamp.nativewindow.jawt.JAWT; import jogamp.nativewindow.jawt.JAWTUtil; import jogamp.nativewindow.jawt.JAWT_Rectangle; @@ -67,12 +81,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // user properties protected boolean shallUseOffscreenLayer = false; - + // lifetime: forever - protected Component component; - private AWTGraphicsConfiguration config; // control access due to delegation - private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - private RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + protected final Component component; + private final AWTGraphicsConfiguration config; // control access due to delegation + private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); + private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + private final JAWTComponentListener jawtComponentListener; // lifetime: valid after lock but may change with each 1st lock, purges after invalidate private boolean isApplet; @@ -81,13 +96,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected long drawable; protected Rectangle bounds; protected Insets insets; - + private volatile long offscreenSurfaceLayer; + private long drawable_old; - + /** * Constructed by {@link jogamp.nativewindow.NativeWindowFactoryImpl#getNativeWindow(Object, AbstractGraphicsConfiguration)} * via this platform's specialization (X11, OSX, Windows, ..). - * + * * @param comp * @param config */ @@ -98,29 +114,142 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(! ( config instanceof AWTGraphicsConfiguration ) ) { throw new NativeWindowException("Error: AbstractGraphicsConfiguration is not an AWTGraphicsConfiguration: "+config); } + this.component = (Component)comp; this.config = (AWTGraphicsConfiguration) config; - init((Component)comp); - } - - private void init(Component windowObject) throws NativeWindowException { + this.jawtComponentListener = new JAWTComponentListener(); invalidate(); - this.component = windowObject; this.isApplet = false; + this.offscreenSurfaceLayer = 0; + } + private static String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); } + private String jawtStr() { return "JAWTWindow["+id(JAWTWindow.this)+"]"; } + + private class JAWTComponentListener implements ComponentListener, HierarchyListener { + private boolean isShowing; + + private String str(final Object obj) { + if( null == obj ) { + return "0xnil: null"; + } else if( obj instanceof Component ) { + final Component c = (Component)obj; + return id(obj)+": "+c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+ + ", displayable "+c.isDisplayable()+", "+c.getX()+"/"+c.getY()+" "+c.getWidth()+"x"+c.getHeight()+"]"; + } else { + return id(obj)+": "+obj.getClass().getSimpleName()+"[..]"; + } + } + private String s(final ComponentEvent e) { + return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+ + " ** COMP "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); + } + private String s(final HierarchyEvent e) { + return "visible[isShowing "+isShowing+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ + " ** COMP "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ + " ** CHANGED "+str(e.getChanged())+Platform.getNewline()+ + " ** CHANGEDPARENT "+str(e.getChangedParent())+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); + } + @Override + public final String toString() { + return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); + } + + private JAWTComponentListener() { + isShowing = component.isShowing(); + AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition .. + @Override + public void run() { + if(DEBUG) { + System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString()); + } + component.addComponentListener(JAWTComponentListener.this); + component.addHierarchyListener(JAWTComponentListener.this); + } } ); + } + + private final void detach() { + AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition .. + @Override + public void run() { + if(DEBUG) { + System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString()); + } + component.removeComponentListener(JAWTComponentListener.this); + component.removeHierarchyListener(JAWTComponentListener.this); + } } ); + } + + @Override + public final void componentResized(ComponentEvent e) { + if(DEBUG) { + System.err.println(jawtStr()+".componentResized: "+s(e)); + } + layoutSurfaceLayerIfEnabled(isShowing); + } + + @Override + public final void componentMoved(ComponentEvent e) { + if(DEBUG) { + System.err.println(jawtStr()+".componentMoved: "+s(e)); + } + layoutSurfaceLayerIfEnabled(isShowing); + } + + @Override + public final void componentShown(ComponentEvent e) { + if(DEBUG) { + System.err.println(jawtStr()+".componentShown: "+s(e)); + } + layoutSurfaceLayerIfEnabled(isShowing); + } + + @Override + public final void componentHidden(ComponentEvent e) { + if(DEBUG) { + System.err.println(jawtStr()+".componentHidden: "+s(e)); + } + layoutSurfaceLayerIfEnabled(isShowing); + } + + @Override + public final void hierarchyChanged(HierarchyEvent e) { + final boolean wasShowing = isShowing; + isShowing = component.isShowing(); + int action = 0; + if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags() ) ) { + if( e.getChanged() != component && wasShowing != isShowing ) { + // A parent component changed and caused a 'showing' state change, + // propagate to offscreen-layer! + layoutSurfaceLayerIfEnabled(isShowing); + action = 1; + } + } + if(DEBUG) { + final java.awt.Component changed = e.getChanged(); + final boolean displayable = changed.isDisplayable(); + final boolean showing = changed.isShowing(); + System.err.println(jawtStr()+".hierarchyChanged: action "+action+", displayable "+displayable+", showing [changed "+showing+", comp "+isShowing+"], "+s(e)); + } + } } - - public void setShallUseOffscreenLayer(boolean v) { - shallUseOffscreenLayer = v; - } - - public final boolean getShallUseOffscreenLayer() { - return shallUseOffscreenLayer; - } - - public final boolean isOffscreenLayerSurfaceEnabled() { - return isOffscreenLayerSurface; - } - + + private static String getThreadName() { return Thread.currentThread().getName(); } + protected synchronized void invalidate() { + if(DEBUG) { + System.err.println(jawtStr()+".invalidate() - "+jawtComponentListener.toString()); + if( isSurfaceLayerAttached() ) { + System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer)); + } + // Thread.dumpStack(); + } invalidateNative(); jawt = null; isOffscreenLayerSurface = false; @@ -131,33 +260,38 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void invalidateNative(); - protected final void updateBounds(JAWT_Rectangle jawtBounds) { - bounds.setX(jawtBounds.getX()); - bounds.setY(jawtBounds.getY()); - bounds.setWidth(jawtBounds.getWidth()); - bounds.setHeight(jawtBounds.getHeight()); - - if(component instanceof Container) { - java.awt.Insets contInsets = ((Container)component).getInsets(); - insets.setLeftWidth(contInsets.left); - insets.setRightWidth(contInsets.right); - insets.setTopHeight(contInsets.top); - insets.setBottomHeight(contInsets.bottom); + protected final boolean updateBounds(JAWT_Rectangle jawtBounds) { + final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); + final boolean changed = !bounds.equals(jb); + + if(changed) { + if(DEBUG) { + System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); + // Thread.dumpStack(); + } + bounds.set(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); + + if(component instanceof Container) { + final java.awt.Insets contInsets = ((Container)component).getInsets(); + insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom); + } } + return changed; } /** @return the JAWT_DrawingSurfaceInfo's (JAWT_Rectangle) bounds, updated with lock */ public final RectangleImmutable getBounds() { return bounds; } - + + @Override public final InsetsImmutable getInsets() { return insets; } public final Component getAWTComponent() { return component; } - - /** - * Returns true if the AWT component is parented to an {@link java.applet.Applet}, - * otherwise false. This information is valid only after {@link #lockSurface()}. + + /** + * Returns true if the AWT component is parented to an {@link java.applet.Applet}, + * otherwise false. This information is valid only after {@link #lockSurface()}. */ public final boolean isApplet() { return isApplet; @@ -168,70 +302,141 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return jawt; } - /** - * {@inheritDoc} - */ - public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException { + // + // OffscreenLayerOption + // + + @Override + public void setShallUseOffscreenLayer(boolean v) { + shallUseOffscreenLayer = v; + } + + @Override + public final boolean getShallUseOffscreenLayer() { + return shallUseOffscreenLayer; + } + + @Override + public final boolean isOffscreenLayerSurfaceEnabled() { + return isOffscreenLayerSurface; + } + + // + // OffscreenLayerSurface + // + + @Override + public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { throw new NativeWindowException("Not an offscreen layer surface"); } - int lockRes = lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { - throw new NativeWindowException("Could not lock (offscreen layer): "+this); - } - try { - if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle(): 0x"+Long.toHexString(layerHandle)); - } - attachSurfaceLayerImpl(layerHandle); - } finally { - unlockSurface(); - } - } - protected abstract void attachSurfaceLayerImpl(final long layerHandle); - - /** - * {@inheritDoc} + attachSurfaceLayerImpl(layerHandle); + offscreenSurfaceLayer = layerHandle; + component.repaint(); + } + protected void attachSurfaceLayerImpl(final long layerHandle) { + throw new UnsupportedOperationException("offscreen layer not supported"); + } + + /** + * Layout the offscreen layer according to the implementing class's constraints. + * <p> + * This method allows triggering a re-layout of the offscreen surface + * in case the implementation requires it. + * </p> + * <p> + * Call this method if any parent or ancestor's layout has been changed, + * which could affects the layout of this surface. + * </p> + * @see #isOffscreenLayerSurfaceEnabled() + * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ - public final void detachSurfaceLayer(final long layerHandle) throws NativeWindowException { - if( !isOffscreenLayerSurfaceEnabled() ) { - throw new java.lang.UnsupportedOperationException("Not an offscreen layer surface"); + protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) {} + + private final void layoutSurfaceLayerIfEnabled(boolean visible) throws NativeWindowException { + if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { + layoutSurfaceLayerImpl(offscreenSurfaceLayer, visible); } - int lockRes = lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { - throw new NativeWindowException("Could not lock (offscreen layer): "+this); + } + + + @Override + public final void detachSurfaceLayer() throws NativeWindowException { + if( 0 == offscreenSurfaceLayer) { + throw new NativeWindowException("No offscreen layer attached: "+this); } - try { - if(DEBUG) { - System.err.println("JAWTWindow.detachSurfaceHandle(): 0x"+Long.toHexString(layerHandle)); - } - detachSurfaceLayerImpl(layerHandle); - } finally { - unlockSurface(); + if(DEBUG) { + System.err.println("JAWTWindow.detachSurfaceHandle(): osh "+toHexString(offscreenSurfaceLayer)); } - } - protected abstract void detachSurfaceLayerImpl(final long layerHandle); - - // - // SurfaceUpdateListener - // + detachSurfaceLayerImpl(offscreenSurfaceLayer, detachSurfaceLayerNotify); + } + private final Runnable detachSurfaceLayerNotify = new Runnable() { + @Override + public void run() { + offscreenSurfaceLayer = 0; + } + }; - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + /** + * @param detachNotify Runnable to be called before native detachment + */ + protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { + throw new UnsupportedOperationException("offscreen layer not supported"); } - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + + @Override + public final long getAttachedSurfaceLayer() { + return offscreenSurfaceLayer; } - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + @Override + public final boolean isSurfaceLayerAttached() { + return 0 != offscreenSurfaceLayer; + } + + @Override + public final void setChosenCapabilities(CapabilitiesImmutable caps) { + ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); + config.setChosenCapabilities(caps); + } + + @Override + public final RecursiveLock getLock() { + return surfaceLock; + } + + @Override + public final boolean setCursor(final PixelRectangle pixelrect, final PointImmutable hotSpot) { + AWTEDTExecutor.singleton.invoke(false, new Runnable() { + public void run() { + Cursor c = null; + if( null == pixelrect || null == hotSpot ) { + c = Cursor.getDefaultCursor(); + } else { + final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY()); + try { + c = AWTMisc.getCursor(pixelrect, awtHotspot); + } catch (Exception e) { + e.printStackTrace(); + } + } + if( null != c ) { + component.setCursor(c); + } + } } ); + return true; + } + + @Override + public final boolean hideCursor() { + AWTEDTExecutor.singleton.invoke(false, new Runnable() { + public void run() { + component.setCursor(AWTMisc.getNullCursor()); + } } ); + return true; } - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { - surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - // // NativeSurface // @@ -243,59 +448,65 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, c = c.getParent(); } } - + /** - * If JAWT offscreen layer is supported, + * If JAWT offscreen layer is supported, * implementation shall respect {@link #getShallUseOffscreenLayer()} * and may respect {@link #isApplet()}. - * + * * @return The JAWT instance reflecting offscreen layer support, etc. - * + * * @throws NativeWindowException */ protected abstract JAWT fetchJAWTImpl() throws NativeWindowException; protected abstract int lockSurfaceImpl() throws NativeWindowException; protected void dumpJAWTInfo() { - if(null != jawt) { - System.err.println("JAWT version: 0x"+Integer.toHexString(jawt.getCachedVersion())+ - ", CA_LAYER: "+ JAWTUtil.isJAWTUsingOffscreenLayer(jawt)+ - ", isLayeredSurface "+isOffscreenLayerSurfaceEnabled()+", bounds "+bounds+", insets "+insets); - } else { - System.err.println("JAWT n/a, bounds "+bounds+", insets "+insets); - } + System.err.println(jawt2String(null).toString()); // Thread.dumpStack(); } - - public final int lockSurface() throws NativeWindowException { + + @Override + public final int lockSurface() throws NativeWindowException, RuntimeException { surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? if ( LOCK_SURFACE_NOT_READY == res ) { - determineIfApplet(); - try { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - adevice.lock(); + if( !component.isDisplayable() ) { + // W/o native peer, we cannot utilize JAWT for locking. + surfaceLock.unlock(); + if(DEBUG) { + System.err.println("JAWTWindow: Can't lock surface, component peer n/a. Component displayable "+component.isDisplayable()+", "+component); + Thread.dumpStack(); + } + } else { + determineIfApplet(); try { - jawt = fetchJAWTImpl(); - isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); - res = lockSurfaceImpl(); - if(LOCK_SUCCESS == res && drawable_old != drawable) { - res = LOCK_SURFACE_CHANGED; - if(DEBUG) { - System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable)); - // Thread.dumpStack(); + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + adevice.lock(); + try { + if(null == jawt) { // no need to re-fetch for each frame + jawt = fetchJAWTImpl(); + isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); + } + res = lockSurfaceImpl(); + if(LOCK_SUCCESS == res && drawable_old != drawable) { + res = LOCK_SURFACE_CHANGED; + if(DEBUG) { + System.err.println("JAWTWindow: surface change "+toHexString(drawable_old)+" -> "+toHexString(drawable)); + // Thread.dumpStack(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + adevice.unlock(); } } } finally { if (LOCK_SURFACE_NOT_READY >= res) { - adevice.unlock(); + surfaceLock.unlock(); } } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - surfaceLock.unlock(); - } } } return res; @@ -303,6 +514,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract void unlockSurfaceImpl() throws NativeWindowException; + @Override public final void unlockSurface() { surfaceLock.validateLocked(); drawable_old = drawable; @@ -310,7 +522,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if (surfaceLock.getHoldCount() == 1) { final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); try { - unlockSurfaceImpl(); + if(null != jawt) { + unlockSurfaceImpl(); + } } finally { adevice.unlock(); } @@ -318,47 +532,68 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, surfaceLock.unlock(); } + @Override public final boolean isSurfaceLockedByOtherThread() { return surfaceLock.isLockedByOtherThread(); } - public final boolean isSurfaceLocked() { - return surfaceLock.isLocked(); - } - + @Override public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } + @Override public boolean surfaceSwap() { return false; } + @Override + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + } + + @Override + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + } + + @Override + public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + } + + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); + } + + @Override public long getSurfaceHandle() { return drawable; } - - public final AWTGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - + + @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } + @Override public final long getDisplayHandle() { return getGraphicsConfiguration().getScreen().getDevice().getHandle(); } + @Override public final int getScreenIndex() { return getGraphicsConfiguration().getScreen().getIndex(); } - public int getWidth() { + @Override + public final int getWidth() { return component.getWidth(); } - public int getHeight() { + @Override + public final int getHeight() { return component.getHeight(); } @@ -366,41 +601,55 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // NativeWindow // - public synchronized void destroy() { - invalidate(); - component = null; // don't dispose the AWT component, since we are merely an immutable uplink + @Override + public void destroy() { + surfaceLock.lock(); + try { + if(DEBUG) { + System.err.println(jawtStr()+".destroy @ Thread "+getThreadName()); + } + jawtComponentListener.detach(); + invalidate(); + } finally { + surfaceLock.unlock(); + } } + @Override public final NativeWindow getParent() { return null; } + @Override public long getWindowHandle() { return drawable; } - + + @Override public final int getX() { return component.getX(); } + @Override public final int getY() { return component.getY(); } - + /** * {@inheritDoc} - * + * * <p> - * This JAWT default implementation is currently still using + * This JAWT default implementation is currently still using * a blocking implementation. It first attempts to retrieve the location * via a native implementation. If this fails, it tries the blocking AWT implementation. - * If the latter fails due to an external AWT tree-lock, the non block + * If the latter fails due to an external AWT tree-lock, the non block * implementation {@link #getLocationOnScreenNonBlocking(Point, Component)} is being used. * The latter simply traverse up to the AWT component tree and sums the rel. position. * We have to determine whether the latter is good enough for all cases, * currently only OS X utilizes the non blocking method per default. - * </p> + * </p> */ + @Override public Point getLocationOnScreen(Point storage) { Point los = getLocationOnScreenNative(storage); if(null == los) { @@ -410,7 +659,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, System.err.println("Warning: JAWT Lock hold, but not the AWT tree lock: "+this); Thread.dumpStack(); } - return getLocationOnScreenNonBlocking(storage, component); + if( null == storage ) { + storage = new Point(); + } + getLocationOnScreenNonBlocking(storage, component); + return storage; } java.awt.Point awtLOS = component.getLocationOnScreen(); if(null!=storage) { @@ -421,7 +674,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } return los; } - + protected Point getLocationOnScreenNative(Point storage) { int lockRes = lockSurface(); if(LOCK_SURFACE_NOT_READY == lockRes) { @@ -442,50 +695,84 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return d; } finally { unlockSurface(); - } + } } protected abstract Point getLocationOnScreenNativeImpl(int x, int y); - protected static Point getLocationOnScreenNonBlocking(Point storage, Component comp) { - int x = 0; - int y = 0; + protected static Component getLocationOnScreenNonBlocking(Point storage, Component comp) { + final java.awt.Insets insets = new java.awt.Insets(0, 0, 0, 0); // DEBUG + Component last = null; while(null != comp) { - x += comp.getX(); - y += comp.getY(); + final int dx = comp.getX(); + final int dy = comp.getY(); + if( DEBUG ) { + final java.awt.Insets ins = AWTMisc.getInsets(comp, false); + if( null != ins ) { + insets.bottom += ins.bottom; + insets.top += ins.top; + insets.left += ins.left; + insets.right += ins.right; + } + System.err.print("LOS: "+storage+" + "+comp.getClass().getName()+"["+dx+"/"+dy+", vis "+comp.isVisible()+", ins "+ins+" -> "+insets+"] -> "); + } + storage.translate(dx, dy); + if( DEBUG ) { + System.err.println(storage); + } + last = comp; + if( comp instanceof Window ) { // top-level heavy-weight ? + break; + } comp = comp.getParent(); } - if(null!=storage) { - storage.translate(x, y); - return storage; - } - return new Point(x, y); + return last; } - + + @Override public boolean hasFocus() { return component.hasFocus(); } - + + protected StringBuilder jawt2String(StringBuilder sb) { + if( null == sb ) { + sb = new StringBuilder(); + } + sb.append("JVM version: ").append(Platform.JAVA_VERSION).append(" ("). + append(Platform.JAVA_VERSION_NUMBER). + append(" update ").append(Platform.JAVA_VERSION_UPDATE).append(")").append(Platform.getNewline()); + if(null != jawt) { + sb.append("JAWT version: 0x").append(Integer.toHexString(jawt.getCachedVersion())). + append(", CA_LAYER: ").append(JAWTUtil.isJAWTUsingOffscreenLayer(jawt)). + append(", isLayeredSurface ").append(isOffscreenLayerSurfaceEnabled()).append(", bounds ").append(bounds).append(", insets ").append(insets); + } else { + sb.append("JAWT n/a, bounds ").append(bounds).append(", insets ").append(insets); + } + return sb; + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("JAWT-Window["+ - "windowHandle 0x"+Long.toHexString(getWindowHandle())+ - ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+ - ", bounds "+bounds+", insets "+insets+ - ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface); - if(null!=component) { - sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ - ", visible "+component.isVisible()); - } else { - sb.append(", component NULL"); - } + sb.append(jawtStr()+"["); + jawt2String(sb); + sb.append( ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface+ + ", attachedSurfaceLayer "+toHexString(getAttachedSurfaceLayer())+ + ", windowHandle "+toHexString(getWindowHandle())+ + ", surfaceHandle "+toHexString(getSurfaceHandle())+ + ", bounds "+bounds+", insets "+insets + ); + sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ + ", visible "+component.isVisible()); sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+ - ",\n\tconfig "+getPrivateGraphicsConfiguration()+ + ",\n\tconfig "+config+ ",\n\tawtComponent "+getAWTComponent()+ ",\n\tsurfaceLock "+surfaceLock+"]"); return sb.toString(); } + protected final String toHexString(long l) { + return "0x"+Long.toHexString(l); + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index 4ee336176..6dc52a702 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -36,25 +36,111 @@ import javax.media.nativewindow.*; /** Encapsulates a graphics device on EGL platforms. */ - public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - boolean closeDisplay = false; + final long[] nativeDisplayID = new long[1]; + /* final */ EGLDisplayLifecycleCallback eglLifecycleCallback; + + /** + * Hack to allow inject a EGL termination call. + * <p> + * FIXME: This shall be removed when relocated EGL to the nativewindow package, + * since then it can be utilized directly. + * </p> + */ + public interface EGLDisplayLifecycleCallback { + /** + * Implementation should issue an <code>EGL.eglGetDisplay(nativeDisplayID)</code> + * inclusive <code>EGL.eglInitialize(eglDisplayHandle, ..)</code> call. + * @param nativeDisplayID in/out array of size 1, passing the requested nativeVisualID, may return a different revised nativeVisualID handle + * @return the initialized EGL display ID, or <code>0</code> if not successful + */ + public long eglGetAndInitDisplay(long[] nativeDisplayID); + + /** + * Implementation should issue an <code>EGL.eglTerminate(eglDisplayHandle)</code> call. + * @param eglDisplayHandle + */ + void eglTerminate(long eglDisplayHandle); + } /** * Note that this is not an open connection, ie no native display handle exist. * This constructor exist to setup a default device connection/unit.<br> */ - public EGLGraphicsDevice(String connection, int unitID) { - super(NativeWindowFactory.TYPE_EGL, connection, unitID); + public EGLGraphicsDevice() { + super(NativeWindowFactory.TYPE_EGL, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + this.nativeDisplayID[0] = 0 ; // EGL.EGL_DEFAULT_DISPLAY + this.eglLifecycleCallback = null; } - /** Constructs a new EGLGraphicsDevice corresponding to the given EGL display handle. */ - public EGLGraphicsDevice(long eglDisplay, String connection, int unitID) { + public EGLGraphicsDevice(long nativeDisplayID, long eglDisplay, String connection, int unitID, EGLDisplayLifecycleCallback eglLifecycleCallback) { super(NativeWindowFactory.TYPE_EGL, connection, unitID, eglDisplay); + this.nativeDisplayID[0] = nativeDisplayID; + this.eglLifecycleCallback = eglLifecycleCallback; } - + + public long getNativeDisplayID() { return nativeDisplayID[0]; } + + @Override public Object clone() { return super.clone(); } + + /** + * Opens the EGL device if handle is null and it's {@link EGLDisplayLifecycleCallback} is valid. + * <p> + * {@inheritDoc} + * </p> + */ + @Override + public boolean open() { + if(null != eglLifecycleCallback && 0 == handle) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - EGLGraphicsDevice.open(): "+this); + } + handle = eglLifecycleCallback.eglGetAndInitDisplay(nativeDisplayID); + if(0 == handle) { + throw new NativeWindowException("EGLGraphicsDevice.open() failed: "+this); + } + return true; + } + return false; + } + + /** + * Closes the EGL device if handle is not null and it's {@link EGLDisplayLifecycleCallback} is valid. + * <p> + * {@inheritDoc} + * </p> + */ + @Override + public boolean close() { + if(null != eglLifecycleCallback && 0 != handle) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - EGLGraphicsDevice.close(): "+this); + } + eglLifecycleCallback.eglTerminate(handle); + } + return super.close(); + } + + @Override + public boolean isHandleOwner() { + return null != eglLifecycleCallback; + } + @Override + public void clearHandleOwner() { + eglLifecycleCallback = null; + } + @Override + protected Object getHandleOwnership() { + return eglLifecycleCallback; + } + @Override + protected Object setHandleOwnership(Object newOwnership) { + final EGLDisplayLifecycleCallback oldOwnership = eglLifecycleCallback; + eglLifecycleCallback = (EGLDisplayLifecycleCallback) newOwnership; + return oldOwnership; + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java index 0dc788c17..99ca006fa 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -43,6 +43,7 @@ public class MacOSXGraphicsDevice extends DefaultGraphicsDevice implements Clone super(NativeWindowFactory.TYPE_MACOSX, AbstractGraphicsDevice.DEFAULT_CONNECTION, unitID); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index f4309617b..36bf646d5 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -30,62 +30,119 @@ package com.jogamp.nativewindow.swt; import com.jogamp.common.os.Platform; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; import org.eclipse.swt.graphics.GCData; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; +import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.VisualIDHolder; + import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.x11.X11Lib; public class SWTAccessor { - static final Field swt_control_handle; - static final boolean swt_uses_long_handles; - + private static final boolean DEBUG = true; + + private static final Field swt_control_handle; + private static final boolean swt_uses_long_handles; + + private static Object swt_osx_init = new Object(); + private static Field swt_osx_control_view = null; + private static Field swt_osx_view_id = null; + + private static final String nwt; + public static final boolean isOSX; + public static final boolean isWindows; + public static final boolean isX11; + public static final boolean isX11GTK; + // X11/GTK, Windows/GDI, .. - static final String str_handle = "handle"; - + private static final String str_handle = "handle"; + // OSX/Cocoa - static final String str_view = "view"; // OSX - static final String str_id = "id"; // OSX + private static final String str_osx_view = "view"; // OSX + private static final String str_osx_id = "id"; // OSX // static final String str_NSView = "org.eclipse.swt.internal.cocoa.NSView"; - - static final Method swt_control_internal_new_GC; - static final Method swt_control_internal_dispose_GC; - static final String str_internal_new_GC = "internal_new_GC"; - static final String str_internal_dispose_GC = "internal_dispose_GC"; - - static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; - static final Class<?> OS_gtk_class; - static final Method OS_gtk_widget_realize; - static final Method OS_gtk_widget_unrealize; - static final Method OS_GTK_WIDGET_WINDOW; - static final Method OS_gdk_x11_drawable_get_xdisplay; - static final Method OS_gdk_x11_drawable_get_xid; - static final String str_gtk_widget_realize = "gtk_widget_realize"; - static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; - static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; - static final String str_gdk_x11_drawable_get_xdisplay = "gdk_x11_drawable_get_xdisplay"; - static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; - + + private static final Method swt_control_internal_new_GC; + private static final Method swt_control_internal_dispose_GC; + private static final String str_internal_new_GC = "internal_new_GC"; + private static final String str_internal_dispose_GC = "internal_dispose_GC"; + + private static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; + public static final Class<?> OS_gtk_class; + private static final String str_OS_gtk_version = "GTK_VERSION"; + public static final VersionNumber OS_gtk_version; + + private static final Method OS_gtk_widget_realize; + private static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) + private static final Method OS_GTK_WIDGET_WINDOW; + private static final Method OS_gtk_widget_get_window; + private static final Method OS_gdk_x11_drawable_get_xdisplay; + private static final Method OS_gdk_x11_display_get_xdisplay; + private static final Method OS_gdk_window_get_display; + private static final Method OS_gdk_x11_drawable_get_xid; + private static final Method OS_gdk_x11_window_get_xid; + private static final Method OS_gdk_window_set_back_pixmap; + + private static final String str_gtk_widget_realize = "gtk_widget_realize"; + private static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; + private static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; + private static final String str_gtk_widget_get_window = "gtk_widget_get_window"; + private static final String str_gdk_x11_drawable_get_xdisplay = "gdk_x11_drawable_get_xdisplay"; + private static final String str_gdk_x11_display_get_xdisplay = "gdk_x11_display_get_xdisplay"; + private static final String str_gdk_window_get_display = "gdk_window_get_display"; + private static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; + private static final String str_gdk_x11_window_get_xid = "gdk_x11_window_get_xid"; + private static final String str_gdk_window_set_back_pixmap = "gdk_window_set_back_pixmap"; + + private static final VersionNumber GTK_VERSION_2_14_0 = new VersionNumber(2, 14, 0); + private static final VersionNumber GTK_VERSION_2_24_0 = new VersionNumber(2, 24, 0); + private static final VersionNumber GTK_VERSION_3_0_0 = new VersionNumber(3, 0, 0); + + private static VersionNumber GTK_VERSION(int version) { + // return (major << 16) + (minor << 8) + micro; + final int micro = ( version ) & 0x0f; + final int minor = ( version >> 8 ) & 0x0f; + final int major = ( version >> 16 ) & 0x0f; + return new VersionNumber(major, minor, micro); + } + static { + AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override + public Object run() { + NativeWindowFactory.initSingleton(); // last resort .. + return null; + } } ); + + nwt = NativeWindowFactory.getNativeWindowType(false); + isOSX = NativeWindowFactory.TYPE_MACOSX == nwt; + isWindows = NativeWindowFactory.TYPE_WINDOWS == nwt; + isX11 = NativeWindowFactory.TYPE_X11 == nwt; + Field f = null; - - if(NativeWindowFactory.TYPE_MACOSX != NativeWindowFactory.getNativeWindowType(false) ) { + if( !isOSX ) { try { f = Control.class.getField(str_handle); } catch (Exception ex) { throw new NativeWindowException(ex); } - } + } swt_control_handle = f; // maybe null ! - + boolean ulh; if (null != swt_control_handle) { ulh = swt_control_handle.getGenericType().toString().equals(long.class.toString()); @@ -95,7 +152,7 @@ public class SWTAccessor { swt_uses_long_handles = ulh; // System.err.println("SWT long handles: " + swt_uses_long_handles); // System.err.println("Platform 64bit: "+Platform.is64Bit()); - + Method m=null; try { m = ReflectionUtil.getMethod(Control.class, str_internal_new_GC, new Class[] { GCData.class }); @@ -103,51 +160,88 @@ public class SWTAccessor { throw new NativeWindowException(ex); } swt_control_internal_new_GC = m; - + try { if(swt_uses_long_handles) { - m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { long.class, GCData.class }); + m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { long.class, GCData.class }); } else { - m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { int.class, GCData.class }); + m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { int.class, GCData.class }); } } catch (NoSuchMethodException ex) { throw new NativeWindowException(ex); } swt_control_internal_dispose_GC = m; - Class<?> c=null; - Method m1=null, m2=null, m3=null, m4=null, m5=null; - Class<?> handleType = swt_uses_long_handles ? long.class : int.class ; - if( NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false) ) { + Class<?> c=null; + VersionNumber _gtk_version = new VersionNumber(0, 0, 0); + Method m1=null, m2=null, m3=null, m4=null, m5=null, m6=null, m7=null, m8=null, m9=null, ma=null; + final Class<?> handleType = swt_uses_long_handles ? long.class : int.class ; + if( isX11 ) { + // mandatory try { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); - m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); - m2 = c.getDeclaredMethod(str_gtk_widget_unrealize, handleType); - m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); - m4 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); - m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); + Field field_OS_gtk_version = c.getField(str_OS_gtk_version); + _gtk_version = GTK_VERSION(field_OS_gtk_version.getInt(null)); + m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); + if (_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { + m4 = c.getDeclaredMethod(str_gtk_widget_get_window, handleType); + } else { + m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); + } + if (_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { + m6 = c.getDeclaredMethod(str_gdk_x11_display_get_xdisplay, handleType); + m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); + } else { + m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); + } + if (_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { + m9 = c.getDeclaredMethod(str_gdk_x11_window_get_xid, handleType); + } else { + m8 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); + } + ma = c.getDeclaredMethod(str_gdk_window_set_back_pixmap, handleType, handleType, boolean.class); } catch (Exception ex) { throw new NativeWindowException(ex); } + // optional + try { + m2 = c.getDeclaredMethod(str_gtk_widget_unrealize, handleType); + } catch (Exception ex) { } } OS_gtk_class = c; + OS_gtk_version = _gtk_version; OS_gtk_widget_realize = m1; OS_gtk_widget_unrealize = m2; OS_GTK_WIDGET_WINDOW = m3; - OS_gdk_x11_drawable_get_xdisplay = m4; - OS_gdk_x11_drawable_get_xid = m5; + OS_gtk_widget_get_window = m4; + OS_gdk_x11_drawable_get_xdisplay = m5; + OS_gdk_x11_display_get_xdisplay = m6; + OS_gdk_window_get_display = m7; + OS_gdk_x11_drawable_get_xid = m8; + OS_gdk_x11_window_get_xid = m9; + OS_gdk_window_set_back_pixmap = ma; + + isX11GTK = isX11 && null != OS_gtk_class; + + if(DEBUG) { + System.err.println("SWTAccessor.<init>: GTK Version: "+OS_gtk_version); + } } - static Object getIntOrLong(long arg) { + private static Number getIntOrLong(long arg) { if(swt_uses_long_handles) { return new Long(arg); } return new Integer((int) arg); } - - static void callStaticMethodL2V(Method m, long arg) { + + private static void callStaticMethodL2V(Method m, long arg) { ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); } - - static long callStaticMethodL2L(Method m, long arg) { + + private static void callStaticMethodLLZ2V(Method m, long arg0, long arg1, boolean arg3) { + ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg0), getIntOrLong(arg1), Boolean.valueOf(arg3) }); + } + + private static long callStaticMethodL2L(Method m, long arg) { Object o = ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); if(o instanceof Number) { return ((Number)o).longValue(); @@ -155,82 +249,194 @@ public class SWTAccessor { throw new InternalError("SWT method "+m.getName()+" didn't return int or long but "+o.getClass()); } } - + + // + // Public properties + // + public static boolean isUsingLongHandles() { return swt_uses_long_handles; } - public static long getHandle(Control swtControl) { + public static boolean useX11GTK() { return isX11GTK; } + public static VersionNumber GTK_VERSION() { return OS_gtk_version; } + + // + // Common GTK + // + + public static long gdk_widget_get_window(long handle) { + final long window; + if (OS_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { + window = callStaticMethodL2L(OS_gtk_widget_get_window, handle); + } else { + window = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); + } + if(0 == window) { + throw new NativeWindowException("Null gtk-window-handle of SWT handle 0x"+Long.toHexString(handle)); + } + return window; + } + + public static long gdk_window_get_xdisplay(long window) { + final long xdisplay; + if (OS_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { + final long display = callStaticMethodL2L(OS_gdk_window_get_display, window); + if(0 == display) { + throw new NativeWindowException("Null display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + xdisplay = callStaticMethodL2L(OS_gdk_x11_display_get_xdisplay, display); + } else { + xdisplay = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, window); + } + if(0 == xdisplay) { + throw new NativeWindowException("Null x11-display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xdisplay; + } + + public static long gdk_window_get_xwindow(long window) { + final long xWindow; + if (OS_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { + xWindow = callStaticMethodL2L(OS_gdk_x11_window_get_xid, window); + } else { + xWindow = callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, window); + } + if(0 == xWindow) { + throw new NativeWindowException("Null x11-window-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xWindow; + } + + public static void gdk_window_set_back_pixmap(long window, long pixmap, boolean parent_relative) { + callStaticMethodLLZ2V(OS_gdk_window_set_back_pixmap, window, pixmap, parent_relative); + } + + // + // Common any toolkit + // + + /** + * @param swtControl the SWT Control to retrieve the native widget-handle from + * @return the native widget-handle + * @throws NativeWindowException if the widget handle is null + */ + public static long getHandle(Control swtControl) throws NativeWindowException { long h = 0; - if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + if( isOSX ) { + synchronized(swt_osx_init) { + try { + if(null == swt_osx_view_id) { + swt_osx_control_view = Control.class.getField(str_osx_view); + Object view = swt_osx_control_view.get(swtControl); + swt_osx_view_id = view.getClass().getField(str_osx_id); + h = swt_osx_view_id.getLong(view); + } else { + h = swt_osx_view_id.getLong( swt_osx_control_view.get(swtControl) ); + } + } catch (Exception ex) { + throw new NativeWindowException(ex); + } + } + } else { try { - Field fView = Control.class.getField(str_view); - Object view = fView.get(swtControl); - Field fId = view.getClass().getField(str_id); - return fId.getLong(view); + h = swt_control_handle.getLong(swtControl); } catch (Exception ex) { throw new NativeWindowException(ex); - } + } } - - try { - h = swt_control_handle.getLong(swtControl); - } catch (Exception ex) { - throw new NativeWindowException(ex); + if(0 == h) { + throw new NativeWindowException("Null widget-handle of SWT "+swtControl.getClass().getName()+": "+swtControl.toString()); } return h; } - public static void setRealized(final Control swtControl, final boolean realize) { + public static void setRealized(final Control swtControl, final boolean realize) + throws NativeWindowException + { + if(!realize && swtControl.isDisposed()) { + return; + } final long handle = getHandle(swtControl); - + if(null != OS_gtk_class) { invoke(true, new Runnable() { + @Override public void run() { if(realize) { callStaticMethodL2V(OS_gtk_widget_realize, handle); - } else { + } else if(null != OS_gtk_widget_unrealize) { callStaticMethodL2V(OS_gtk_widget_unrealize, handle); - } + } } }); } } - - public static AbstractGraphicsDevice getDevice(Control swtControl) { - long handle = getHandle(swtControl); - if( null != OS_gtk_class ) { - long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); - long displayHandle = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, widgedHandle); - // FIXME: May think about creating a private non-shared X11 Display handle, like we use to for AWT - // to avoid locking problems ! - return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false); + + /** + * @param swtControl the SWT Control to retrieve the native device handle from + * @return the AbstractGraphicsDevice w/ the native device handle + * @throws NativeWindowException if the widget handle is null + * @throws UnsupportedOperationException if the windowing system is not supported + */ + public static AbstractGraphicsDevice getDevice(Control swtControl) throws NativeWindowException, UnsupportedOperationException { + final long handle = getHandle(swtControl); + if( isX11GTK ) { + final long xdisplay0 = gdk_window_get_xdisplay( gdk_widget_get_window( handle ) ); + return new X11GraphicsDevice(xdisplay0, AbstractGraphicsDevice.DEFAULT_UNIT, false /* owner */); } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) ) { + if( isWindows ) { return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } - if( NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + if( isOSX ) { return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + } + + /** + * @param device + * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen + * @return + */ + public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { + return NativeWindowFactory.createScreen(device, screen); } - - public static long getWindowHandle(Control swtControl) { - long handle = getHandle(swtControl); - if( null != OS_gtk_class ) { - long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); - return callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, widgedHandle); + + public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { + if( isX11 ) { + return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || - NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + if( isWindows || isOSX ) { + return VisualIDHolder.VID_UNDEFINED; + } + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + } + + /** + * @param swtControl the SWT Control to retrieve the native window handle from + * @return the native window handle + * @throws NativeWindowException if the widget handle is null + * @throws UnsupportedOperationException if the windowing system is not supported + */ + public static long getWindowHandle(Control swtControl) throws NativeWindowException, UnsupportedOperationException { + final long handle = getHandle(swtControl); + if(0 == handle) { + throw new NativeWindowException("Null SWT handle of SWT control "+swtControl); + } + if( isX11GTK ) { + return gdk_window_get_xwindow( gdk_widget_get_window( handle ) ); + } + if( isWindows || isOSX ) { return handle; } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - + public static long newGC(final Control swtControl, final GCData gcData) { final Object[] o = new Object[1]; invoke(true, new Runnable() { + @Override public void run() { o[0] = ReflectionUtil.callMethod(swtControl, swt_control_internal_new_GC, new Object[] { gcData }); } @@ -244,6 +450,7 @@ public class SWTAccessor { public static void disposeGC(final Control swtControl, final long gc, final GCData gcData) { invoke(true, new Runnable() { + @Override public void run() { if(swt_uses_long_handles) { ReflectionUtil.callMethod(swtControl, swt_control_internal_dispose_GC, new Object[] { new Long(gc), gcData }); @@ -253,13 +460,128 @@ public class SWTAccessor { } }); } - + + /** + * Runs the specified action in an SWT compatible thread, which is: + * <ul> + * <li>Mac OSX + * <ul> + * <!--li>AWT EDT: In case AWT is available, the AWT EDT is the OSX UI main thread</li--> + * <li><i>Main Thread</i>: Run on OSX UI main thread. 'wait' is implemented on Java site via lock/wait on {@link RunnableTask} to not freeze OSX main thread.</li> + * </ul></li> + * <li>Linux, Windows, .. + * <ul> + * <li>Current thread.</li> + * </ul></li> + * </ul> + * @see Platform#AWT_AVAILABLE + * @see Platform#getOSType() + */ public static void invoke(boolean wait, Runnable runnable) { - if(Platform.OS_TYPE == Platform.OSType.MACOS) { + if( isOSX ) { + // Use SWT main thread! Only reliable config w/ -XStartOnMainThread !? OSXUtil.RunOnMainThread(wait, runnable); } else { runnable.run(); - } + } + } + + /** + * Runs the specified action on the SWT UI thread. + * <p> + * If <code>display</code> is disposed or the current thread is the SWT UI thread + * {@link #invoke(boolean, Runnable)} is being used. + * @see #invoke(boolean, Runnable) + */ + public static void invoke(org.eclipse.swt.widgets.Display display, boolean wait, Runnable runnable) { + if( display.isDisposed() || Thread.currentThread() == display.getThread() ) { + invoke(wait, runnable); + } else if( wait ) { + display.syncExec(runnable); + } else { + display.asyncExec(runnable); + } + } + + // + // Specific X11 GTK ChildWindow - Using plain X11 native parenting (works well) + // + + public static long createCompatibleX11ChildWindow(AbstractGraphicsScreen screen, Control swtControl, int visualID, int width, int height) { + final long handle = getHandle(swtControl); + final long parentWindow = gdk_widget_get_window( handle ); + gdk_window_set_back_pixmap (parentWindow, 0, false); + + final long x11ParentHandle = gdk_window_get_xwindow(parentWindow); + final long x11WindowHandle = X11Lib.CreateWindow(x11ParentHandle, screen.getDevice().getHandle(), screen.getIndex(), visualID, width, height, true, true); + + return x11WindowHandle; + } + + public static void resizeX11Window(AbstractGraphicsDevice device, Rectangle clientArea, long x11Window) { + X11Lib.SetWindowPosSize(device.getHandle(), x11Window, clientArea.x, clientArea.y, clientArea.width, clientArea.height); + } + public static void destroyX11Window(AbstractGraphicsDevice device, long x11Window) { + X11Lib.DestroyWindow(device.getHandle(), x11Window); + } + + // + // Specific X11 SWT/GTK ChildWindow - Using SWT/GTK native parenting (buggy - sporadic resize flickering, sporadic drop of rendering) + // + // FIXME: Need to use reflection for 32bit access as well ! + // + + // public static final int GDK_WA_TYPE_HINT = 1 << 9; + // public static final int GDK_WA_VISUAL = 1 << 6; + + public static long createCompatibleGDKChildWindow(Control swtControl, int visualID, int width, int height) { + return 0; + /** + final long handle = SWTAccessor.getHandle(swtControl); + final long parentWindow = gdk_widget_get_window( handle ); + + final long screen = OS.gdk_screen_get_default (); + final long gdkvisual = OS.gdk_x11_screen_lookup_visual (screen, visualID); + + final GdkWindowAttr attrs = new GdkWindowAttr(); + attrs.width = width > 0 ? width : 1; + attrs.height = height > 0 ? height : 1; + attrs.event_mask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | + OS.GDK_FOCUS_CHANGE_MASK | OS.GDK_POINTER_MOTION_MASK | + OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | + OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK | + OS.GDK_EXPOSURE_MASK | OS.GDK_VISIBILITY_NOTIFY_MASK | + OS.GDK_POINTER_MOTION_HINT_MASK; + attrs.window_type = OS.GDK_WINDOW_CHILD; + attrs.visual = gdkvisual; + + final long childWindow = OS.gdk_window_new (parentWindow, attrs, OS.GDK_WA_VISUAL|GDK_WA_TYPE_HINT); + OS.gdk_window_set_user_data (childWindow, handle); + OS.gdk_window_set_back_pixmap (parentWindow, 0, false); + + OS.gdk_window_show (childWindow); + OS.gdk_flush(); + return childWindow; */ + } + + public static void showGDKWindow(long gdkWindow) { + /* OS.gdk_window_show (gdkWindow); + OS.gdk_flush(); */ + } + public static void focusGDKWindow(long gdkWindow) { + /* + OS.gdk_window_show (gdkWindow); + OS.gdk_window_focus(gdkWindow, 0); + OS.gdk_flush(); */ + } + public static void resizeGDKWindow(Rectangle clientArea, long gdkWindow) { + /** + OS.gdk_window_move (gdkWindow, clientArea.x, clientArea.y); + OS.gdk_window_resize (gdkWindow, clientArea.width, clientArea.height); + OS.gdk_flush(); */ + } + + public static void destroyGDKWindow(long gdkWindow) { + // OS.gdk_window_destroy (gdkWindow); } - } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java index 5cabdf150..643982715 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -34,7 +34,7 @@ package com.jogamp.nativewindow.windows; import javax.media.nativewindow.*; -/** +/** * Encapsulates a graphics device on Windows platforms.<br> */ public class WindowsGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { @@ -47,6 +47,7 @@ public class WindowsGraphicsDevice extends DefaultGraphicsDevice implements Clon super(NativeWindowFactory.TYPE_WINDOWS, connection, unitID); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java index 0d2914c7d..120c86584 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -48,7 +48,7 @@ import jogamp.nativewindow.x11.XVisualInfo; public class X11GraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { private XVisualInfo info; - public X11GraphicsConfiguration(X11GraphicsScreen screen, + public X11GraphicsConfiguration(X11GraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, XVisualInfo info) { super(screen, capsChosen, capsRequested); @@ -71,12 +71,12 @@ public class X11GraphicsConfiguration extends MutableGraphicsConfiguration imple final public int getXVisualID() { return (null!=info)?(int)info.getVisualid():0; } - + @Override public String toString() { return getClass().getSimpleName()+"["+getScreen()+", visualID 0x" + Long.toHexString(getXVisualID()) + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ "]"; } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 308756b54..863e53bde 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -33,7 +33,6 @@ package com.jogamp.nativewindow.x11; -import jogamp.nativewindow.Debug; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; @@ -46,8 +45,8 @@ import javax.media.nativewindow.ToolkitLock; */ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - public static final boolean DEBUG = Debug.debug("GraphicsDevice"); - final boolean closeDisplay; + /* final */ boolean handleOwner; + final boolean isXineramaEnabled; /** Constructs a new X11GraphicsDevice corresponding to the given connection and default * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#getDefaultToolkitLock(String)}.<br> @@ -57,25 +56,21 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl */ public X11GraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_X11, connection, unitID); - closeDisplay = false; + handleOwner = false; + isXineramaEnabled = false; } /** Constructs a new X11GraphicsDevice corresponding to the given native display handle and default - * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long) */ public X11GraphicsDevice(long display, int unitID, boolean owner) { - // FIXME: derive unitID from connection could be buggy, one DISPLAY for all screens for example.. - super(NativeWindowFactory.TYPE_X11, X11Lib.XDisplayString(display), unitID, display); - if(0==display) { - throw new NativeWindowException("null display"); - } - closeDisplay = owner; + this(display, unitID, NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_X11, display), owner); } /** * @param display the Display connection - * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking in NEWT + * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking w/ private connection * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long, ToolkitLock) */ public X11GraphicsDevice(long display, int unitID, ToolkitLock locker, boolean owner) { @@ -83,16 +78,83 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl if(0==display) { throw new NativeWindowException("null display"); } - closeDisplay = owner; + handleOwner = owner; + isXineramaEnabled = X11Util.XineramaIsEnabled(this); + } + + /** + * Constructs a new X11GraphicsDevice corresponding to the given display connection. + * <p> + * The constructor opens the native connection and takes ownership. + * </p> + * @param displayConnection the semantic display connection name + * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking w/ private connection + * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long, ToolkitLock) + */ + public X11GraphicsDevice(String displayConnection, int unitID, ToolkitLock locker) { + super(NativeWindowFactory.TYPE_X11, displayConnection, unitID, 0, locker); + handleOwner = true; + open(); + isXineramaEnabled = X11Util.XineramaIsEnabled(this); + } + + private static int getDefaultScreenImpl(long dpy) { + return X11Lib.DefaultScreen(dpy); } + /** + * Returns the default screen number as referenced by the display connection, i.e. 'somewhere:0.1' -> 1 + * <p> + * Implementation uses the XLib macro <code>DefaultScreen(display)</code>. + * </p> + */ + public int getDefaultScreen() { + final long display = getHandle(); + if(0==display) { + throw new NativeWindowException("null display"); + } + final int ds = getDefaultScreenImpl(display); + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.getDefaultDisplay() of "+this+": "+ds+", count "+X11Lib.ScreenCount(display)); + } + return ds; + } + + public int getDefaultVisualID() { + final long display = getHandle(); + if(0==display) { + throw new NativeWindowException("null display"); + } + return X11Lib.DefaultVisualID(display, getDefaultScreenImpl(display)); + } + + public final boolean isXineramaEnabled() { + return isXineramaEnabled; + } + + @Override public Object clone() { return super.clone(); } + @Override + public boolean open() { + if(handleOwner && 0 == handle) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.open(): "+this); + } + handle = X11Util.openDisplay(connection); + if(0 == handle) { + throw new NativeWindowException("X11GraphicsDevice.open() failed: "+this); + } + return true; + } + return false; + } + + @Override public boolean close() { - // FIXME: shall we respect the unitID ? - if(closeDisplay && 0 != handle) { + if(handleOwner && 0 != handle) { if(DEBUG) { System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.close(): "+this); } @@ -100,5 +162,23 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return super.close(); } -} + @Override + public boolean isHandleOwner() { + return handleOwner; + } + @Override + public void clearHandleOwner() { + handleOwner = false; + } + @Override + protected Object getHandleOwnership() { + return Boolean.valueOf(handleOwner); + } + @Override + protected Object setHandleOwnership(Object newOwnership) { + final Boolean oldOwnership = Boolean.valueOf(handleOwner); + handleOwner = ((Boolean) newOwnership).booleanValue(); + return oldOwnership; + } +} diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 94013ec38..700937829 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -33,10 +33,12 @@ package com.jogamp.nativewindow.x11; -import javax.media.nativewindow.*; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.NativeWindowException; import jogamp.nativewindow.x11.X11Lib; -import jogamp.nativewindow.x11.X11Util; /** Encapsulates a screen index on X11 platforms. Objects of this type are passed to {@link @@ -48,7 +50,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl /** Constructs a new X11GraphicsScreen corresponding to the given native screen index. */ public X11GraphicsScreen(X11GraphicsDevice device, int screen) { - super(device, fetchScreen(device, screen)); + super(device, device.isXineramaEnabled() ? 0 : screen); } public static AbstractGraphicsScreen createScreenDevice(long display, int screenIdx, boolean owner) { @@ -56,21 +58,12 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return new X11GraphicsScreen(new X11GraphicsDevice(display, AbstractGraphicsDevice.DEFAULT_UNIT, owner), screenIdx); } - public long getDefaultVisualID() { + public int getVisualID() { // It still could be an AWT hold handle .. - long display = getDevice().getHandle(); - int scrnIdx = X11Lib.DefaultScreen(display); - return X11Lib.DefaultVisualID(display, scrnIdx); - } - - private static int fetchScreen(X11GraphicsDevice device, int screen) { - // It still could be an AWT hold handle .. - if(X11Util.XineramaIsEnabled(device.getHandle())) { - screen = 0; // Xinerama -> 1 screen - } - return screen; + return X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java index ebdaf2fbb..48f72e574 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -42,8 +42,9 @@ package javax.media.nativewindow; /** A marker interface describing a graphics configuration, visual, or pixel format in a toolkit-independent manner. */ - public interface AbstractGraphicsConfiguration extends VisualIDHolder, Cloneable { + public Object clone(); + /** * Return the screen this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 1dd01a274..31b64269f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,22 +29,25 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package javax.media.nativewindow; +import jogamp.nativewindow.Debug; + /** A interface describing a graphics device in a toolkit-independent manner. */ - public interface AbstractGraphicsDevice extends Cloneable { + public static final boolean DEBUG = Debug.debug("GraphicsDevice"); + /** Dummy connection value for a default connection where no native support for multiple devices is available */ public static String DEFAULT_CONNECTION = "decon"; @@ -54,6 +57,8 @@ public interface AbstractGraphicsDevice extends Cloneable { /** Default unit id for the 1st device: 0 */ public static int DEFAULT_UNIT = 0; + public Object clone(); + /** * Returns the type of the underlying subsystem, ie * NativeWindowFactory.TYPE_KD, NativeWindowFactory.TYPE_X11, .. @@ -84,10 +89,16 @@ public interface AbstractGraphicsDevice extends Cloneable { public int getUnitID(); /** - * Returns a unique ID String of this device using {@link #getType() type}, - * {@link #getConnection() connection} and {@link #getUnitID() unitID}.<br> - * The unique ID does not reflect the instance of the device, hence the handle is not included.<br> + * Returns a unique ID object of this device using {@link #getType() type}, + * {@link #getConnection() connection} and {@link #getUnitID() unitID} as it's key components. + * <p> + * The unique ID does not reflect the instance of the device, hence the handle is not included. * The unique ID may be used as a key for semantic device mapping. + * </p> + * <p> + * The returned string object reference is unique using {@link String#intern()} + * and hence can be used as a key itself. + * </p> */ public String getUniqueID(); @@ -98,27 +109,58 @@ public interface AbstractGraphicsDevice extends Cloneable { public long getHandle(); /** - * Optionally locking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock}. + * Optionally locking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock#lock()}. * The lock implementation must be recursive. */ public void lock(); - /** - * Optionally unlocking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock}. + /** + * Optionally unlocking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock#unlock()}. * The lock implementation must be recursive. + * + * @throws RuntimeException in case the lock is not acquired by this thread. */ public void unlock(); /** - * Optionally closing the device. + * @throws RuntimeException if current thread does not hold the lock + */ + public void validateLocked() throws RuntimeException; + + /** + * Optionally [re]opening the device if handle is <code>null</code>. * <p> - * The default implementation is a <code>NOP</code>, just setting the handle to <code>null</code>. + * The default implementation is a <code>NOP</code>. + * </p> + * <p> + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * issue the native open operation in case handle is <code>null</code>. * </p> - * The specific implementing, ie {@link com.jogamp.nativewindow.x11.X11GraphicsDevice}, - * shall have a enable/disable like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice#setCloseDisplay(boolean, boolean)},<br> - * which shall be invoked at creation time to determine ownership/role of freeing the resource.<br> * - * @return true if the handle was not <code>null</code>, otherwise false. + * @return true if the handle was <code>null</code> and opening was successful, otherwise false. + */ + public boolean open(); + + /** + * Optionally closing the device if handle is not <code>null</code>. + * <p> + * The default implementation {@link ToolkitLock#dispose() dispose} it's {@link ToolkitLock} and sets the handle to <code>null</code>. + * </p> + * <p> + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * issue the native close operation or skip it depending on the {@link #isHandleOwner() handles's ownership}. + * </p> + * + * @return true if the handle was not <code>null</code> and closing was successful, otherwise false. */ public boolean close(); + + /** + * @return <code>true</code> if instance owns the handle to issue {@link #close()}, otherwise <code>false</code>. + */ + public boolean isHandleOwner(); + + public void clearHandleOwner(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java index eb2cc9120..da8f12f3e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,11 +28,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -44,6 +44,8 @@ package javax.media.nativewindow; */ public interface AbstractGraphicsScreen extends Cloneable { + public Object clone(); + /** * Return the device this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index b422f50e6..9eed887b5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -44,7 +44,7 @@ package javax.media.nativewindow; must support, such as color depth per channel. It currently contains the minimal number of routines which allow configuration on all supported window systems. */ -public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparable { +public class Capabilities implements CapabilitiesImmutable, Cloneable { protected final static String na_str = "----" ; private int redBits = 8; @@ -62,15 +62,20 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl // Switch for on- or offscreen private boolean onscreen = true; + // offscreen bitmap mode + private boolean isBitmap = false; + /** Creates a Capabilities object. All attributes are in a default state. */ public Capabilities() {} + @Override public Object cloneMutable() { return clone(); } - + + @Override public Object clone() { try { return super.clone(); @@ -79,9 +84,32 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl } } + /** + * Copies all {@link Capabilities} values + * from <code>source</code> into this instance. + * @return this instance + */ + public Capabilities copyFrom(CapabilitiesImmutable other) { + redBits = other.getRedBits(); + greenBits = other.getGreenBits(); + blueBits = other.getBlueBits(); + alphaBits = other.getAlphaBits(); + backgroundOpaque = other.isBackgroundOpaque(); + onscreen = other.isOnscreen(); + isBitmap = other.isBitmap(); + transparentValueRed = other.getTransparentRedValue(); + transparentValueGreen = other.getTransparentGreenValue(); + transparentValueBlue = other.getTransparentBlueValue(); + transparentValueAlpha = other.getTransparentAlphaValue(); + return this; + } + + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + this.redBits; + hash = ((hash << 5) - hash) + ( this.onscreen ? 1 : 0 ); + hash = ((hash << 5) - hash) + ( this.isBitmap ? 1 : 0 ); hash = ((hash << 5) - hash) + this.greenBits; hash = ((hash << 5) - hash) + this.blueBits; hash = ((hash << 5) - hash) + this.alphaBits; @@ -90,10 +118,10 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl hash = ((hash << 5) - hash) + this.transparentValueGreen; hash = ((hash << 5) - hash) + this.transparentValueBlue; hash = ((hash << 5) - hash) + this.transparentValueAlpha; - hash = ((hash << 5) - hash) + ( this.onscreen ? 1 : 0 ); return hash; } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof CapabilitiesImmutable)) { @@ -105,31 +133,33 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl other.getBlueBits()==blueBits && other.getAlphaBits()==alphaBits && other.isBackgroundOpaque()==backgroundOpaque && - other.isOnscreen()==onscreen; - if(!backgroundOpaque) { - res = res && other.getTransparentRedValue()==transparentValueRed && - other.getTransparentGreenValue()==transparentValueGreen && - other.getTransparentBlueValue()==transparentValueBlue && - other.getTransparentAlphaValue()==transparentValueAlpha; + other.isOnscreen()==onscreen && + other.isBitmap()==isBitmap; + if(res && !backgroundOpaque) { + res = other.getTransparentRedValue()==transparentValueRed && + other.getTransparentGreenValue()==transparentValueGreen && + other.getTransparentBlueValue()==transparentValueBlue && + other.getTransparentAlphaValue()==transparentValueAlpha; } return res; } - /** comparing RGBA values only */ - public int compareTo(Object o) { - if ( ! ( o instanceof Capabilities ) ) { + /** + * Comparing RGBA values only + **/ + @Override + public int compareTo(final CapabilitiesImmutable caps) { + /** + if ( ! ( o instanceof CapabilitiesImmutable ) ) { Class<?> c = (null != o) ? o.getClass() : null ; - throw new ClassCastException("Not a Capabilities object: " + c); + throw new ClassCastException("Not a CapabilitiesImmutable object, but " + c); } + final CapabilitiesImmutable caps = (CapabilitiesImmutable) o; */ - final Capabilities caps = (Capabilities) o; - - final int a = ( alphaBits > 0 ) ? alphaBits : 1; - final int rgba = redBits * greenBits * blueBits * a; + final int rgba = redBits * greenBits * blueBits * ( alphaBits + 1 ); - final int xa = ( caps.alphaBits ) > 0 ? caps.alphaBits : 1; - final int xrgba = caps.redBits * caps.greenBits * caps.blueBits * xa; + final int xrgba = caps.getRedBits() * caps.getGreenBits() * caps.getBlueBits() * ( caps.getAlphaBits() + 1 ); if(rgba > xrgba) { return 1; @@ -148,13 +178,11 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl return VisualIDHolder.VID_UNDEFINED; default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - - /** Returns the number of bits requested for the color buffer's red - component. On some systems only the color depth, which is the - sum of the red, green, and blue bits, is considered. */ - public int getRedBits() { + + @Override + public final int getRedBits() { return redBits; } @@ -165,10 +193,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl this.redBits = redBits; } - /** Returns the number of bits requested for the color buffer's - green component. On some systems only the color depth, which is - the sum of the red, green, and blue bits, is considered. */ - public int getGreenBits() { + @Override + public final int getGreenBits() { return greenBits; } @@ -179,10 +205,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl this.greenBits = greenBits; } - /** Returns the number of bits requested for the color buffer's blue - component. On some systems only the color depth, which is the - sum of the red, green, and blue bits, is considered. */ - public int getBlueBits() { + @Override + public final int getBlueBits() { return blueBits; } @@ -192,99 +216,111 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl public void setBlueBits(int blueBits) { this.blueBits = blueBits; } - - /** Returns the number of bits requested for the color buffer's - alpha component. On some systems only the color depth, which is - the sum of the red, green, and blue bits, is considered. */ - public int getAlphaBits() { + + @Override + public final int getAlphaBits() { return alphaBits; } - /** Sets the number of bits requested for the color buffer's alpha - component. On some systems only the color depth, which is the - sum of the red, green, and blue bits, is considered. */ + /** + * Sets the number of bits requested for the color buffer's alpha + * component. On some systems only the color depth, which is the + * sum of the red, green, and blue bits, is considered. + * <p> + * <b>Note:</b> If alpha bits are <code>zero</code>, they are set to <code>one</code> + * by {@link #setBackgroundOpaque(boolean)} and it's OpenGL specialization <code>GLCapabilities::setSampleBuffers(boolean)</code>.<br/> + * Ensure to call this method after the above to ensure a <code>zero</code> value.</br> + * The above automated settings takes into account, that the user calls this method to <i>request</i> alpha bits, + * not to <i>reflect</i> a current state. Nevertheless if this is the case - call it at last. + * </p> + */ public void setAlphaBits(int alphaBits) { this.alphaBits = alphaBits; } - /** - * Defaults to true, ie. opaque surface. - * <p> - * On supported platforms, setting opaque to false may result in a translucent surface. </p> - * - * <p> - * Platform implementations may need an alpha component in the surface (eg. Windows), - * or expect pre-multiplied alpha values (eg. X11/XRender).<br> - * To unify the experience, this method also invokes {@link #setAlphaBits(int) setAlphaBits(1)} - * if {@link #getAlphaBits()} == 0.<br> - * Please note that in case alpha is required on the platform the - * clear color shall have an alpha lower than 1.0 to allow anything shining through. - * </p> - * - * <p> - * Mind that translucency may cause a performance penalty - * due to the composite work required by the window manager.</p> - * - * <p> - * The platform implementation may utilize the transparency RGBA values.<br> - * This is true for the original GLX transparency specification, which is no more used today.<br> - * Actually these values are currently not used by any implementation, - * so we may mark them deprecated soon, if this doesn't change.<br> - * </p> - */ + /** + * Sets whether the surface shall be opaque or translucent. + * <p> + * Platform implementations may need an alpha component in the surface (eg. Windows), + * or expect pre-multiplied alpha values (eg. X11/XRender).<br> + * To unify the experience, this method also invokes {@link #setAlphaBits(int) setAlphaBits(1)} + * if {@link #getAlphaBits()} == 0.<br> + * Please note that in case alpha is required on the platform the + * clear color shall have an alpha lower than 1.0 to allow anything shining through. + * </p> + * <p> + * Mind that translucency may cause a performance penalty + * due to the composite work required by the window manager. + * </p> + */ public void setBackgroundOpaque(boolean opaque) { - backgroundOpaque = opaque; - if(!opaque && getAlphaBits()==0) { - setAlphaBits(1); - } + backgroundOpaque = opaque; + if(!opaque && getAlphaBits()==0) { + setAlphaBits(1); + } } - /** Indicates whether the background of this OpenGL context should - be considered opaque. Defaults to true. - - @see #setBackgroundOpaque - */ - public boolean isBackgroundOpaque() { + @Override + public final boolean isBackgroundOpaque() { return backgroundOpaque; } - /** Sets whether the drawable surface supports onscreen. - Defaults to true. - */ + /** + * Sets whether the surface shall be on- or offscreen. + * <p> + * Defaults to true. + * </p> + * <p> + * If requesting an offscreen surface without further selection of it's mode, + * e.g. FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}, + * the implementation will choose the best available offscreen mode. + * </p> + * @param onscreen + */ public void setOnscreen(boolean onscreen) { this.onscreen=onscreen; } - /** Indicates whether the drawable surface is onscreen. - Defaults to true. - */ - public boolean isOnscreen() { + @Override + public final boolean isOnscreen() { return onscreen; } - /** Gets the transparent red value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentRedValue - */ - public int getTransparentRedValue() { return transparentValueRed; } + /** + * Requesting offscreen bitmap mode. + * <p> + * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. + * </p> + * <p> + * Defaults to false. + * </p> + * <p> + * Requesting offscreen bitmap mode disables the offscreen auto selection. + * </p> + */ + public void setBitmap(boolean enable) { + if(enable) { + setOnscreen(false); + } + isBitmap = enable; + } - /** Gets the transparent green value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentGreenValue - */ - public int getTransparentGreenValue() { return transparentValueGreen; } + @Override + public boolean isBitmap() { + return isBitmap; + } - /** Gets the transparent blue value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentBlueValue - */ - public int getTransparentBlueValue() { return transparentValueBlue; } + @Override + public final int getTransparentRedValue() { return transparentValueRed; } - /** Gets the transparent alpha value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentAlphaValue - */ - public int getTransparentAlphaValue() { return transparentValueAlpha; } + @Override + public final int getTransparentGreenValue() { return transparentValueGreen; } + + @Override + public final int getTransparentBlueValue() { return transparentValueBlue; } + + @Override + public final int getTransparentAlphaValue() { return transparentValueAlpha; } /** Sets the transparent red value for the frame buffer configuration, ranging from 0 to the maximum frame buffer value for red. @@ -314,33 +350,65 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl A value of -1 is interpreted as any value. */ public void setTransparentAlphaValue(int transValueAlpha) { transparentValueAlpha=transValueAlpha; } + @Override public StringBuilder toString(StringBuilder sink) { + return toString(sink, true); + } + + /** Returns a textual representation of this Capabilities + object. */ + @Override + public String toString() { + StringBuilder msg = new StringBuilder(); + msg.append("Caps["); + toString(msg); + msg.append("]"); + return msg.toString(); + } + + /** Return a textual representation of this object's on/off screen state. Use the given StringBuilder [optional]. */ + protected StringBuilder onoffScreenToString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); } if(onscreen) { sink.append("on-scr"); } else { - sink.append("offscr"); + sink.append("offscr["); } - sink.append(", rgba 0x").append(toHexString(redBits)).append("/").append(toHexString(greenBits)).append("/").append(toHexString(blueBits)).append("/").append(toHexString(alphaBits)); - if(backgroundOpaque) { - sink.append(", opaque"); + if(isBitmap) { + sink.append("bitmap"); + } else if(onscreen) { + sink.append("."); // no additional off-screen modes besides on-screen } else { - sink.append(", trans-rgba 0x").append(toHexString(transparentValueRed)).append("/").append(toHexString(transparentValueGreen)).append("/").append(toHexString(transparentValueBlue)).append("/").append(toHexString(transparentValueAlpha)); + sink.append("auto-cfg"); // auto-config off-screen mode } + sink.append("]"); + return sink; } - protected final String toHexString(int val) { return Integer.toHexString(val); } - /** Returns a textual representation of this Capabilities - object. */ - public String toString() { - StringBuilder msg = new StringBuilder(); - msg.append("Caps["); - toString(msg); - msg.append("]"); - return msg.toString(); + /** Element separator */ + protected static final String ESEP = "/"; + /** Component separator */ + protected static final String CSEP = ", "; + + protected StringBuilder toString(StringBuilder sink, boolean withOnOffScreen) { + if(null == sink) { + sink = new StringBuilder(); + } + sink.append("rgba ").append(redBits).append(ESEP).append(greenBits).append(ESEP).append(blueBits).append(ESEP).append(alphaBits); + if(backgroundOpaque) { + sink.append(", opaque"); + } else { + sink.append(", trans-rgba 0x").append(toHexString(transparentValueRed)).append(ESEP).append(toHexString(transparentValueGreen)).append(ESEP).append(toHexString(transparentValueBlue)).append(ESEP).append(toHexString(transparentValueAlpha)); + } + if(withOnOffScreen) { + sink.append(CSEP); + onoffScreenToString(sink); + } + return sink; } + protected final String toHexString(int val) { return Integer.toHexString(val); } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java index a306363dc..1f4db7997 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,11 +28,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -58,13 +58,13 @@ public interface CapabilitiesChooser { not necessarily required, that the chooser select that entry. <P> <em>Note:</em> this method is called automatically by the - {@link GraphicsConfigurationFactory#chooseGraphicsConfiguration} method + {@link GraphicsConfigurationFactory#chooseGraphicsConfiguration} method when an instance of this class is passed in to it. It should generally not be invoked by users directly, unless it is desired to delegate the choice to some other CapabilitiesChooser object. */ public int chooseCapabilities(CapabilitiesImmutable desired, - List /*<CapabilitiesImmutable>*/ available, + List<? extends CapabilitiesImmutable> available, int windowSystemRecommendedChoice); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java index 3d7362c40..c496a1535 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java @@ -33,51 +33,72 @@ import com.jogamp.common.type.WriteCloneable; /** * Specifies an immutable set of capabilities that a window's rendering context * must support, such as color depth per channel. - * + * * @see javax.media.nativewindow.Capabilities */ -public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable { +public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, Comparable<CapabilitiesImmutable> { /** - * Returns the number of bits requested for the color buffer's red + * Returns the number of bits for the color buffer's red * component. On some systems only the color depth, which is the sum of the * red, green, and blue bits, is considered. */ int getRedBits(); /** - * Returns the number of bits requested for the color buffer's green + * Returns the number of bits for the color buffer's green * component. On some systems only the color depth, which is the sum of the * red, green, and blue bits, is considered. */ int getGreenBits(); /** - * Returns the number of bits requested for the color buffer's blue + * Returns the number of bits for the color buffer's blue * component. On some systems only the color depth, which is the sum of the * red, green, and blue bits, is considered. */ int getBlueBits(); /** - * Returns the number of bits requested for the color buffer's alpha + * Returns the number of bits for the color buffer's alpha * component. On some systems only the color depth, which is the sum of the * red, green, and blue bits, is considered. */ int getAlphaBits(); /** - * Indicates whether the background of this OpenGL context should be - * considered opaque. Defaults to true. + * Returns whether an opaque or translucent surface is requested, supported or chosen. + * <p> + * Default is true, i.e. opaque. + * </p> */ boolean isBackgroundOpaque(); /** - * Indicates whether the drawable surface is onscreen. Defaults to true. + * Returns whether an on- or offscreen surface is requested, available or chosen. + * <p> + * Default is true, i.e. onscreen. + * </p> + * <p> + * Mind that an capabilities intance w/ <i>available</i> semantics + * may show onscreen, but also the offscreen modes FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}. + * This is valid, since one native configuration maybe used for either functionality. + * </p> */ boolean isOnscreen(); /** + * Returns whether bitmap offscreen mode is requested, available or chosen. + * <p> + * Default is false. + * </p> + * <p> + * For chosen capabilities, only the selected offscreen surface is set to <code>true</code>. + * </p> + */ + boolean isBitmap(); + + /** * Gets the transparent red value for the frame buffer configuration. This * value is undefined if; equals true. */ @@ -109,7 +130,7 @@ public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable { @Override int hashCode(); - /** Return a textual representation of this object. Use the given StringBuffer [optional]. */ + /** Return a textual representation of this object. Use the given StringBuilder [optional]. */ StringBuilder toString(StringBuilder sink); /** Returns a textual representation of this object. */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 48c4d31ce..77cbe2995 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -66,10 +66,19 @@ import jogamp.nativewindow.Debug; */ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { - private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); + private static final boolean DEBUG; + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); + } + + private final static int NO_SCORE = -9999999; + private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; + + @Override public int chooseCapabilities(final CapabilitiesImmutable desired, - final List /*<CapabilitiesImmutable>*/ available, + final List<? extends CapabilitiesImmutable> available, final int windowSystemRecommendedChoice) { if (DEBUG) { System.err.println("Desired: " + desired); @@ -92,17 +101,19 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { // Create score array int[] scores = new int[availnum]; - int NO_SCORE = -9999999; - int COLOR_MISMATCH_PENALTY_SCALE = 36; for (int i = 0; i < availnum; i++) { scores[i] = NO_SCORE; } // Compute score for each for (int i = 0; i < availnum; i++) { - CapabilitiesImmutable cur = (CapabilitiesImmutable) available.get(i); + final CapabilitiesImmutable cur = available.get(i); if (cur == null) { continue; } + if (desired.isOnscreen() && !cur.isOnscreen()) { + continue; // requested onscreen, but n/a + } + int score = 0; // Compute difference in color depth score += (COLOR_MISMATCH_PENALTY_SCALE * @@ -122,7 +133,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { System.err.println(" ]"); } - // Ready to select. Choose score closest to 0. + // Ready to select. Choose score closest to 0. int scoreClosestToZero = NO_SCORE; int chosenIndex = -1; for (int i = 0; i < availnum; i++) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java index a33c3792a..42d7f3a23 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -36,12 +36,12 @@ import jogamp.nativewindow.Debug; public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphicsConfiguration { protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration"); - + private AbstractGraphicsScreen screen; protected CapabilitiesImmutable capabilitiesChosen; protected CapabilitiesImmutable capabilitiesRequested; - public DefaultGraphicsConfiguration(AbstractGraphicsScreen screen, + public DefaultGraphicsConfiguration(AbstractGraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { if(null == screen) { throw new IllegalArgumentException("Null screen"); @@ -69,18 +69,22 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics } } + @Override final public AbstractGraphicsScreen getScreen() { return screen; } + @Override final public CapabilitiesImmutable getChosenCapabilities() { return capabilitiesChosen; } + @Override final public CapabilitiesImmutable getRequestedCapabilities() { return capabilitiesRequested; } + @Override public AbstractGraphicsConfiguration getNativeGraphicsConfiguration() { return this; } @@ -89,36 +93,37 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics final public int getVisualID(VIDType type) throws NativeWindowException { return capabilitiesChosen.getVisualID(type); } - + /** * Set the capabilities to a new value. * + * <p> * The use case for setting the Capabilities at a later time is - * a change of the graphics device in a multi-screen environment.<br> - * + * a change or re-validation of capabilities. + * </p> * @see javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(Capabilities, CapabilitiesChooser, AbstractGraphicsScreen) */ protected void setChosenCapabilities(CapabilitiesImmutable capsChosen) { - capabilitiesChosen = capsChosen; + this.capabilitiesChosen = capsChosen; } /** * Set a new screen. * + * <p> * the use case for setting a new screen at a later time is - * a change of the graphics device in a multi-screen environment.<br> - * - * A copy of the passed object is being used. + * a change of the graphics device in a multi-screen environment. + * </p> */ - final protected void setScreen(DefaultGraphicsScreen screen) { - this.screen = (AbstractGraphicsScreen) screen.clone(); + protected void setScreen(AbstractGraphicsScreen screen) { + this.screen = screen; } @Override public String toString() { return getClass().getSimpleName()+"[" + screen + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ "]"; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 187959a67..15ff2b1ac 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -37,10 +37,10 @@ import jogamp.nativewindow.NativeWindowFactoryImpl; public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice { private static final String separator = "_"; - private String type; - protected String connection; - protected int unitID; - protected String uniqueID; + private final String type; + protected final String connection; + protected final int unitID; + protected final String uniqueID; protected long handle; protected ToolkitLock toolkitLock; @@ -50,34 +50,24 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * @param type */ public DefaultGraphicsDevice(String type, String connection, int unitID) { - this.type = type; - this.connection = connection; - this.unitID = unitID; - this.uniqueID = getUniqueID(type, connection, unitID); - this.handle = 0; - this.toolkitLock = NativeWindowFactory.getDefaultToolkitLock(type); + this(type, connection, unitID, 0, NativeWindowFactory.getDefaultToolkitLock(type)); } /** * Create an instance with the system default {@link ToolkitLock}. - * gathered via {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + * gathered via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. * @param type * @param handle */ public DefaultGraphicsDevice(String type, String connection, int unitID, long handle) { - this.type = type; - this.connection = connection; - this.unitID = unitID; - this.uniqueID = getUniqueID(type, connection, unitID); - this.handle = handle; - this.toolkitLock = NativeWindowFactory.createDefaultToolkitLock(type, handle); + this(type, connection, unitID, handle, NativeWindowFactory.getDefaultToolkitLock(type, handle)); } /** - * Create an instance with the given {@link ToolkitLock} instance. + * Create an instance with the given {@link ToolkitLock} instance, or <i>null</i> {@link ToolkitLock} if null. * @param type * @param handle - * @param locker + * @param locker if null, a non blocking <i>null</i> lock is used. */ public DefaultGraphicsDevice(String type, String connection, int unitID, long handle, ToolkitLock locker) { this.type = type; @@ -97,49 +87,72 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } } + @Override public final String getType() { return type; } + @Override public final String getConnection() { return connection; } + @Override public final int getUnitID() { return unitID; } + @Override public final String getUniqueID() { return uniqueID; } + @Override public final long getHandle() { return handle; } /** - * No lock is performed on the graphics device per default, - * instead the aggregated recursive {@link ToolkitLock#lock()} is invoked. + * {@inheritDoc} + * <p> + * Locking is perfomed via delegation to {@link ToolkitLock#lock()}, {@link ToolkitLock#unlock()}. + * </p> * * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) */ + @Override public final void lock() { toolkitLock.lock(); } - /** - * No lock is performed on the graphics device per default, - * instead the aggregated recursive {@link ToolkitLock#unlock()} is invoked. + @Override + public final void validateLocked() throws RuntimeException { + toolkitLock.validateLocked(); + } + + /** + * {@inheritDoc} + * <p> + * Locking is perfomed via delegation to {@link ToolkitLock#lock()}, {@link ToolkitLock#unlock()}. + * </p> * * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) */ + @Override public final void unlock() { toolkitLock.unlock(); } + @Override + public boolean open() { + return false; + } + + @Override public boolean close() { + toolkitLock.dispose(); if(0 != handle) { handle = 0; return true; @@ -148,8 +161,53 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } @Override + public boolean isHandleOwner() { + return false; + } + + @Override + public void clearHandleOwner() { + } + + @Override public String toString() { - return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+"]"; + return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", owner "+isHandleOwner()+", "+toolkitLock+"]"; + } + + /** + * Set the native handle of the underlying native device + * and return the previous one. + */ + protected final long setHandle(long newHandle) { + final long oldHandle = handle; + handle = newHandle; + return oldHandle; + } + + protected Object getHandleOwnership() { + return null; + } + protected Object setHandleOwnership(Object newOwnership) { + return null; + } + + public static final void swapDeviceHandleAndOwnership(final DefaultGraphicsDevice aDevice1, final DefaultGraphicsDevice aDevice2) { + aDevice1.lock(); + try { + aDevice2.lock(); + try { + final long aDevice1Handle = aDevice1.getHandle(); + final long aDevice2Handle = aDevice2.setHandle(aDevice1Handle); + aDevice1.setHandle(aDevice2Handle); + final Object aOwnership1 = aDevice1.getHandleOwnership(); + final Object aOwnership2 = aDevice2.setHandleOwnership(aOwnership1); + aDevice1.setHandleOwnership(aOwnership2); + } finally { + aDevice2.unlock(); + } + } finally { + aDevice1.unlock(); + } } /** @@ -160,10 +218,11 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * The current ToolkitLock is being locked/unlocked while swapping the reference, * ensuring no concurrent access can occur during the swap. * </p> - * + * * @param locker the ToolkitLock, if null, {@link jogamp.nativewindow.NullToolkitLock} is being used + * @return the previous ToolkitLock instance */ - protected void setToolkitLock(ToolkitLock locker) { + protected ToolkitLock setToolkitLock(ToolkitLock locker) { final ToolkitLock _toolkitLock = toolkitLock; _toolkitLock.lock(); try { @@ -171,6 +230,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } finally { _toolkitLock.unlock(); } + return _toolkitLock; } /** @@ -183,7 +243,12 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice return toolkitLock; } - protected static String getUniqueID(String type, String connection, int unitID) { - return (type + separator + connection + separator + unitID).intern(); + /** + * Returns a unique String object using {@link String#intern()} for the given arguments, + * which object reference itself can be used as a key. + */ + private static String getUniqueID(String type, String connection, int unitID) { + final String r = (type + separator + connection + separator + unitID).intern(); + return r.intern(); } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java index f50bd0e14..4bd548916 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -33,8 +33,8 @@ package javax.media.nativewindow; public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen { - AbstractGraphicsDevice device; - private int idx; + private final AbstractGraphicsDevice device; + private final int idx; public DefaultGraphicsScreen(AbstractGraphicsDevice device, int idx) { this.device = device; @@ -54,10 +54,12 @@ public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen } } + @Override public AbstractGraphicsDevice getDevice() { return device; } + @Override public int getIndex() { return idx; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java index 2610f2cfa..c09e6eaa4 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -36,13 +36,19 @@ package javax.media.nativewindow; import com.jogamp.common.util.ReflectionUtil; import jogamp.nativewindow.Debug; import jogamp.nativewindow.DefaultGraphicsConfigurationFactoryImpl; + +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.Set; /** * Provides the mechanism by which the graphics configuration for a - * window can be chosen before the window is created. The graphics + * window can be chosen before the window is created. The graphics * configuration decides parameters related to hardware accelerated rendering such * as the OpenGL pixel format. <br> * On some window systems (EGL/OpenKODE and X11 in particular) it is necessary to @@ -59,19 +65,57 @@ import java.util.Map; public abstract class GraphicsConfigurationFactory { protected static final boolean DEBUG; - private static Map<Class<?>, GraphicsConfigurationFactory> registeredFactories; - private static Class<?> abstractGraphicsDeviceClass; + private static class DeviceCapsType { + public final Class<?> deviceType; + public final Class<?> capsType; + private final int hash32; + + public DeviceCapsType(Class<?> deviceType, Class<?> capsType) { + this.deviceType = deviceType; + this.capsType = capsType; + + // 31 * x == (x << 5) - x + int hash32 = 31 + deviceType.hashCode(); + hash32 = ((hash32 << 5) - hash32) + capsType.hashCode(); + this.hash32 = hash32; + } + + @Override + public final int hashCode() { + return hash32; + } + + @Override + public final boolean equals(Object obj) { + if(this == obj) { return true; } + if (obj instanceof DeviceCapsType) { + DeviceCapsType dct = (DeviceCapsType)obj; + return deviceType == dct.deviceType && capsType == dct.capsType; + } + return false; + } + + @Override + public final String toString() { + return "DeviceCapsType["+deviceType.getName()+", "+capsType.getName()+"]"; + } + + } + + private static final Map<DeviceCapsType, GraphicsConfigurationFactory> registeredFactories; + private static final DeviceCapsType defaultDeviceCapsType; static boolean initialized = false; - + static { DEBUG = Debug.debug("GraphicsConfiguration"); if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - Info: GraphicsConfigurationFactory.<init>"); // Thread.dumpStack(); } - abstractGraphicsDeviceClass = javax.media.nativewindow.AbstractGraphicsDevice.class; + registeredFactories = Collections.synchronizedMap(new HashMap<DeviceCapsType, GraphicsConfigurationFactory>()); + defaultDeviceCapsType = new DeviceCapsType(AbstractGraphicsDevice.class, CapabilitiesImmutable.class); } - + public static synchronized void initSingleton() { if(!initialized) { initialized = true; @@ -79,32 +123,31 @@ public abstract class GraphicsConfigurationFactory { if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.initSingleton()"); } - registeredFactories = Collections.synchronizedMap(new HashMap<Class<?>, GraphicsConfigurationFactory>()); - + // Register the default no-op factory for arbitrary // AbstractGraphicsDevice implementations, including // AWTGraphicsDevice instances -- the OpenGL binding will take // care of handling AWTGraphicsDevices on X11 platforms (as // well as X11GraphicsDevices in non-AWT situations) - registerFactory(abstractGraphicsDeviceClass, new DefaultGraphicsConfigurationFactoryImpl()); - - if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) { + registerFactory(defaultDeviceCapsType.deviceType, defaultDeviceCapsType.capsType, new DefaultGraphicsConfigurationFactoryImpl()); + + if (NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true)) { try { - ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", - "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); + ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", + "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); } catch (Exception e) { throw new RuntimeException(e); } if(NativeWindowFactory.isAWTAvailable()) { try { - ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", - "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); + ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", + "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); } catch (Exception e) { /* n/a */ } } } } } - + public static synchronized void shutdown() { if(initialized) { initialized = false; @@ -112,10 +155,9 @@ public abstract class GraphicsConfigurationFactory { System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.shutdown()"); } registeredFactories.clear(); - registeredFactories = null; } } - + protected static String getThreadName() { return Thread.currentThread().getName(); } @@ -133,74 +175,175 @@ public abstract class GraphicsConfigurationFactory { protected GraphicsConfigurationFactory() { } - /** Returns the factory for use with the given type of - AbstractGraphicsDevice. */ - public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device) { + /** + * Returns the graphics configuration factory for use with the + * given device and capability. + * + * @see #getFactory(Class, Class) + */ + public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device, CapabilitiesImmutable caps) { if (device == null) { - return getFactory(AbstractGraphicsDevice.class); + throw new IllegalArgumentException("null device"); + } + if (caps == null) { + throw new IllegalArgumentException("null caps"); } - return getFactory(device.getClass()); + return getFactory(device.getClass(), caps.getClass()); } /** * Returns the graphics configuration factory for use with the - * given class, which must implement the {@link - * AbstractGraphicsDevice} interface. + * given device and capability class. + * <p> + * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. + * </p> * - * @throws IllegalArgumentException if the given class does not implement AbstractGraphicsDevice + * <p> + * Pseudo code for finding a suitable factory is: + * <pre> + For-All devT := getTopDownDeviceTypes(deviceType) + For-All capsT := getTopDownCapabilitiesTypes(capabilitiesType) + f = factory.get(devT, capsT); + if(f) { return f; } + end + end + * </pre> + * </p> + * + * @param deviceType the minimum capabilities class type accepted, must implement or extend {@link AbstractGraphicsDevice} + * @param capabilitiesType the minimum capabilities class type accepted, must implement or extend {@link CapabilitiesImmutable} + * + * @throws IllegalArgumentException if the deviceType does not implement {@link AbstractGraphicsDevice} or + * capabilitiesType does not implement {@link CapabilitiesImmutable} */ - public static GraphicsConfigurationFactory getFactory(Class<?> abstractGraphicsDeviceImplementor) + public static GraphicsConfigurationFactory getFactory(Class<?> deviceType, Class<?> capabilitiesType) throws IllegalArgumentException, NativeWindowException { - if (!(abstractGraphicsDeviceClass.isAssignableFrom(abstractGraphicsDeviceImplementor))) { + if (!(defaultDeviceCapsType.deviceType.isAssignableFrom(deviceType))) { throw new IllegalArgumentException("Given class must implement AbstractGraphicsDevice"); } + if (!(defaultDeviceCapsType.capsType.isAssignableFrom(capabilitiesType))) { + throw new IllegalArgumentException("Given capabilities class must implement CapabilitiesImmutable"); + } + if(DEBUG) { + Thread.dumpStack(); + System.err.println("GraphicsConfigurationFactory.getFactory: "+deviceType.getName()+", "+capabilitiesType.getName()); + dumpFactories(); + } - GraphicsConfigurationFactory factory = null; - Class<?> clazz = abstractGraphicsDeviceImplementor; - while (clazz != null) { - factory = registeredFactories.get(clazz); - if (factory != null) { - if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.getFactory() "+abstractGraphicsDeviceImplementor+" -> "+factory); + final List<Class<?>> deviceTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.deviceType, deviceType, false); + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() deviceTypes: " + deviceTypes); + } + final List<Class<?>> capabilitiesTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.capsType, capabilitiesType, true); + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() capabilitiesTypes: " + capabilitiesTypes); + } + for(int j=0; j<deviceTypes.size(); j++) { + final Class<?> interfaceDevice = deviceTypes.get(j); + for(int i=0; i<capabilitiesTypes.size(); i++) { + Class<?> interfaceCaps = capabilitiesTypes.get(i); + final DeviceCapsType dct = new DeviceCapsType(interfaceDevice, interfaceCaps); + final GraphicsConfigurationFactory factory = registeredFactories.get(dct); + if (factory != null) { + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() found "+dct+" -> "+factory); + } + return factory; } - return factory; } - clazz = clazz.getSuperclass(); } // Return the default - factory = registeredFactories.get(abstractGraphicsDeviceClass); + final GraphicsConfigurationFactory factory = registeredFactories.get(defaultDeviceCapsType); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.getFactory() DEFAULT "+abstractGraphicsDeviceClass+" -> "+factory); + System.err.println("GraphicsConfigurationFactory.getFactory() DEFAULT "+defaultDeviceCapsType+" -> "+factory); } return factory; } + private static ArrayList<Class<?>> getAllAssignableClassesFrom(Class<?> superClassOrInterface, Class<?> fromClass, boolean interfacesOnly) { + // Using a todo list avoiding a recursive loop! + final ArrayList<Class<?>> inspectClasses = new ArrayList<Class<?>>(); + final ArrayList<Class<?>> resolvedInterfaces = new ArrayList<Class<?>>(); + inspectClasses.add(fromClass); + for(int j=0; j<inspectClasses.size(); j++) { + final Class<?> clazz = inspectClasses.get(j); + getAllAssignableClassesFrom(superClassOrInterface, clazz, interfacesOnly, resolvedInterfaces, inspectClasses); + } + return resolvedInterfaces; + } + private static void getAllAssignableClassesFrom(Class<?> superClassOrInterface, Class<?> fromClass, boolean interfacesOnly, List<Class<?>> resolvedInterfaces, List<Class<?>> inspectClasses) { + final ArrayList<Class<?>> types = new ArrayList<Class<?>>(); + if( superClassOrInterface.isAssignableFrom(fromClass) && !resolvedInterfaces.contains(fromClass)) { + if( !interfacesOnly || fromClass.isInterface() ) { + types.add(fromClass); + } + } + types.addAll(Arrays.asList(fromClass.getInterfaces())); + + for(int i=0; i<types.size(); i++) { + final Class<?> iface = types.get(i); + if( superClassOrInterface.isAssignableFrom(iface) && !resolvedInterfaces.contains(iface) ) { + resolvedInterfaces.add(iface); + if( !superClassOrInterface.equals(iface) && !inspectClasses.contains(iface) ) { + inspectClasses.add(iface); // safe add to todo list, avoiding a recursive nature + } + } + } + final Class<?> parentClass = fromClass.getSuperclass(); + if( null != parentClass && superClassOrInterface.isAssignableFrom(parentClass) && !inspectClasses.contains(parentClass) ) { + inspectClasses.add(parentClass); // safe add to todo list, avoiding a recursive nature + } + } + private static void dumpFactories() { + Set<DeviceCapsType> dcts = registeredFactories.keySet(); + int i=0; + for(Iterator<DeviceCapsType> iter = dcts.iterator(); iter.hasNext(); ) { + DeviceCapsType dct = iter.next(); + System.err.println("Factory #"+i+": "+dct+" -> "+registeredFactories.get(dct)); + i++; + } + } - /** Registers a GraphicsConfigurationFactory handling graphics - * device objects of the given class. This does not need to be - * called by end users, only implementors of new + /** + * Registers a GraphicsConfigurationFactory handling + * the given graphics device and capability class. + * <p> + * This does not need to be called by end users, only implementors of new * GraphicsConfigurationFactory subclasses. + * </p> + * + * <p> + * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. + * </p> * + * <p>See {@link #getFactory(Class, Class)} for a description of the find algorithm.</p> + * + * @param deviceType the minimum capabilities class type accepted, must implement or extend interface {@link AbstractGraphicsDevice} + * @param capabilitiesType the minimum capabilities class type accepted, must extend interface {@link CapabilitiesImmutable} * @return the previous registered factory, or null if none * @throws IllegalArgumentException if the given class does not implement AbstractGraphicsDevice */ - protected static GraphicsConfigurationFactory registerFactory(Class<?> abstractGraphicsDeviceImplementor, GraphicsConfigurationFactory factory) + protected static GraphicsConfigurationFactory registerFactory(Class<?> abstractGraphicsDeviceImplementor, Class<?> capabilitiesType, GraphicsConfigurationFactory factory) throws IllegalArgumentException { - if (!(abstractGraphicsDeviceClass.isAssignableFrom(abstractGraphicsDeviceImplementor))) { - throw new IllegalArgumentException("Given class must implement AbstractGraphicsDevice"); + if (!(defaultDeviceCapsType.deviceType.isAssignableFrom(abstractGraphicsDeviceImplementor))) { + throw new IllegalArgumentException("Given device class must implement AbstractGraphicsDevice"); + } + if (!(defaultDeviceCapsType.capsType.isAssignableFrom(capabilitiesType))) { + throw new IllegalArgumentException("Given capabilities class must implement CapabilitiesImmutable"); } + final DeviceCapsType dct = new DeviceCapsType(abstractGraphicsDeviceImplementor, capabilitiesType); final GraphicsConfigurationFactory prevFactory; if(null == factory) { - prevFactory = registeredFactories.remove(abstractGraphicsDeviceImplementor); + prevFactory = registeredFactories.remove(dct); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.registerFactory() remove "+abstractGraphicsDeviceImplementor+ + System.err.println("GraphicsConfigurationFactory.registerFactory() remove "+dct+ ", deleting: "+prevFactory); } } else { - prevFactory = registeredFactories.put(abstractGraphicsDeviceImplementor, factory); + prevFactory = registeredFactories.put(dct, factory); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.registerFactory() put "+abstractGraphicsDeviceImplementor+" -> "+factory+ + System.err.println("GraphicsConfigurationFactory.registerFactory() put "+dct+" -> "+factory+ ", overridding: "+prevFactory); } } @@ -211,7 +354,7 @@ public abstract class GraphicsConfigurationFactory { * <P> Selects a graphics configuration on the specified graphics * device compatible with the supplied {@link Capabilities}. Some * platforms (e.g.: X11, EGL, KD) require the graphics configuration - * to be specified when the native window is created. + * to be specified when the native window is created. * These architectures have seperated their device, screen, window and drawable * context and hence are capable of quering the capabilities for each screen. * A fully established window is not required.</P> @@ -219,7 +362,7 @@ public abstract class GraphicsConfigurationFactory { * <P>Other platforms (e.g. Windows, MacOSX) don't offer the mentioned seperation * and hence need a fully established window and it's drawable. * Here the validation of the capabilities is performed later. - * In this case, the AbstractGraphicsConfiguration implementation + * In this case, the AbstractGraphicsConfiguration implementation * must allow an overwrite of the Capabilites, for example * {@link DefaultGraphicsConfiguration#setChosenCapabilities DefaultGraphicsConfiguration.setChosenCapabilities(..)}. * </P> @@ -244,6 +387,7 @@ public abstract class GraphicsConfigurationFactory { * @param capsRequested the original requested capabilities * @param chooser the choosing implementation * @param screen the referring Screen + * @param nativeVisualID if not {@link VisualIDHolder#VID_UNDEFINED} it reflects a pre-chosen visualID of the native platform's windowing system. * @return the complete GraphicsConfiguration * * @throws IllegalArgumentException if the data type of the passed @@ -258,7 +402,7 @@ public abstract class GraphicsConfigurationFactory { public final AbstractGraphicsConfiguration chooseGraphicsConfiguration(CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, - AbstractGraphicsScreen screen) + AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { if(null==capsChosen) { throw new NativeWindowException("Chosen Capabilities are null"); @@ -275,7 +419,7 @@ public abstract class GraphicsConfigurationFactory { } device.lock(); try { - return chooseGraphicsConfigurationImpl(capsChosen, capsRequested, chooser, screen); + return chooseGraphicsConfigurationImpl(capsChosen, capsRequested, chooser, screen, nativeVisualID); } finally { device.unlock(); } @@ -283,7 +427,7 @@ public abstract class GraphicsConfigurationFactory { protected abstract AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl(CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen screen) + CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java new file mode 100644 index 000000000..a0db11ad9 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java @@ -0,0 +1,44 @@ +/** + * Copyright 2012 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow; + +/** + * Provides a {@link NativeSurface} with a mutable <code>surfaceHandle</code> + * via {@link #setSurfaceHandle(long)}. + * + * @see NativeSurface + */ +public interface MutableSurface extends NativeSurface { + + /** + * Sets the surface handle which is created outside of this implementation. + */ + public void setSurfaceHandle(long surfaceHandle); +} + diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java index b7829cb6d..a755b1812 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,12 +20,12 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow; /** Provides low-level information required for @@ -54,10 +54,10 @@ public interface NativeSurface extends SurfaceUpdatedListener { * <p> * The surface handle shall be valid after a successfull call, * ie return a value other than {@link #LOCK_SURFACE_UNLOCKED} and {@link #LOCK_SURFACE_NOT_READY}, - * which is - * <pre> - * boolean ok = lockSurface() > LOCK_SURFACE_NOT_READY; - * </pre> + * which is + * <pre> + * boolean ok = LOCK_SURFACE_NOT_READY < lockSurface(); + * </pre> * </p> * <p> * The caller may need to take care of the result {@link #LOCK_SURFACE_CHANGED}, @@ -71,7 +71,7 @@ public interface NativeSurface extends SurfaceUpdatedListener { * This call allows recursion from the same thread. * </p> * <p> - * The implementation may want to aquire the + * The implementation may want to aquire the * application level {@link com.jogamp.common.util.locks.RecursiveLock} * first before proceeding with a native surface lock. * </p> @@ -83,10 +83,11 @@ public interface NativeSurface extends SurfaceUpdatedListener { * @return {@link #LOCK_SUCCESS}, {@link #LOCK_SURFACE_CHANGED} or {@link #LOCK_SURFACE_NOT_READY}. * * @throws RuntimeException after timeout when waiting for the surface lock + * @throws NativeWindowException if native locking failed, maybe platform related * * @see com.jogamp.common.util.locks.RecursiveLock */ - public int lockSurface(); + public int lockSurface() throws NativeWindowException, RuntimeException; /** * Unlock the surface of this native window @@ -96,36 +97,41 @@ public interface NativeSurface extends SurfaceUpdatedListener { * The implementation shall also invoke {@link AbstractGraphicsDevice#unlock()} * for the final unlock (recursive count zero).<P> * - * @throws RuntimeException if surface is not locked + * The implementation shall be fail safe, i.e. tolerant in case the native resources + * are already released / unlocked. In this case the implementation shall simply ignore the call. * * @see #lockSurface * @see com.jogamp.common.util.locks.RecursiveLock */ - public void unlockSurface() throws NativeWindowException ; + public void unlockSurface(); /** - * Return if surface is locked by another thread, ie not the current one + * Query if surface is locked by another thread, i.e. not the current one. + * <br> + * Convenient shortcut for: + * <pre> + * final Thread o = getSurfaceLockOwner(); + * if( null != o && Thread.currentThread() != o ) { .. } + * </pre> */ public boolean isSurfaceLockedByOtherThread(); /** - * Return if surface is locked - */ - public boolean isSurfaceLocked(); - - /** * Return the locking owner's Thread, or null if not locked. */ public Thread getSurfaceLockOwner(); /** * Provide a mechanism to utilize custom (pre-) swap surface - * code. This method is called before the render toolkit (e.g. JOGL) - * swaps the buffer/surface. The implementation may itself apply the swapping, + * code. This method is called before the render toolkit (e.g. JOGL) + * swaps the buffer/surface if double buffering is enabled. + * <p> + * The implementation may itself apply the swapping, * in which case true shall be returned. + * </p> * * @return true if this method completed swapping the surface, - * otherwise false, in which case eg the GLDrawable + * otherwise false, in which case eg the GLDrawable * implementation has to swap the code. */ public boolean surfaceSwap(); @@ -147,13 +153,13 @@ public interface NativeSurface extends SurfaceUpdatedListener { /** Remove the specified {@link SurfaceUpdatedListener} from the list. */ public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l); - + /** * Returns the handle to the surface for this NativeSurface. <P> - * + * * The surface handle should be set/update by {@link #lockSurface()}, * where {@link #unlockSurface()} is not allowed to modify it. - * After {@link #unlockSurface()} it is no more guaranteed + * After {@link #unlockSurface()} it is no more guaranteed * that the surface handle is still valid. * * The surface handle shall reflect the platform one @@ -189,16 +195,16 @@ public interface NativeSurface extends SurfaceUpdatedListener { public AbstractGraphicsConfiguration getGraphicsConfiguration(); /** - * Convenience: Get display handle from + * Convenience: Get display handle from * AbstractGraphicsConfiguration . AbstractGraphicsScreen . AbstractGraphicsDevice */ public long getDisplayHandle(); /** - * Convenience: Get display handle from + * Convenience: Get display handle from * AbstractGraphicsConfiguration . AbstractGraphicsScreen */ public int getScreenIndex(); - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java index 2bc352116..a740ebbe0 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -52,10 +52,9 @@ import javax.media.nativewindow.util.Point; which can create NativeWindow objects for its components. <P> */ public interface NativeWindow extends NativeSurface { - - /** - * destroys the window and releases - * windowing related resources. + + /** + * Destroys this window incl. releasing all related resources. */ public void destroy(); @@ -67,63 +66,63 @@ public interface NativeWindow extends NativeSurface { /** * Returns the window handle for this NativeWindow. <P> * - * The window handle shall reflect the platform one + * The window handle shall reflect the platform one * for all window related operations, e.g. open, close, resize. <P> * * On X11 this returns an entity of type Window. <BR> - * On Microsoft Windows this returns an entity of type HWND. + * On Microsoft Windows this returns an entity of type HWND. */ public long getWindowHandle(); - /** + /** * Returns the insets defined as the width and height of the window decoration * on the left, right, top and bottom.<br> * Insets are zero if the window is undecorated, including child windows. - * + * * <p> * Insets are available only after the native window has been created, * ie. the native window has been made visible.<br> - * + * * The top-level window area's top-left corner is located at * <pre> * getX() - getInsets().{@link InsetsImmutable#getLeftWidth() getLeftWidth()} * getY() - getInsets().{@link InsetsImmutable#getTopHeight() getTopHeight()} - * </pre> - * + * </pre> + * * The top-level window size is * <pre> - * getWidth() + getInsets().{@link InsetsImmutable#getTotalWidth() getTotalWidth()} + * getWidth() + getInsets().{@link InsetsImmutable#getTotalWidth() getTotalWidth()} * getHeight() + getInsets().{@link InsetsImmutable#getTotalHeight() getTotalHeight()} - * </pre> - * + * </pre> + * * @return insets */ public InsetsImmutable getInsets(); - + /** Returns the current x position of this window, relative to it's parent. */ - - /** + + /** * @return the current x position of the top-left corner - * of the client area relative to it's parent. + * of the client area relative to it's parent. * Since the position reflects the client area, it does not include the insets. * @see #getInsets() */ public int getX(); - /** + /** * @return the current y position of the top-left corner - * of the client area relative to it's parent. + * of the client area relative to it's parent. * Since the position reflects the client area, it does not include the insets. * @see #getInsets() */ public int getY(); - /** - * Returns the current position of the top-left corner + /** + * Returns the current position of the top-left corner * of the client area in screen coordinates. * <p> * Since the position reflects the client area, it does not include the insets. - * </p> + * </p> * @param point if not null, * {@link javax.media.nativewindow.util.Point#translate(javax.media.nativewindow.util.Point)} * the passed {@link javax.media.nativewindow.util.Point} by this location on the screen and return it. @@ -131,8 +130,8 @@ public interface NativeWindow extends NativeSurface { * or a new instance with the screen location of this NativeWindow. */ public Point getLocationOnScreen(Point point); - + /** Returns true if this native window owns the focus, otherwise false. */ boolean hasFocus(); - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java index 593c1e7d6..0943c8c09 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,11 +28,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index b85ad47f2..034bf2456 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -33,19 +33,36 @@ package javax.media.nativewindow; -import java.lang.reflect.Constructor; +import java.io.File; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; +import javax.media.nativewindow.util.PointImmutable; + import jogamp.nativewindow.Debug; import jogamp.nativewindow.NativeWindowFactoryImpl; +import jogamp.nativewindow.ToolkitProperties; +import jogamp.nativewindow.ResourceToolkitLock; +import jogamp.nativewindow.WrappedWindow; +import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.windows.GDIUtil; +import jogamp.nativewindow.x11.X11Lib; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSizePos; +import com.jogamp.nativewindow.awt.AWTGraphicsDevice; +import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; +import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; /** Provides a pluggable mechanism for arbitrary window toolkits to adapt their components to the {@link NativeWindow} interface, @@ -56,57 +73,75 @@ import com.jogamp.common.util.ReflectionUtil; public abstract class NativeWindowFactory { protected static final boolean DEBUG; - /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_EGL = "EGL"; + /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ + public static final String TYPE_EGL = ".egl".intern(); + + /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_WINDOWS = ".windows".intern(); + + /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_X11 = ".x11".intern(); - /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_WINDOWS = "Windows"; + /** Broadcom VC IV/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_BCM_VC_IV = ".bcm.vc.iv".intern(); - /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_X11 = "X11"; + /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ + public static final String TYPE_ANDROID = ".android".intern(); - /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_ANDROID = "ANDROID"; + /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_MACOSX = ".macosx".intern(); - /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_MACOSX = "MacOSX"; + /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_AWT = ".awt".intern(); - /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_AWT = "AWT"; + /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_DEFAULT = ".default".intern(); - /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_DEFAULT = "default"; + private static final String nativeWindowingTypePure; // canonical String via String.intern() + private static final String nativeWindowingTypeCustom; // canonical String via String.intern() private static NativeWindowFactory defaultFactory; private static Map<Class<?>, NativeWindowFactory> registeredFactories; - + private static Class<?> nativeWindowClass; - private static String nativeWindowingTypePure; - private static String nativeWindowingTypeCustom; private static boolean isAWTAvailable; - + private static final String JAWTUtilClassName = "jogamp.nativewindow.jawt.JAWTUtil" ; + /** {@link jogamp.nativewindow.x11.X11Util} implements {@link ToolkitProperties}. */ private static final String X11UtilClassName = "jogamp.nativewindow.x11.X11Util"; + /** {@link jogamp.nativewindow.macosx.OSXUtil} implements {@link ToolkitProperties}. */ private static final String OSXUtilClassName = "jogamp.nativewindow.macosx.OSXUtil"; + /** {@link jogamp.nativewindow.windows.GDIUtil} implements {@link ToolkitProperties}. */ private static final String GDIClassName = "jogamp.nativewindow.windows.GDIUtil"; - + private static ToolkitLock jawtUtilJAWTToolkitLock; - - public static final String X11JAWTToolkitLockClassName = "jogamp.nativewindow.jawt.x11.X11JAWTToolkitLock" ; - public static final String X11ToolkitLockClassName = "jogamp.nativewindow.x11.X11ToolkitLock" ; - - private static Class<?> x11JAWTToolkitLockClass; - private static Constructor<?> x11JAWTToolkitLockConstructor; - private static Class<?> x11ToolkitLockClass; - private static Constructor<?> x11ToolkitLockConstructor; - private static boolean isFirstUIActionOnProcess; + private static boolean requiresToolkitLock; + private static boolean desktopHasThreadingIssues; + + // Shutdown hook mechanism for the factory + private static volatile boolean isJVMShuttingDown = false; + private static final List<Runnable> customShutdownHooks = new ArrayList<Runnable>(); /** Creates a new NativeWindowFactory instance. End users do not need to call this method. */ protected NativeWindowFactory() { } + private static final boolean guessBroadcomVCIV() { + return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { + private final File vcliblocation = new File( + "/opt/vc/lib/libbcm_host.so"); + @Override + public Boolean run() { + if ( vcliblocation.isFile() ) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + } ).booleanValue(); + } + private static String _getNativeWindowingType() { switch(Platform.OS_TYPE) { case ANDROID: @@ -114,99 +149,188 @@ public abstract class NativeWindowFactory { case MACOS: return TYPE_MACOSX; case WINDOWS: - return TYPE_WINDOWS; + return TYPE_WINDOWS; case OPENKODE: return TYPE_EGL; - + case LINUX: case FREEBSD: case SUNOS: case HPUX: default: + if( guessBroadcomVCIV() ) { + return TYPE_BCM_VC_IV; + } return TYPE_X11; } } static { - Platform.initSingleton(); - DEBUG = Debug.debug("NativeWindow"); + final boolean[] _DEBUG = new boolean[] { false }; + final String[] _tmp = new String[] { null }; + + AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override + public Object run() { + Platform.initSingleton(); // last resort .. + _DEBUG[0] = Debug.debug("NativeWindow"); + _tmp[0] = Debug.getProperty("nativewindow.ws.name", true); + Runtime.getRuntime().addShutdownHook( + new Thread(new Runnable() { + @Override + public void run() { + NativeWindowFactory.shutdown(true); + } }, "NativeWindowFactory_ShutdownHook" ) ) ; + return null; + } } ) ; + + DEBUG = _DEBUG[0]; if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - Info: NativeWindowFactory.<init>"); // Thread.dumpStack(); } + + // Gather the windowing TK first + nativeWindowingTypePure = _getNativeWindowingType(); + if(null==_tmp[0] || _tmp[0].length()==0) { + nativeWindowingTypeCustom = nativeWindowingTypePure; + } else { + nativeWindowingTypeCustom = _tmp[0].intern(); // canonical representation + } } - static boolean initialized = false; + private static boolean initialized = false; - private static void initSingletonNativeImpl(final boolean firstUIActionOnProcess, final ClassLoader cl) { - isFirstUIActionOnProcess = firstUIActionOnProcess; - + private static void initSingletonNativeImpl(final ClassLoader cl) { final String clazzName; - if( TYPE_X11.equals(nativeWindowingTypePure) ) { + if( TYPE_X11 == nativeWindowingTypePure ) { clazzName = X11UtilClassName; - } else if( TYPE_WINDOWS.equals(nativeWindowingTypePure) ) { + } else if( TYPE_WINDOWS == nativeWindowingTypePure ) { clazzName = GDIClassName; - } else if( TYPE_MACOSX.equals(nativeWindowingTypePure) ) { + } else if( TYPE_MACOSX == nativeWindowingTypePure ) { clazzName = OSXUtilClassName; } else { clazzName = null; } if( null != clazzName ) { - ReflectionUtil.callStaticMethod(clazzName, "initSingleton", - new Class[] { boolean.class }, - new Object[] { new Boolean(firstUIActionOnProcess) }, cl ); - - final Boolean res = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); - requiresToolkitLock = res.booleanValue(); - } else { + ReflectionUtil.callStaticMethod(clazzName, "initSingleton", null, null, cl ); + + final Boolean res1 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); + requiresToolkitLock = res1.booleanValue(); + final Boolean res2 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "hasThreadingIssues", null, null, cl); + desktopHasThreadingIssues = res2.booleanValue(); + } else { requiresToolkitLock = false; - } + desktopHasThreadingIssues = false; + } + } + + /** Returns true if the JVM is shutting down, otherwise false. */ + public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; } + + /** + * Add a custom shutdown hook to be performed at JVM shutdown before shutting down NativeWindowFactory instance. + * + * @param head if true add runnable at the start, otherwise at the end + * @param runnable runnable to be added. + */ + public static void addCustomShutdownHook(boolean head, Runnable runnable) { + synchronized( customShutdownHooks ) { + if( !customShutdownHooks.contains( runnable ) ) { + if( head ) { + customShutdownHooks.add(0, runnable); + } else { + customShutdownHooks.add( runnable ); + } + } + } } /** + * Cleanup resources at JVM shutdown + */ + public static synchronized void shutdown(boolean _isJVMShuttingDown) { + isJVMShuttingDown = _isJVMShuttingDown; + if(DEBUG) { + System.err.println("NativeWindowFactory.shutdown() START: JVM Shutdown "+isJVMShuttingDown+", on thread "+Thread.currentThread().getName()); + } + synchronized(customShutdownHooks) { + final int cshCount = customShutdownHooks.size(); + for(int i=0; i < cshCount; i++) { + try { + if( DEBUG ) { + System.err.println("NativeWindowFactory.shutdown - customShutdownHook #"+(i+1)+"/"+cshCount); + } + customShutdownHooks.get(i).run(); + } catch(Throwable t) { + System.err.println("NativeWindowFactory.shutdown: Catched "+t.getClass().getName()+" during customShutdownHook #"+(i+1)+"/"+cshCount); + if( DEBUG ) { + t.printStackTrace(); + } + } + } + customShutdownHooks.clear(); + } + if(DEBUG) { + System.err.println("NativeWindowFactory.shutdown(): Post customShutdownHook"); + } + + if(initialized) { + initialized = false; + if(null != registeredFactories) { + registeredFactories.clear(); + registeredFactories = null; + } + GraphicsConfigurationFactory.shutdown(); + } + + shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown + // SharedResourceToolkitLock.shutdown(DEBUG); // not used yet + if(DEBUG) { + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); + } + } + + private static void shutdownNativeImpl(final ClassLoader cl) { + final String clazzName; + if( TYPE_X11 == nativeWindowingTypePure ) { + clazzName = X11UtilClassName; + } else if( TYPE_WINDOWS == nativeWindowingTypePure ) { + clazzName = GDIClassName; + } else if( TYPE_MACOSX == nativeWindowingTypePure ) { + clazzName = OSXUtilClassName; + } else { + clazzName = null; + } + if( null != clazzName ) { + ReflectionUtil.callStaticMethod(clazzName, "shutdown", null, null, cl ); + } + } + + /** Returns true if {@link #initSingleton()} has been called w/o subsequent {@link #shutdown(boolean)}. */ + public static synchronized boolean isInitialized() { return initialized; } + + /** * Static one time initialization of this factory.<br> * This initialization method <b>must be called</b> once by the program or utilizing modules! - * <p> - * The parameter <code>firstUIActionOnProcess</code> has an impact on concurrent locking: - * <ul> - * <li> {@link #getDefaultToolkitLock() getDefaultToolkitLock() }</li> - * <li> {@link #getDefaultToolkitLock(java.lang.String) getDefaultToolkitLock(type) }</li> - * <li> {@link #createDefaultToolkitLock(java.lang.String, long) createDefaultToolkitLock(type, dpyHandle) }</li> - * <li> {@link #createDefaultToolkitLockNoAWT(java.lang.String, long) createDefaultToolkitLockNoAWT(type, dpyHandle) }</li> - * </ul> - * </p> - * @param firstUIActionOnProcess Should be <code>true</code> if called before the first UI action of the running program, - * otherwise <code>false</code>. */ - public static synchronized void initSingleton(final boolean firstUIActionOnProcess) { + public static synchronized void initSingleton() { if(!initialized) { initialized = true; if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.initSingleton("+firstUIActionOnProcess+")"); + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.initSingleton()"); } final ClassLoader cl = NativeWindowFactory.class.getClassLoader(); - // Gather the windowing OS first - nativeWindowingTypePure = _getNativeWindowingType(); - String tmp = Debug.getProperty("nativewindow.ws.name", true); - if(null==tmp || tmp.length()==0) { - nativeWindowingTypeCustom = nativeWindowingTypePure; - } else { - nativeWindowingTypeCustom = tmp; - } - - if(firstUIActionOnProcess) { - // X11 initialization before possible AWT initialization - initSingletonNativeImpl(true, cl); - } isAWTAvailable = false; // may be set to true below if( Platform.AWT_AVAILABLE && ReflectionUtil.isClassAvailable("com.jogamp.nativewindow.awt.AWTGraphicsDevice", cl) ) { - + Method[] jawtUtilMethods = AccessController.doPrivileged(new PrivilegedAction<Method[]>() { + @Override public Method[] run() { try { Class<?> _jawtUtilClass = Class.forName(JAWTUtilClassName, true, NativeWindowFactory.class.getClassLoader()); @@ -216,7 +340,7 @@ public abstract class NativeWindowFactory { jawtUtilInitMethod.setAccessible(true); Method jawtUtilGetJAWTToolkitLockMethod = _jawtUtilClass.getDeclaredMethod("getJAWTToolkitLock", new Class[]{}); jawtUtilGetJAWTToolkitLockMethod.setAccessible(true); - return new Method[] { jawtUtilInitMethod, jawtUtilIsHeadlessMethod, jawtUtilGetJAWTToolkitLockMethod }; + return new Method[] { jawtUtilInitMethod, jawtUtilIsHeadlessMethod, jawtUtilGetJAWTToolkitLockMethod }; } catch (Exception e) { if(DEBUG) { e.printStackTrace(); @@ -229,7 +353,7 @@ public abstract class NativeWindowFactory { final Method jawtUtilInitMethod = jawtUtilMethods[0]; final Method jawtUtilIsHeadlessMethod = jawtUtilMethods[1]; final Method jawtUtilGetJAWTToolkitLockMethod = jawtUtilMethods[2]; - + ReflectionUtil.callMethod(null, jawtUtilInitMethod); Object resO = ReflectionUtil.callMethod(null, jawtUtilIsHeadlessMethod); @@ -240,18 +364,21 @@ public abstract class NativeWindowFactory { } else { throw new RuntimeException("JAWTUtil.isHeadlessMode() didn't return a Boolean"); } - resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitLockMethod); + resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitLockMethod); if(resO instanceof ToolkitLock) { jawtUtilJAWTToolkitLock = (ToolkitLock) resO; } else { throw new RuntimeException("JAWTUtil.getJAWTToolkitLock() didn't return a ToolkitLock"); - } + } } } - if(!firstUIActionOnProcess) { - // X11 initialization after possible AWT initialization - initSingletonNativeImpl(false, cl); - } + + // X11 initialization after possible AWT initialization + // This is performed post AWT initialization, allowing AWT to complete the same, + // which may have been triggered before NativeWindow initialization. + // This way behavior is more uniforms across configurations (Applet/RCP, applications, ..). + initSingletonNativeImpl(cl); + registeredFactories = Collections.synchronizedMap(new HashMap<Class<?>, NativeWindowFactory>()); // register our default factory -> NativeWindow @@ -259,79 +386,47 @@ public abstract class NativeWindowFactory { nativeWindowClass = javax.media.nativewindow.NativeWindow.class; registerFactory(nativeWindowClass, factory); defaultFactory = factory; - + if ( isAWTAvailable ) { // register either our default factory or (if exist) the X11/AWT one -> AWT Component registerFactory(ReflectionUtil.getClass(ReflectionUtil.AWTNames.ComponentClass, false, cl), factory); } - if( TYPE_X11 == nativeWindowingTypePure ) { - // passing through RuntimeException if not exists intended - x11ToolkitLockClass = ReflectionUtil.getClass(X11ToolkitLockClassName, false, cl); - x11ToolkitLockConstructor = ReflectionUtil.getConstructor(x11ToolkitLockClass, new Class[] { long.class } ); - if( isAWTAvailable() ) { - x11JAWTToolkitLockClass = ReflectionUtil.getClass(X11JAWTToolkitLockClassName, false, cl); - x11JAWTToolkitLockConstructor = ReflectionUtil.getConstructor(x11JAWTToolkitLockClass, new Class[] { long.class } ); - } - } - if(DEBUG) { - System.err.println("NativeWindowFactory firstUIActionOnProcess "+firstUIActionOnProcess); - System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock); + System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock+", desktopHasThreadingIssues "+desktopHasThreadingIssues); System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory); } - - GraphicsConfigurationFactory.initSingleton(); - } - } - public static synchronized void shutdown() { - if(initialized) { - initialized = false; - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() START"); - } - registeredFactories.clear(); - registeredFactories = null; - GraphicsConfigurationFactory.shutdown(); - // X11Util.shutdown(..) already called via GLDrawableFactory.shutdown() .. - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END"); - } + GraphicsConfigurationFactory.initSingleton(); } } - - /** @return true if initialized with <b>{@link #initSingleton(boolean) initSingleton(firstUIActionOnProcess==true)}</b>, - otherwise false. */ - public static boolean isFirstUIActionOnProcess() { - return isFirstUIActionOnProcess; - } /** @return true if the underlying toolkit requires locking, otherwise false. */ public static boolean requiresToolkitLock() { return requiresToolkitLock; - } - + } + /** @return true if not headless, AWT Component and NativeWindow's AWT part available */ public static boolean isAWTAvailable() { return isAWTAvailable; } /** * @param useCustom if false return the native value, if true return a custom value if set, otherwise fallback to the native value. - * @return a define native window type, like {@link #TYPE_X11}, .. + * @return the native window type, e.g. {@link #TYPE_X11}, which is canonical via {@link String#intern()}. + * Hence {@link String#equals(Object)} and <code>==</code> produce the same result. */ public static String getNativeWindowType(boolean useCustom) { return useCustom?nativeWindowingTypeCustom:nativeWindowingTypePure; } - /** Don't know if we shall add this factory here .. + /** Don't know if we shall add this factory here .. public static AbstractGraphicsDevice createGraphicsDevice(String type, String connection, int unitID, long handle, ToolkitLock locker) { - if(type.equals(TYPE_EGL)) { + if(TYPE_EGL == type) { return new - } else if(type.equals(TYPE_X11)) { - } else if(type.equals(TYPE_WINDOWS)) { - } else if(type.equals(TYPE_MACOSX)) { - } else if(type.equals(TYPE_AWT)) { - } else if(type.equals(TYPE_DEFAULT)) { + } else if(TYPE_X11 == type) { + } else if(TYPE_WINDOWS == type) { + } else if(TYPE_MACOSX == type)) { + } else if(TYPE_AWT == type) { + } else if(TYPE_DEFAULT == type) { } } */ @@ -346,126 +441,89 @@ public abstract class NativeWindowFactory { } /** - * Provides the system default {@link ToolkitLock}, a singleton instance. - * <br> + * Returns the AWT {@link ToolkitLock} (JAWT based) if {@link #isAWTAvailable}, otherwise null. + * <p> + * The JAWT based {@link ToolkitLock} also locks the global lock, + * which matters if the latter is required. + * </p> + */ + public static ToolkitLock getAWTToolkitLock() { + return jawtUtilJAWTToolkitLock; + } + + public static ToolkitLock getNullToolkitLock() { + return NativeWindowFactoryImpl.getNullToolkitLock(); + } + + /** + * Provides the system default {@link ToolkitLock} for the default system windowing type. + * @see #getNativeWindowType(boolean) * @see #getDefaultToolkitLock(java.lang.String) */ public static ToolkitLock getDefaultToolkitLock() { - return getDefaultToolkitLock(getNativeWindowType(false)); + return getDefaultToolkitLock(nativeWindowingTypePure); } /** - * Provides the default {@link ToolkitLock} for <code>type</code>, a singleton instance. - * <br> + * Provides the default {@link ToolkitLock} for <code>type</code>. * <ul> - * <li> If {@link #initSingleton(boolean) initSingleton( <b>firstUIActionOnProcess := false</b> )} </li> - * <ul> - * <li>If <b>AWT-type</b> and <b>native-X11-type</b> and <b>AWT-available</b></li> - * <ul> - * <li> return {@link #getAWTToolkitLock()} </li> - * </ul> - * </ul> - * <li> Otherwise return {@link #getNullToolkitLock()} </li> + * <li> JAWT {@link ToolkitLock} if required and <code>type</code> is of {@link #TYPE_AWT} and AWT available,</li> + * <li> {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise</li> + * <li> {@link jogamp.nativewindow.NullToolkitLock} </li> * </ul> */ public static ToolkitLock getDefaultToolkitLock(String type) { - if( requiresToolkitLock() ) { - if( TYPE_AWT == type && TYPE_X11 == getNativeWindowType(false) && isAWTAvailable() ) { + if( requiresToolkitLock ) { + if( TYPE_AWT == type && isAWTAvailable() ) { return getAWTToolkitLock(); } + return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); } - /** Returns the AWT Toolkit (JAWT based) if {@link #isAWTAvailable}, otherwise null. */ - public static ToolkitLock getAWTToolkitLock() { - return jawtUtilJAWTToolkitLock; - } - - public static ToolkitLock getNullToolkitLock() { - return NativeWindowFactoryImpl.getNullToolkitLock(); - } - /** - * Creates the default {@link ToolkitLock} for <code>type</code> and <code>deviceHandle</code>. - * <br> + * Provides the default {@link ToolkitLock} for <code>type</code> and <code>deviceHandle</code>. * <ul> - * <li> If {@link #initSingleton(boolean) initSingleton( <b>firstUIActionOnProcess := false</b> )} </li> - * <ul> - * <li>If <b>X11 type</b> </li> - * <ul> - * <li> return {@link jogamp.nativewindow.x11.X11ToolkitLock} </li> - * </ul> - * </ul> - * <li> Otherwise return {@link jogamp.nativewindow.NullToolkitLock} </li> + * <li> JAWT {@link ToolkitLock} if required and <code>type</code> is of {@link #TYPE_AWT} and AWT available,</li> + * <li> {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise</li> + * <li> {@link jogamp.nativewindow.NullToolkitLock} </li> * </ul> */ - public static ToolkitLock createDefaultToolkitLock(String type, long deviceHandle) { - if( requiresToolkitLock() ) { - if( TYPE_X11 == type ) { - if( 0== deviceHandle ) { - throw new RuntimeException("JAWTUtil.createDefaultToolkitLock() called with NULL device but on X11"); - } - return createX11ToolkitLock(deviceHandle); + public static ToolkitLock getDefaultToolkitLock(String type, long deviceHandle) { + if( requiresToolkitLock ) { + if( TYPE_AWT == type && isAWTAvailable() ) { + return getAWTToolkitLock(); } + return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); } - + /** - * Creates the default {@link ToolkitLock} for <code>type</code> and <code>deviceHandle</code>. - * <br> - * <ul> - * <li> If {@link #initSingleton(boolean) initSingleton( <b>firstUIActionOnProcess := false</b> )} </li> - * <ul> - * <li>If <b>X11 type</b> </li> - * <ul> - * <li> If <b>shared-AWT-type</b> and <b>AWT available</b> </li> - * <ul> - * <li> return {@link jogamp.nativewindow.jawt.x11.X11JAWTToolkitLock} </li> - * </ul> - * <li> else return {@link jogamp.nativewindow.x11.X11ToolkitLock} </li> - * </ul> - * </ul> - * <li> Otherwise return {@link jogamp.nativewindow.NullToolkitLock} </li> - * </ul> + * @param device + * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen + * @return newly created AbstractGraphicsScreen matching device's native type */ - public static ToolkitLock createDefaultToolkitLock(String type, String sharedType, long deviceHandle) { - if( requiresToolkitLock() ) { - if( TYPE_X11 == type ) { - if( 0== deviceHandle ) { - throw new RuntimeException("JAWTUtil.createDefaultToolkitLock() called with NULL device but on X11"); - } - if( TYPE_AWT == sharedType && isAWTAvailable() ) { - return createX11AWTToolkitLock(deviceHandle); - } - return createX11ToolkitLock(deviceHandle); + public static AbstractGraphicsScreen createScreen(AbstractGraphicsDevice device, int screen) { + final String type = device.getType(); + if( TYPE_X11 == type ) { + final X11GraphicsDevice x11Device = (X11GraphicsDevice)device; + if(0 > screen) { + screen = x11Device.getDefaultScreen(); } + return new X11GraphicsScreen(x11Device, screen); } - return NativeWindowFactoryImpl.getNullToolkitLock(); - } - - protected static ToolkitLock createX11AWTToolkitLock(long deviceHandle) { - try { - if(DEBUG) { - System.err.println("NativeWindowFactory.createX11AWTToolkitLock(0x"+Long.toHexString(deviceHandle)+")"); - // Thread.dumpStack(); - } - return (ToolkitLock) x11JAWTToolkitLockConstructor.newInstance(new Object[]{new Long(deviceHandle)}); - } catch (Exception ex) { - throw new RuntimeException(ex); + if(0 > screen) { + screen = 0; // FIXME: Needs native API utilization } - } - - protected static ToolkitLock createX11ToolkitLock(long deviceHandle) { - try { - return (ToolkitLock) x11ToolkitLockConstructor.newInstance(new Object[]{new Long(deviceHandle)}); - } catch (Exception ex) { - throw new RuntimeException(ex); + if( TYPE_AWT == type ) { + final AWTGraphicsDevice awtDevice = (AWTGraphicsDevice) device; + return new AWTGraphicsScreen(awtDevice); } + return new DefaultGraphicsScreen(device, screen); } - /** Returns the appropriate NativeWindowFactory to handle window objects of the given type. The windowClass might be {@link NativeWindow NativeWindow}, in which case the client has @@ -498,7 +556,7 @@ public abstract class NativeWindowFactory { } /** Converts the given window object and it's - {@link AbstractGraphicsConfiguration AbstractGraphicsConfiguration} into a + {@link AbstractGraphicsConfiguration AbstractGraphicsConfiguration} into a {@link NativeWindow NativeWindow} which can be operated upon by a custom toolkit, e.g. {@link javax.media.opengl.GLDrawableFactory javax.media.opengl.GLDrawableFactory}.<br> The object may be a component for a particular window toolkit, such as an AWT @@ -509,7 +567,7 @@ public abstract class NativeWindowFactory { NativeWindowFactory is responsible for handling objects from a particular window toolkit. The built-in NativeWindowFactory handles NativeWindow instances as well as AWT Components.<br> - + @throws IllegalArgumentException if the given window object could not be handled by any of the registered NativeWindowFactory instances @@ -528,22 +586,22 @@ public abstract class NativeWindowFactory { NativeWindow. Implementors of concrete NativeWindowFactory subclasses should override this method. */ protected abstract NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException; - + /** * Returns the {@link OffscreenLayerSurface} instance of this {@link NativeSurface}. * <p> - * In case this surface is a {@link NativeWindow}, we traverse from the given surface + * In case this surface is a {@link NativeWindow}, we traverse from the given surface * up to root until an implementation of {@link OffscreenLayerSurface} is found. * In case <code>ifEnabled</code> is true, the surface must also implement {@link OffscreenLayerOption} - * where {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()} is <code>true</code>. + * where {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()} is <code>true</code>. * </p> - * + * * @param surface The surface to query. - * @param ifEnabled If true, only return the enabled {@link OffscreenLayerSurface}, see {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()}. + * @param ifEnabled If true, only return the enabled {@link OffscreenLayerSurface}, see {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()}. * @return */ public static OffscreenLayerSurface getOffscreenLayerSurface(NativeSurface surface, boolean ifEnabled) { - if(surface instanceof OffscreenLayerSurface && + if(surface instanceof OffscreenLayerSurface && ( !ifEnabled || surface instanceof OffscreenLayerOption ) ) { final OffscreenLayerSurface ols = (OffscreenLayerSurface) surface; return ( !ifEnabled || ((OffscreenLayerOption)ols).isOffscreenLayerSurfaceEnabled() ) ? ols : null; @@ -556,9 +614,97 @@ public abstract class NativeWindowFactory { final OffscreenLayerSurface ols = (OffscreenLayerSurface) nw; return ( !ifEnabled || ((OffscreenLayerOption)ols).isOffscreenLayerSurfaceEnabled() ) ? ols : null; } - nw = nw.getParent(); + nw = nw.getParent(); } } - return null; + return null; + } + + /** + * Returns true if the given visualID is valid for further processing, i.e. OpenGL usage, + * otherwise return false. + * <p> + * On certain platforms, i.e. X11, a valid visualID is required at window creation. + * Other platforms may determine it later on, e.g. OSX and Windows. </p> + * <p> + * If the visualID is {@link VisualIDHolder#VID_UNDEFINED} and the platform requires it + * at creation time (see above), it is not valid for further processing. + * </p> + */ + public static boolean isNativeVisualIDValidForProcessing(int visualID) { + return NativeWindowFactory.TYPE_X11 != NativeWindowFactory.getNativeWindowType(false) || + VisualIDHolder.VID_UNDEFINED != visualID ; } + + /** + * Creates a native device type, following {@link #getNativeWindowType(boolean) getNativeWindowType(true)}. + * <p> + * The device will be opened if <code>own</code> is true, otherwise no native handle will ever be acquired. + * </p> + */ + public static AbstractGraphicsDevice createDevice(String displayConnection, boolean own) { + final String nwt = NativeWindowFactory.getNativeWindowType(true); + if( NativeWindowFactory.TYPE_X11 == nwt ) { + if( own ) { + return new X11GraphicsDevice(displayConnection, AbstractGraphicsDevice.DEFAULT_UNIT, null /* ToolkitLock */); + } else { + return new X11GraphicsDevice(displayConnection, AbstractGraphicsDevice.DEFAULT_UNIT); + } + } else if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { + return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { + return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); + /** + * FIXME: Needs service provider interface (SPI) for TK dependent implementation + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { + } else if( NativeWindowFactory.TYPE_EGL == nwt ) { + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_AWT == nwt ) { + */ + } + throw new UnsupportedOperationException("n/a for windowing system: "+nwt); + } + + /** + * Creates a wrapped {@link NativeWindow} with given native handles and {@link AbstractGraphicsScreen}. + * <p> + * The given {@link UpstreamSurfaceHookMutableSizePos} maybe used to reflect resizes and repositioning of the native window. + * </p> + * <p> + * The {@link AbstractGraphicsScreen} may be created via {@link #createScreen(AbstractGraphicsDevice, int)}. + * </p> + * <p> + * The {@link AbstractGraphicsScreen} may have an underlying open {@link AbstractGraphicsDevice} + * or a simple <i>dummy</i> instance, see {@link #createDevice(String, boolean)}. + * </p> + */ + public static NativeWindow createWrappedWindow(AbstractGraphicsScreen aScreen, long surfaceHandle, long windowHandle, + UpstreamSurfaceHookMutableSizePos hook) { + final CapabilitiesImmutable caps = new Capabilities(); + final AbstractGraphicsConfiguration config = new DefaultGraphicsConfiguration(aScreen, caps, caps); + return new WrappedWindow(config, surfaceHandle, hook, true, windowHandle); + } + + public static PointImmutable getLocationOnScreen(NativeWindow nw) { + final String nwt = NativeWindowFactory.getNativeWindowType(true); + if( NativeWindowFactory.TYPE_X11 == nwt ) { + return X11Lib.GetRelativeLocation(nw.getDisplayHandle(), nw.getScreenIndex(), nw.getWindowHandle(), 0, 0, 0); + } else if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { + return GDIUtil.GetRelativeLocation(nw.getWindowHandle(), 0, 0, 0); + } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { + return OSXUtil.GetLocationOnScreen(nw.getWindowHandle(), null == nw.getParent(), 0, 0); + /** + * FIXME: Needs service provider interface (SPI) for TK dependent implementation + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { + } else if( NativeWindowFactory.TYPE_EGL == nwt ) { + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_AWT == nwt ) { + */ + } + throw new UnsupportedOperationException("n/a for windowing system: "+nwt); + } + + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java index 12d30b3cd..11496899a 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java @@ -32,30 +32,30 @@ package javax.media.nativewindow; * within the implementation. */ public interface OffscreenLayerOption { - /** + /** * Request an offscreen layer, if supported. * <p> * Shall be called before the first {@link NativeWindow#lockSurface()}, * and hence before realization. * </p> - * + * * @see #getShallUseOffscreenLayer() - * @see #isOffscreenLayerSurfaceEnabled() + * @see #isOffscreenLayerSurfaceEnabled() */ public void setShallUseOffscreenLayer(boolean v); /** Returns the property set by {@link #setShallUseOffscreenLayer(boolean)}. */ public boolean getShallUseOffscreenLayer(); - /** + /** * Returns true if this instance uses an offscreen layer, otherwise false. * <p> * This instance is an offscreen layer, if {@link #setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} * has been called before it's realization and first lock and the underlying implementation supports it. * </p> * The return value is undefined before issuing the first {@link NativeWindow#lockSurface()}. - * - * @see #setShallUseOffscreenLayer(boolean) + * + * @see #setShallUseOffscreenLayer(boolean) */ public boolean isOffscreenLayerSurfaceEnabled(); }
\ No newline at end of file diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index dd36509ba..cf8cf89d2 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -27,22 +27,60 @@ */ package javax.media.nativewindow; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PointImmutable; + +import com.jogamp.common.util.locks.RecursiveLock; + /** * Interface specifying the offscreen layer surface protocol. */ public interface OffscreenLayerSurface { - /** + /** * Attach the offscreen layer to this offscreen layer surface. + * <p> + * Implementation may realize all required resources at this point. + * </p> + * * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ public void attachSurfaceLayer(final long layerHandle) throws NativeWindowException; - - /** + + /** * Detaches a previously attached offscreen layer from this offscreen layer surface. * @see #attachSurfaceLayer(long) * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + * or no surface layer is attached. + */ + public void detachSurfaceLayer() throws NativeWindowException; + + /** Returns the attached surface layer or null if none is attached. */ + public long getAttachedSurfaceLayer(); + + /** Returns true if a surface layer is attached, otherwise false. */ + public boolean isSurfaceLayerAttached(); + + /** Sets the capabilities of this instance, allowing upstream API's to refine it, i.e. OpenGL related settings. */ + public void setChosenCapabilities(CapabilitiesImmutable caps); + + /** Returns the recursive lock object of this surface, which synchronizes multithreaded access. */ + public RecursiveLock getLock(); + + /** + * Optional method setting cursor in the corresponding on-screen surface/window, if exists. + * + * @param pixelrect cursor pixels, maybe null for default cursor + * @param hotSpot maybe null for default cursor + * @return true if successful, i.e. on-screen surface/window w/ cursor capabilities exists. Otherwise false. + */ + public boolean setCursor(PixelRectangle pixelrect, PointImmutable hotSpot); + + /** + * Optional method hiding the cursor in the corresponding on-screen surface/window, if exists. + * + * @return true if successful, i.e. on-screen surface/window w/ cursor capabilities exists. Otherwise false. */ - public void detachSurfaceLayer(final long layerHandle) throws NativeWindowException; + public boolean hideCursor(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 6a36bb130..0af2bdaf9 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -1,5 +1,5 @@ /** - * Copyright 2010 JogAmp Community. All rights reserved. + * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: @@ -28,154 +28,100 @@ package javax.media.nativewindow; - import jogamp.nativewindow.Debug; -import jogamp.nativewindow.SurfaceUpdatedHelper; - -import com.jogamp.common.util.locks.LockFactory; -import com.jogamp.common.util.locks.RecursiveLock; -public abstract class ProxySurface implements NativeSurface { +/** + * Provides a mutable {@link NativeSurface}, i.e. {@link MutableSurface}, while allowing an + * {@link UpstreamSurfaceHook} to influence the lifecycle and information. + * + * @see UpstreamSurfaceHook + * @see MutableSurface + * @see NativeSurface + */ +public interface ProxySurface extends MutableSurface { public static final boolean DEBUG = Debug.debug("ProxySurface"); - - private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - private AbstractGraphicsConfiguration config; // control access due to delegation - protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); - private long surfaceHandle_old; - protected long displayHandle; - protected int height; - protected int scrnIndex; - protected int width; - - public ProxySurface(AbstractGraphicsConfiguration cfg) { - invalidate(); - config = cfg; - displayHandle=cfg.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); - surfaceHandle_old = 0; - } - - void invalidate() { - displayHandle = 0; - invalidateImpl(); - } - protected abstract void invalidateImpl(); - - public final long getDisplayHandle() { - return displayHandle; - } - - protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - - public final AbstractGraphicsConfiguration getGraphicsConfiguration() { - return config.getNativeGraphicsConfiguration(); - } - - public final int getScreenIndex() { - return getGraphicsConfiguration().getScreen().getIndex(); - } - - public abstract long getSurfaceHandle(); - - public final int getWidth() { - return width; - } - - public final int getHeight() { - return height; - } - - public void surfaceSizeChanged(int width, int height) { - this.width = width; - this.height = height; - } - - public boolean surfaceSwap() { - return false; - } - - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.addSurfaceUpdatedListener(l); - } - - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); - } - - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); - } - - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { - surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - - public int lockSurface() throws NativeWindowException { - surfaceLock.lock(); - int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? - - if ( LOCK_SURFACE_NOT_READY == res ) { - try { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - adevice.lock(); - try { - res = lockSurfaceImpl(); - if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) { - res = LOCK_SURFACE_CHANGED; - if(DEBUG) { - System.err.println("ProxySurface: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle())); - // Thread.dumpStack(); - } - } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - adevice.unlock(); - } - } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - surfaceLock.unlock(); - } - } - } - return res; - } - - public final void unlockSurface() { - surfaceLock.validateLocked(); - surfaceHandle_old = getSurfaceHandle(); - - if (surfaceLock.getHoldCount() == 1) { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - try { - unlockSurfaceImpl(); - } finally { - adevice.unlock(); - } - } - surfaceLock.unlock(); - } - - protected abstract int lockSurfaceImpl(); - - protected abstract void unlockSurfaceImpl() ; - - public final void validateSurfaceLocked() { - surfaceLock.validateLocked(); - } - - public final boolean isSurfaceLocked() { - return surfaceLock.isLocked(); - } - - public final boolean isSurfaceLockedByOtherThread() { - return surfaceLock.isLockedByOtherThread(); - } - - public final Thread getSurfaceLockOwner() { - return surfaceLock.getOwner(); - } - - public abstract String toString(); + + /** + * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's surface handle + * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() + */ + public static final int OPT_PROXY_OWNS_UPSTREAM_SURFACE = 1 << 6; + + /** + * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's {@link AbstractGraphicsDevice}. + * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() + */ + public static final int OPT_PROXY_OWNS_UPSTREAM_DEVICE = 1 << 7; + + /** + * Implementation specific bitvalue stating the upstream's {@link NativeSurface} is an invisible window, i.e. maybe incomplete. + * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() + */ + public static final int OPT_UPSTREAM_WINDOW_INVISIBLE = 1 << 8; + + /** Allow redefining the AbstractGraphicsConfiguration */ + public void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg); + + /** + * Return the upstream {@link NativeSurface} if used, otherwise <code>null</code>. + * <p> + * An upstream {@link NativeSurface} may backup this {@link ProxySurface} instance's representation, + * e.g. via a {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set} {@link UpstreamSurfaceHook}. + * </p> + * <p> + * One example is the JOGL EGLWrappedSurface, which might be backed up by a + * native platform NativeSurface (X11, WGL, CGL, ..). + * </p> + */ + public NativeSurface getUpstreamSurface(); + + /** Returns the {@link UpstreamSurfaceHook} if {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set}, otherwise <code>null</code>. */ + public UpstreamSurfaceHook getUpstreamSurfaceHook(); + + /** + * Sets the {@link UpstreamSurfaceHook} and returns the previous value. + */ + public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook); + + /** + * Enables or disables the {@link UpstreamSurfaceHook} lifecycle functions + * {@link UpstreamSurfaceHook#create(ProxySurface)} and {@link UpstreamSurfaceHook#destroy(ProxySurface)}. + * <p> + * Use this for small code blocks where the native resources shall not change, + * i.e. resizing a derived (OpenGL) drawable. + * </p> + */ + public void enableUpstreamSurfaceHookLifecycle(boolean enable); + + /** + * {@link UpstreamSurfaceHook#create(ProxySurface)} is being issued and the proxy surface/window handles shall be set. + */ + public void createNotify(); + + /** + * {@link UpstreamSurfaceHook#destroy(ProxySurface)} is being issued and all proxy surface/window handles shall be cleared. + */ + public void destroyNotify(); + + public StringBuilder getUpstreamOptionBits(StringBuilder sink); + public int getUpstreamOptionBits(); + + /** Returns <code>true</code> if the give bit-mask <code>v</code> is set in this instance upstream-option-bits, otherwise <code>false</code>.*/ + public boolean containsUpstreamOptionBits(int v); + + /** Add the given bit-mask to this instance upstream-option-bits using bit-or w/ <code>v</code>.*/ + public void addUpstreamOptionBits(int v); + + /** Clear the given bit-mask from this instance upstream-option-bits using bit-and w/ <code>~v</code>*/ + public void clearUpstreamOptionBits(int v); + + public StringBuilder toString(StringBuilder sink); + @Override + public String toString(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java b/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java deleted file mode 100644 index 956e68e61..000000000 --- a/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any kind. ALL - * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, - * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN - * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR - * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR - * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE - * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, - * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF - * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for use - * in the design, construction, operation or maintenance of any nuclear - * facility. - * - * Sun gratefully acknowledges that this software was originally authored - * and developed by Kenneth Bradley Russell and Christopher John Kline. - */ - -package javax.media.nativewindow; - -public interface SurfaceChangeable { - - /** Sets the surface handle which is created outside of this implementation */ - public void setSurfaceHandle(long surfaceHandle); - - /** - * The surface's size has been determined or changed. - * Implementation shall update the stored surface size with the given ones. - */ - public void surfaceSizeChanged(int width, int height); - -} - diff --git a/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java b/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java index 0912b5afe..de65a3031 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java +++ b/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,7 +29,7 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * */ package javax.media.nativewindow; diff --git a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java index 30f9660f0..017b996d7 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java @@ -33,12 +33,46 @@ import jogamp.nativewindow.Debug; /** * Marker for a singleton global recursive blocking lock implementation, * optionally locking a native windowing toolkit as well. - * <br> - * One use case is the AWT locking on X11, see {@link jogamp.nativewindow.jawt.JAWTToolkitLock}. + * <p> + * Toolkit locks are created solely via {@link NativeWindowFactory}. + * </p> + * <p> + * One use case is the AWT locking on X11, see {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. + * </p> */ public interface ToolkitLock { + public static final boolean DEBUG = Debug.debug("ToolkitLock"); public static final boolean TRACE_LOCK = Debug.isPropertyDefined("nativewindow.debug.ToolkitLock.TraceLock", true); + /** + * Blocking until the lock is acquired by this Thread or a timeout is reached. + * <p> + * Timeout is implementation specific, if used at all. + * </p> + * + * @throws RuntimeException in case of a timeout + */ public void lock(); + + /** + * Release the lock. + * + * @throws RuntimeException in case the lock is not acquired by this thread. + */ public void unlock(); + + /** + * @throws RuntimeException if current thread does not hold the lock + */ + public void validateLocked() throws RuntimeException; + + /** + * Dispose this instance. + * <p> + * Shall be called when instance is no more required. + * </p> + * This allows implementations sharing a lock via resources + * to decrease the reference counter. + */ + public void dispose(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java new file mode 100644 index 000000000..f08a6c938 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java @@ -0,0 +1,52 @@ +/** + * Copyright 2012 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow; + +/** + * Interface allowing upstream caller to pass lifecycle actions and size info + * to a {@link ProxySurface} instance. + */ +public interface UpstreamSurfaceHook { + /** called within {@link ProxySurface#createNotify()} within lock, before using surface. */ + public void create(ProxySurface s); + /** called within {@link ProxySurface#destroyNotify()} within lock, before clearing fields. */ + public void destroy(ProxySurface s); + + /** Returns the width of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + public int getWidth(ProxySurface s); + /** Returns the height of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + public int getHeight(ProxySurface s); + + /** + * {@link UpstreamSurfaceHook} w/ mutable size, allowing it's {@link ProxySurface} user to resize. + */ + public interface MutableSize extends UpstreamSurfaceHook { + public void setSize(int width, int height); + } +} diff --git a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java index 4f3d3ff00..4ed79b1dc 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java +++ b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java @@ -38,7 +38,7 @@ import java.util.Comparator; * </p> */ public interface VisualIDHolder { - + public enum VIDType { // Generic Values INTRINSIC(0), NATIVE(1), @@ -47,19 +47,19 @@ public interface VisualIDHolder { // X11 Values X11_XVISUAL(20), X11_FBCONFIG(21), // Windows Values - WIN32_PFD(30); - + WIN32_PFD(30); + public final int id; VIDType(int id){ this.id = id; } - } - + } + /** * Returns the native visual ID of the given <code>type</code> * if supported, or {@link #VID_UNDEFINED} if not supported. - * <p> + * <p> * Depending on the native windowing system, <code>type</code> is handled as follows: * <ul> * <li>X11 throws NativeWindowException on <code>EGL_CONFIG</code>, <code>WIN32_PFD</code> @@ -76,7 +76,7 @@ public interface VisualIDHolder { * <li><code>X11_XVISUAL</code>: <i>X11 XVisual ID</i></li> * <li><code>X11_FBCONFIG</code>: <i>X11 FBConfig ID</i> or <code>VID_UNDEFINED</code></li> * </ul></li> - * <li>Windows/GL throws NativeWindowException on <code>EGL_CONFIG</code>, <code>X11_XVISUAL</code>, <code>X11_FBCONFIG</code> + * <li>Windows/GL throws NativeWindowException on <code>EGL_CONFIG</code>, <code>X11_XVISUAL</code>, <code>X11_FBCONFIG</code> * <ul> * <li><code>INTRINSIC</code>: <i>Win32 PIXELFORMATDESCRIPTOR ID</i></li> * <li><code>NATIVE</code>: <i>Win32 PIXELFORMATDESCRIPTOR ID</i></li> @@ -91,35 +91,36 @@ public interface VisualIDHolder { * </ul> * </p> * Note: <code>INTRINSIC</code> and <code>NATIVE</code> are always handled, - * but may result in {@link #VID_UNDEFINED}. The latter is true if - * the native value are actually undefined or the corresponding object is not + * but may result in {@link #VID_UNDEFINED}. The latter is true if + * the native value are actually undefined or the corresponding object is not * mapped to a native visual object. - * + * * @throws NativeWindowException if <code>type</code> is neither * <code>INTRINSIC</code> nor <code>NATIVE</code> - * and does not match the native implementation. + * and does not match the native implementation. */ int getVisualID(VIDType type) throws NativeWindowException ; - - /** + + /** * {@link #getVisualID(VIDType)} result indicating an undefined value, * which could be cause by an unsupported query. * <p> * We assume the const value <code>0</code> doesn't reflect a valid native visual ID * and is interpreted as <i>no value</i> on all platforms. * This is currently true for Android, X11 and Windows. - * </p> + * </p> */ static final int VID_UNDEFINED = 0; - + /** Comparing {@link VIDType#NATIVE} */ public static class VIDComparator implements Comparator<VisualIDHolder> { private VIDType type; - + public VIDComparator(VIDType type) { this.type = type; } - + + @Override public int compare(VisualIDHolder vid1, VisualIDHolder vid2) { final int id1 = vid1.getVisualID(type); final int id2 = vid2.getVisualID(type); @@ -131,5 +132,5 @@ public interface VisualIDHolder { } return 0; } - } + } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java index 884c916e4..8570b78da 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java +++ b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java @@ -37,13 +37,17 @@ package javax.media.nativewindow; * this protocol default behavior {@link WindowClosingMode#DISPOSE_ON_CLOSE DISPOSE_ON_CLOSE} shall be used.</p> */ public interface WindowClosingProtocol { + + /** + * Window closing mode if triggered by toolkit close operation. + */ public enum WindowClosingMode { /** * Do nothing on native window close operation.<br> * This is the default behavior within an AWT environment. */ DO_NOTHING_ON_CLOSE, - + /** * Dispose resources on native window close operation.<br> * This is the default behavior in case no underlying toolkit defines otherwise. diff --git a/src/nativewindow/classes/javax/media/nativewindow/package.html b/src/nativewindow/classes/javax/media/nativewindow/package.html index 14730a548..3fe42bab0 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/package.html +++ b/src/nativewindow/classes/javax/media/nativewindow/package.html @@ -1,7 +1,7 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> - <title>NativeWindow Protocol Draft Public Review Specification</title> + <title>NativeWindow Specification Overview</title> </head> <body> @@ -10,7 +10,7 @@ <h3>Preface</h3> This specification, an optional set of packages, describing a <i>protocol</i> for a <i>native windowing interface</i> binding to Java(TM).<br> - Currently specified <i>native windowing systems</i> are:<br><br> + Currently specified <i>native windowing systems</i> are: <ul> <li> EGL/OpenKODE Windowing System</li> <li> X11 Windowing System</li> @@ -20,95 +20,79 @@ </ul> <br> However, any other native windowing system may be added to the implementation, - using a generic string identifier and an optional specialisation of:<br><br> + using a generic string identifier and an optional specialisation of: <ul> - <li>{@link javax.media.nativewindow.AbstractGraphicsDevice AbstractGraphicsDevice},<br> - <br> - Shall return the new string identifier with {@link javax.media.nativewindow.AbstractGraphicsDevice#getType() getType()}</li> + <li>{@link javax.media.nativewindow.AbstractGraphicsDevice AbstractGraphicsDevice}, + <p>Shall return the new string identifier with {@link javax.media.nativewindow.AbstractGraphicsDevice#getType() getType()}</p></li> <li>{@link javax.media.nativewindow.AbstractGraphicsScreen AbstractGraphicsScreen}</li> <li>{@link javax.media.nativewindow.AbstractGraphicsConfiguration AbstractGraphicsConfiguration}</li> </ul> - <br> - The implementor has to provide the following:<br><br> + <p>The implementor has to provide the following:</p> <ul> - <li> The specialisation of the abstract class {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}<br> - <br> - shall be registered with {@link javax.media.nativewindow.NativeWindowFactory#registerFactory NativeWindowFactory.registerFactory(..)}.</li> + <li> The specialisation of the abstract class {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory} + <p>shall be registered with {@link javax.media.nativewindow.NativeWindowFactory#registerFactory NativeWindowFactory.registerFactory(..)}.</p></li> - <li> The specialisation of the abstract class {@link javax.media.nativewindow.GraphicsConfigurationFactory GraphicsConfigurationFactory}<br> - <br> - shall be registered with {@link javax.media.nativewindow.GraphicsConfigurationFactory#registerFactory GraphicsConfigurationFactory.registerFactory(..)}.</li> - </ul><br> - This protocol <i>does not</i> describe how to <i>create</i> native windows, but how to <i>bind</i> a native surface to an implementation of - and window to an implementation of {@link javax.media.nativewindow.NativeSurface NativeSurface}.<br> - {@link javax.media.nativewindow.NativeWindow NativeWindow} specializes the NativeSurface.<br> - However, an implementation of this protocol (e.g. {@link com.jogamp.newt}) may support the creation.<br> + <li> The specialisation of the abstract class {@link javax.media.nativewindow.GraphicsConfigurationFactory GraphicsConfigurationFactory} + <p>shall be registered with {@link javax.media.nativewindow.GraphicsConfigurationFactory#registerFactory GraphicsConfigurationFactory.registerFactory(..)}.</p></li> + </ul> + <p>This protocol <i>does not</i> describe how to <i>create</i> native windows, but how to <i>bind</i> a native surface to an implementation of + and window to an implementation of {@link javax.media.nativewindow.NativeSurface NativeSurface}.</p> + <p>{@link javax.media.nativewindow.NativeWindow NativeWindow} specializes the NativeSurface.</p> + <p>However, an implementation of this protocol (e.g. {@link com.jogamp.newt}) may support the creation.</p> <h3>Dependencies</h3> This binding has dependencies to the following: <ul> - <li> Either of the following Java implementations:<br/> + <li> Either of the following Java implementations: <ul> - <li> <a href="http://java.sun.com/j2se/1.5.0/docs/api/">Java SE 1.5 or later</a> </li> - <li> A mobile JavaVM with language 1.5 support, ie: + <li> <a href="http://docs.oracle.com/javase/6/docs/api/">Java SE 1.6 or later</a> </li> + <li> A mobile JavaVM with language 1.6 support, ie: <ul> - <li> <a href="http://developer.android.com/reference/packages.html">Dalvik API Level 7</a> </li> + <li> <a href="http://developer.android.com/reference/packages.html">Android API Level 9 (Version 2.3)</a> </li> <li> <a href="http://jamvm.sourceforge.net/">JamVM</a> </li> </ul> with <ul> - <li> <a href="http://java.sun.com/products/foundation/">Foundation Profile 1.1.2 (JSR 219)</a> </li> - <li> <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/package-summary.html"> Java 1.4 <i>java.nio</i> implementation</a> </li> + <li> <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/nio/package-summary.html"> Java 1.4 <i>java.nio</i> implementation</a> </li> </ul></li> </ul></li> </ul> <br> <h3>Package Structure</h3> - The packages defined by this specification include:<br/><br/> + The packages defined by this specification include: <ul> - <li>The <b>javax.media.nativewindow</b> package<br> - <br> - This package contains Java bindings for a native windowing system.<br> - Subsequent packages contain marker type classes, containing native characteristics of the windowing system. - - <ul> - <li>The <b>javax.media.nativewindow.awt</b> package<br> - <br> - This sub package contains classes to cover the native characteristics of the AWT windowing system.</li> + <li>The <b>javax.media.nativewindow</b> package + <p>This package contains Java bindings for a native windowing system.</p> + <p>Subsequent packages contain marker type classes, containing native characteristics of the windowing system.</p> + <ul> + <li>The <b>javax.media.nativewindow.awt</b> package + <p>This sub package contains classes to cover the native characteristics of the AWT windowing system.</p></li> - <li>The <b>javax.media.nativewindow.x11</b> package<br> - <br> - This sub package contains classes to cover the native characteristics of the X11 windowing system.</li> + <li>The <b>javax.media.nativewindow.x11</b> package + <p>This sub package contains classes to cover the native characteristics of the X11 windowing system.</p></li> - <li>The <b>javax.media.nativewindow.windows</b> package<br> - <br> - This sub package contains classes to cover the native characteristics of the Windows windowing system.</li> + <li>The <b>javax.media.nativewindow.windows</b> package + <p>This sub package contains classes to cover the native characteristics of the Windows windowing system.</p></li> - <li>The <b>javax.media.nativewindow.macosx</b> package<br> - <br> - This sub package contains classes to cover the native characteristics of the MacOSX windowing system.</li> + <li>The <b>javax.media.nativewindow.macosx</b> package + <p>This sub package contains classes to cover the native characteristics of the MacOSX windowing system.</p></li> - <li>The <b>javax.media.nativewindow.egl</b> package<br> - <br> - This sub package contains classes to cover the native characteristics of the EGL/OpenKODE windowing system.</li> + <li>The <b>javax.media.nativewindow.egl</b> package + <p>This sub package contains classes to cover the native characteristics of the EGL/OpenKODE windowing system.</p></li> </ul></li> </ul> <h3>Factory Model</h3> -Running on a platform with a supported windowing system, the factory model shall be used -to instantiate a native window, see {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}.<br> -The implementor has to specialize -All supported -Regardless of the knowledge of the underly -<br> +<p>Running on a platform with a supported windowing system, the factory model shall be used +to instantiate a native window, see {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}.</p> -<h3>Revision History<br> - </h3> +<h3>Revision History</h3> <ul> <li> Early Draft Review, June 2009</li> <li> 2.0.0 Maintenance Release, February 2011</li> +<li> 2.0.2 Major Release, July 18th 2013</li> </ul> <br> <br> diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index 0a5a94565..24ccc836a 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -4,14 +4,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -21,12 +21,12 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; public class Dimension implements Cloneable, DimensionImmutable { @@ -45,10 +45,12 @@ public class Dimension implements Cloneable, DimensionImmutable { this.height=height; } + @Override public Object cloneMutable() { return clone(); } - + + @Override public Object clone() { try { return super.clone(); @@ -57,40 +59,62 @@ public class Dimension implements Cloneable, DimensionImmutable { } } - public int getWidth() { return width; } - public int getHeight() { return height; } + @Override + public final int getWidth() { return width; } + @Override + public final int getHeight() { return height; } - public void setWidth(int width) { + public final void set(int width, int height) { this.width = width; + this.height = height; } - public void setHeight(int height) { + public final void setWidth(int width) { + this.width = width; + } + public final void setHeight(int height) { this.height = height; } - public Dimension scale(int s) { + public final Dimension scale(int s) { width *= s; height *= s; return this; } - public Dimension add(Dimension pd) { + public final Dimension add(Dimension pd) { width += pd.width ; height += pd.height ; return this; } + @Override public String toString() { - return new String(width+" x "+height); + return width + " x " + height; + } + + @Override + public int compareTo(final DimensionImmutable d) { + final int tsq = width*height; + final int xsq = d.getWidth()*d.getHeight(); + + if(tsq > xsq) { + return 1; + } else if(tsq < xsq) { + return -1; + } + return 0; } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Dimension) { Dimension p = (Dimension)obj; - return height == p.height && + return height == p.height && width == p.width ; } return false; } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + width; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java index d14e94c10..e6cacf4ff 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java @@ -37,21 +37,32 @@ import com.jogamp.common.type.WriteCloneable; * <li><code>height</code></li> * </ul> */ -public interface DimensionImmutable extends WriteCloneable { +public interface DimensionImmutable extends WriteCloneable, Comparable<DimensionImmutable> { int getHeight(); int getWidth(); /** + * <p> + * Compares square of size. + * </p> + * {@inheritDoc} + */ + @Override + public int compareTo(final DimensionImmutable d); + + /** * Checks whether two dimensions objects are equal. Two instances * of <code>DimensionReadOnly</code> are equal if two components * <code>height</code> and <code>width</code> are equal. * @return <code>true</code> if the two dimensions are equal; * otherwise <code>false</code>. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index 199ec27cb..3644916fe 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,18 +20,18 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; public class Insets implements Cloneable, InsetsImmutable { static final InsetsImmutable zeroInsets = new Insets(); public static final InsetsImmutable getZero() { return zeroInsets; } - + int l, r, t, b; public Insets() { @@ -44,11 +44,13 @@ public class Insets implements Cloneable, InsetsImmutable { this.t=top; this.b=bottom; } - + + @Override public Object cloneMutable() { return clone(); } - + + @Override protected Object clone() { try { return super.clone(); @@ -57,18 +59,28 @@ public class Insets implements Cloneable, InsetsImmutable { } } + @Override public final int getLeftWidth() { return l; } + @Override public final int getRightWidth() { return r; } + @Override public final int getTotalWidth() { return l + r; } + @Override public final int getTopHeight() { return t; } + @Override public final int getBottomHeight() { return b; } + @Override public final int getTotalHeight() { return t + b; } - public void setLeftWidth(int left) { l = left; } - public void setRightWidth(int right) { r = right; } - public void setTopHeight(int top) { t = top; } - public void setBottomHeight(int bottom) { b = bottom; } - + public final void set(int left, int right, int top, int bottom) { + l = left; r = right; t = top; b = bottom; + } + public final void setLeftWidth(int left) { l = left; } + public final void setRightWidth(int right) { r = right; } + public final void setTopHeight(int top) { t = top; } + public final void setBottomHeight(int bottom) { b = bottom; } + + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Insets) { @@ -79,6 +91,7 @@ public class Insets implements Cloneable, InsetsImmutable { return false; } + @Override public int hashCode() { int sum1 = l + b; int sum2 = t + r; @@ -88,8 +101,9 @@ public class Insets implements Cloneable, InsetsImmutable { return sum3 * (sum3 + 1)/2 + val2; } + @Override public String toString() { - return new String("[ l "+l+", r "+r+" - t "+t+", b "+b+" - "+getTotalWidth()+"x"+getTotalHeight()+"]"); + return "[ l "+l+", r "+r+" - t "+t+", b "+b+" - "+getTotalWidth()+"x"+getTotalHeight()+"]"; } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java index 075641ede..8256068cd 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java @@ -41,13 +41,13 @@ public interface InsetsImmutable extends WriteCloneable { /** @return total width, ie. <code>left_width + right_width</code> */ int getTotalWidth(); - + /** @return top inset height */ int getTopHeight(); /** @return bottom inset height */ int getBottomHeight(); - + /** @return total height, ie. <code>top_height + bottom_height</code> */ int getTotalHeight(); @@ -59,8 +59,10 @@ public interface InsetsImmutable extends WriteCloneable { * @return <code>true</code> if the two Insets are equal; * otherwise <code>false</code>. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java new file mode 100644 index 000000000..823496a92 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2014 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow.util; + +/** + * Basic pixel formats + * <p> + * Notation follows OpenGL notation, i.e. + * name consist of all it's component names + * followed by their bit size. + * </p> + * <p> + * Order of component names is from lowest-bit to highest-bit. + * </p> + * <p> + * In case component-size is 1 byte (e.g. OpenGL data-type GL_UNSIGNED_BYTE), + * component names are ordered from lowest-byte to highest-byte. + * Note that OpenGL applies special interpretation if + * data-type is e.g. GL_UNSIGNED_8_8_8_8_REV or GL_UNSIGNED_8_8_8_8_REV. + * </p> + * <p> + * PixelFormat can be converted to OpenGL GLPixelAttributes + * via + * <pre> + * GLPixelAttributes glpa = GLPixelAttributes.convert(PixelFormat pixFmt, GLProfile glp); + * </pre> + * </p> + * <p> + * See OpenGL Specification 4.3 - February 14, 2013, Core Profile, + * Section 8.4.4 Transfer of Pixel Rectangles, p. 161-174. + * </ul> + * + * </p> + */ +public enum PixelFormat { + /** + * Pixel size is 1 bytes (8 bits) with one component of size 1 byte (8 bits). + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_ALPHA (< GL3), GL_RED (>= GL3), data-type GL_UNSIGNED_BYTE</li> + * <li>AWT: <i>none</i></li> + * </ul> + * </p> + */ + LUMINANCE(1, 8), + + /** + * Pixel size is 3 bytes (24 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: R, G, B</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_RGB, data-type GL_UNSIGNED_BYTE</li> + * <li>AWT: <i>None</i></li> + * </ul> + * </p> + */ + RGB888(3, 24), + + /** + * Pixel size is 3 bytes (24 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: B, G, R</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_BGR (>= GL2), data-type GL_UNSIGNED_BYTE</li> + * <li>AWT: {@link java.awt.image.BufferedImage#TYPE_3BYTE_BGR TYPE_3BYTE_BGR}</li> + * </ul> + * </p> + */ + BGR888(3, 24), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: R, G, B, A</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_RGBA, data-type GL_UNSIGNED_BYTE</li> + * <li>AWT: <i>None</i></li> + * <li>PointerIcon: X11 (XCURSOR)</li> + * <li>PNGJ: Scanlines</li> + * </ul> + * </p> + */ + RGBA8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: A, B, G, R</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_RGBA, data-type GL_UNSIGNED_8_8_8_8</li> + * <li>AWT: {@link java.awt.image.BufferedImage#TYPE_4BYTE_ABGR TYPE_4BYTE_ABGR}</li> + * </ul> + * </p> + */ + ABGR8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: A, R, G, B</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_BGRA, data-type GL_UNSIGNED_INT_8_8_8_8</li> + * <li>AWT: <i>None</i></li> + * </ul> + * </p> + */ + ARGB8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + * <p> + * The components are interleaved in the order: + * <ul> + * <li>Low to High: B, G, R, A</li> + * </ul> + * </p> + * <p> + * Compatible with: + * <ul> + * <li>OpenGL: data-format GL_BGRA, data-type GL_UNSIGNED_BYTE</li> + * <li>AWT: {@link java.awt.image.BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}</li> + * <li>PointerIcon: Win32, OSX (NSBitmapImageRep), AWT</li> + * <li>Window Icon: X11, Win32, OSX (NSBitmapImageRep)</li> + * </ul> + * </p> + */ + BGRA8888(4, 32); + + /** Number of components per pixel, e.g. 4 for RGBA. */ + public final int componentCount; + /** Number of bits per pixel, e.g. 32 for RGBA. */ + public final int bitsPerPixel; + /** Number of bytes per pixel, e.g. 4 for RGBA. */ + public final int bytesPerPixel() { return (7+bitsPerPixel)/8; } + + private PixelFormat(int componentCount, int bpp) { + this.componentCount = componentCount; + this.bitsPerPixel = bpp; + } +} diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java new file mode 100644 index 000000000..87a9ca4fc --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java @@ -0,0 +1,373 @@ +/** + * Copyright (c) 2014 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package javax.media.nativewindow.util; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import com.jogamp.common.nio.Buffers; + +/** + * Pixel Rectangle Utilities. + * <p> + * All conversion methods are endian independent. + * </p> + */ +public class PixelFormatUtil { + public static interface PixelSink { + /** Return the sink's destination pixelformat. */ + PixelFormat getPixelformat(); + + /** + * Returns stride in byte-size, i.e. byte count from one line to the next. + * <p> + * Must be >= {@link #getPixelformat()}.{@link PixelFormat#bytesPerPixel() bytesPerPixel()} * {@link #getSize()}.{@link DimensionImmutable#getWidth() getWidth()}. + * </p> + */ + int getStride(); + + /** + * Returns <code>true</code> if the sink's memory is laid out in + * OpenGL's coordinate system, <i>origin at bottom left</i>. + * Otherwise returns <code>false</code>, i.e. <i>origin at top left</i>. + */ + boolean isGLOriented(); + } + /** + * Pixel sink for up-to 32bit. + */ + public static interface PixelSink32 extends PixelSink { + /** + * Will be invoked over all rows top-to down + * and all columns left-to-right. + * <p> + * Shall consider dest pixelformat and only store as much components + * as defined, up to 32bit. + * </p> + * <p> + * Implementation may better write single bytes from low-to-high bits, + * e.g. {@link ByteOrder#LITTLE_ENDIAN} order. + * Otherwise a possible endian conversion must be taken into consideration. + * </p> + * @param x + * @param y + * @param pixel + */ + void store(int x, int y, int pixel); + } + + /** + * Returns the {@link PixelFormat} with reversed components of <code>fmt</code>. + * If no reversed {@link PixelFormat} is available, returns <code>fmt</code>. + */ + public static PixelFormat getReversed(PixelFormat fmt) { + switch(fmt) { + case LUMINANCE: + return PixelFormat.LUMINANCE; + case RGB888: + return PixelFormat.BGR888; + case BGR888: + return PixelFormat.RGB888; + case RGBA8888: + return PixelFormat.ABGR8888; + case ABGR8888: + return PixelFormat.RGBA8888; + case ARGB8888: + return PixelFormat.BGRA8888; + case BGRA8888: + return PixelFormat.ABGR8888; + default: + throw new InternalError("Unhandled format "+fmt); + } + } + + public static int getValue32(PixelFormat src_fmt, ByteBuffer src, int srcOff) { + switch(src_fmt) { + case LUMINANCE: { + final byte c1 = src.get(srcOff++); + return ( 0xff ) << 24 | ( 0xff & c1 ) << 16 | ( 0xff & c1 ) << 8 | ( 0xff & c1 ); + } + case RGB888: + case BGR888: { + final byte c1 = src.get(srcOff++); + final byte c2 = src.get(srcOff++); + final byte c3 = src.get(srcOff++); + return ( 0xff ) << 24 | ( 0xff & c3 ) << 16 | ( 0xff & c2 ) << 8 | ( 0xff & c1 ); + } + case RGBA8888: + case ABGR8888: + case ARGB8888: + case BGRA8888: { + final byte c1 = src.get(srcOff++); + final byte c2 = src.get(srcOff++); + final byte c3 = src.get(srcOff++); + final byte c4 = src.get(srcOff++); + return ( 0xff & c4 ) << 24 | ( 0xff & c3 ) << 16 | ( 0xff & c2 ) << 8 | ( 0xff & c1 ); + } + default: + throw new InternalError("Unhandled format "+src_fmt); + } + } + + public static int convertToInt32(PixelFormat dest_fmt, final byte r, final byte g, final byte b, final byte a) { + switch(dest_fmt) { + case LUMINANCE: { + final byte l = ( byte) ( ( ( ( 0xff & r ) + ( 0xff & g ) + ( 0xff & b ) ) / 3 ) ); + return ( 0xff ) << 24 | ( 0xff & l ) << 16 | ( 0xff & l ) << 8 | ( 0xff & l ); + } + case RGB888: + return ( 0xff ) << 24 | ( 0xff & b ) << 16 | ( 0xff & g ) << 8 | ( 0xff & r ); + case BGR888: + return ( 0xff ) << 24 | ( 0xff & r ) << 16 | ( 0xff & g ) << 8 | ( 0xff & b ); + case RGBA8888: + return ( 0xff & a ) << 24 | ( 0xff & b ) << 16 | ( 0xff & g ) << 8 | ( 0xff & r ); + case ABGR8888: + return ( 0xff & r ) << 24 | ( 0xff & g ) << 16 | ( 0xff & b ) << 8 | ( 0xff & a ); + case ARGB8888: + return ( 0xff & b ) << 24 | ( 0xff & g ) << 16 | ( 0xff & r ) << 8 | ( 0xff & a ); + case BGRA8888: + return ( 0xff & a ) << 24 | ( 0xff & r ) << 16 | ( 0xff & g ) << 8 | ( 0xff & b ); + default: + throw new InternalError("Unhandled format "+dest_fmt); + } + } + + public static int convertToInt32(PixelFormat dest_fmt, PixelFormat src_fmt, ByteBuffer src, int srcOff) { + final byte r, g, b, a; + switch(src_fmt) { + case LUMINANCE: + r = src.get(srcOff++); // R + g = r; // G + b = r; // B + a = (byte) 0xff; // A + break; + case RGB888: + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + a = (byte) 0xff; // A + break; + case BGR888: + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + a = (byte) 0xff; // A + break; + case RGBA8888: + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + a = src.get(srcOff++); // A + break; + case ABGR8888: + a = src.get(srcOff++); // A + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + break; + case ARGB8888: + a = src.get(srcOff++); // A + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + break; + case BGRA8888: + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + a = src.get(srcOff++); // A + break; + default: + throw new InternalError("Unhandled format "+src_fmt); + } + return convertToInt32(dest_fmt, r, g, b, a); + } + + public static int convertToInt32(PixelFormat dest_fmt, PixelFormat src_fmt, final int src_pixel) { + final byte r, g, b, a; + switch(src_fmt) { + case LUMINANCE: + r = (byte) ( src_pixel ); // R + g = r; // G + b = r; // B + a = (byte) 0xff; // A + break; + case RGB888: + r = (byte) ( src_pixel ); // R + g = (byte) ( src_pixel >>> 8 ); // G + b = (byte) ( src_pixel >>> 16 ); // B + a = (byte) 0xff; // A + break; + case BGR888: + b = (byte) ( src_pixel ); // B + g = (byte) ( src_pixel >>> 8 ); // G + r = (byte) ( src_pixel >>> 16 ); // R + a = (byte) 0xff; // A + break; + case RGBA8888: + r = (byte) ( src_pixel ); // R + g = (byte) ( src_pixel >>> 8 ); // G + b = (byte) ( src_pixel >>> 16 ); // B + a = (byte) ( src_pixel >>> 24 ); // A + break; + case ABGR8888: + a = (byte) ( src_pixel ); // A + b = (byte) ( src_pixel >>> 8 ); // B + g = (byte) ( src_pixel >>> 16 ); // G + r = (byte) ( src_pixel >>> 24 ); // R + break; + case ARGB8888: + a = (byte) ( src_pixel ); // A + r = (byte) ( src_pixel >>> 8 ); // R + g = (byte) ( src_pixel >>> 16 ); // G + b = (byte) ( src_pixel >>> 24 ); // B + break; + case BGRA8888: + b = (byte) ( src_pixel ); // B + g = (byte) ( src_pixel >>> 8 ); // G + r = (byte) ( src_pixel >>> 16 ); // R + a = (byte) ( src_pixel >>> 24 ); // A + break; + default: + throw new InternalError("Unhandled format "+src_fmt); + } + return convertToInt32(dest_fmt, r, g, b, a); + } + + public static PixelRectangle convert32(final PixelRectangle src, + final PixelFormat destFmt, int ddestStride, final boolean isGLOriented, + final boolean destIsDirect) { + final int width = src.getSize().getWidth(); + final int height = src.getSize().getHeight(); + final int bpp = destFmt.bytesPerPixel(); + final int destStride; + if( 0 != ddestStride ) { + destStride = ddestStride; + if( destStride < bpp * width ) { + throw new IllegalArgumentException("Invalid stride "+destStride+", must be greater than bytesPerPixel "+bpp+" * width "+width); + } + } else { + destStride = bpp * width; + } + final int capacity = destStride*height; + final ByteBuffer bb = destIsDirect ? Buffers.newDirectByteBuffer(capacity) : ByteBuffer.allocate(capacity).order(src.getPixels().order()); + + // System.err.println("XXX: SOURCE "+src); + // System.err.println("XXX: DEST fmt "+destFmt+", stride "+destStride+" ("+ddestStride+"), isGL "+isGLOriented+", "+width+"x"+height+", capacity "+capacity+", "+bb); + + final PixelFormatUtil.PixelSink32 imgSink = new PixelFormatUtil.PixelSink32() { + public void store(int x, int y, int pixel) { + int o = destStride*y+x*bpp; + bb.put(o++, (byte) ( pixel )); // 1 + if( 3 <= bpp ) { + bb.put(o++, (byte) ( pixel >>> 8 )); // 2 + bb.put(o++, (byte) ( pixel >>> 16 )); // 3 + if( 4 <= bpp ) { + bb.put(o++, (byte) ( pixel >>> 24 )); // 4 + } + } + } + @Override + public final PixelFormat getPixelformat() { + return destFmt; + } + @Override + public final int getStride() { + return destStride; + } + @Override + public final boolean isGLOriented() { + return isGLOriented; + } + }; + convert32(imgSink, src); + return new PixelRectangle.GenericPixelRect(destFmt, src.getSize(), destStride, isGLOriented, bb); + } + + public static void convert32(PixelSink32 destInt32, final PixelRectangle src) { + convert32(destInt32, + src.getPixels(), src.getPixelformat(), + src.isGLOriented(), + src.getSize().getWidth(), src.getSize().getHeight(), + src.getStride()); + } + + /** + * + * @param dest32 32bit pixel sink + * @param src_bb + * @param src_fmt + * @param src_glOriented if true, the source memory is laid out in OpenGL's coordinate system, <i>origin at bottom left</i>, + * otherwise <i>origin at top left</i>. + * @param width + * @param height + * @param strideInBytes stride in byte-size, i.e. byte count from one line to the next. + * If zero, stride is set to <code>width * bytes-per-pixel</code>. + * If not zero, value must be >= <code>width * bytes-per-pixel</code>. + * @param stride_bytes stride in byte-size, i.e. byte count from one line to the next. + * Must be >= {@link PixelFormat#bytesPerPixel() src_fmt.bytesPerPixel()} * width. + * @throws IllegalArgumentException if <code>strideInBytes</code> is invalid + */ + public static void convert32(PixelSink32 dest32, + final ByteBuffer src_bb, final PixelFormat src_fmt, final boolean src_glOriented, final int width, final int height, int stride_bytes) { + final int src_bpp = src_fmt.bytesPerPixel(); + if( 0 != stride_bytes ) { + if( stride_bytes < src_bpp * width ) { + throw new IllegalArgumentException("Invalid stride "+stride_bytes+", must be greater than bytesPerPixel "+src_bpp+" * width "+width); + } + } else { + stride_bytes = src_bpp * width; + } + final PixelFormat dest_fmt = dest32.getPixelformat(); + final boolean vert_flip = src_glOriented != dest32.isGLOriented(); + final boolean fast_copy = src_fmt == dest_fmt && dest_fmt.bytesPerPixel() == 4 ; + // System.err.println("XXX: SRC fmt "+src_fmt+", stride "+stride_bytes+", isGL "+src_glOriented+", "+width+"x"+height); + // System.err.println("XXX: DST fmt "+dest_fmt+", fast_copy "+fast_copy); + + if( fast_copy ) { + // Fast copy + for(int y=0; y<height; y++) { + int o = vert_flip ? ( height - 1 - y ) * stride_bytes : y * stride_bytes; + for(int x=0; x<width; x++) { + dest32.store(x, y, getValue32(src_fmt, src_bb, o)); + o += src_bpp; + } + } + } else { + // Conversion + for(int y=0; y<height; y++) { + int o = vert_flip ? ( height - 1 - y ) * stride_bytes : y * stride_bytes; + for(int x=0; x<width; x++) { + dest32.store( x, y, convertToInt32( dest_fmt, src_fmt, src_bb, o)); + o += src_bpp; + } + } + } + } +} + diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java new file mode 100644 index 000000000..96c1f7b33 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java @@ -0,0 +1,194 @@ +/** + * Copyright (c) 2014 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package javax.media.nativewindow.util; + +import java.nio.ByteBuffer; + +/** + * Pixel Rectangle identified by it's {@link #hashCode()}. + * <p> + * The {@link #getPixels()} are assumed to be immutable. + * </p> + */ +public interface PixelRectangle { + /** + * <p> + * Computes a hash code over: + * <ul> + * <li>pixelformat</li> + * <li>size</li> + * <li>stride</li> + * <li>isGLOriented</li> + * <li>pixels</li> + * </ul> + * </p> + * <p> + * The hashCode shall be computed only once with first call + * and stored for later retrieval to enhance performance. + * </p> + * <p> + * {@inheritDoc} + * </p> + */ + @Override + int hashCode(); + + /** Returns the {@link PixelFormat}. */ + PixelFormat getPixelformat(); + + /** Returns the size, i.e. width and height. */ + DimensionImmutable getSize(); + + /** + * Returns stride in byte-size, i.e. byte count from one line to the next. + * <p> + * Must be >= {@link #getPixelformat()}.{@link PixelFormat#bytesPerPixel() bytesPerPixel()} * {@link #getSize()}.{@link DimensionImmutable#getWidth() getWidth()}. + * </p> + */ + int getStride(); + + /** + * Returns <code>true</code> if the memory is laid out in + * OpenGL's coordinate system, <i>origin at bottom left</i>. + * Otherwise returns <code>false</code>, i.e. <i>origin at top left</i>. + */ + public boolean isGLOriented(); + + /** Returns the pixels. */ + ByteBuffer getPixels(); + + @Override + String toString(); + + /** + * Generic PixelRectangle implementation + */ + public static class GenericPixelRect implements PixelRectangle { + protected final PixelFormat pixelformat; + protected final DimensionImmutable size; + protected final int strideInBytes; + protected final boolean isGLOriented; + protected final ByteBuffer pixels; + private int hashCode = 0; + private volatile boolean hashCodeComputed = false; + + /** + * + * @param pixelformat + * @param size + * @param strideInBytes stride in byte-size, i.e. byte count from one line to the next. + * If not zero, value must be >= <code>width * bytes-per-pixel</code>. + * If zero, stride is set to <code>width * bytes-per-pixel</code>. + * @param isGLOriented + * @param pixels + * @throws IllegalArgumentException if <code>strideInBytes</code> is invalid. + * @throws IndexOutOfBoundsException if <code>pixels</code> has insufficient bytes left + */ + public GenericPixelRect(final PixelFormat pixelformat, final DimensionImmutable size, int strideInBytes, final boolean isGLOriented, final ByteBuffer pixels) + throws IllegalArgumentException, IndexOutOfBoundsException + { + if( 0 != strideInBytes ) { + if( strideInBytes < pixelformat.bytesPerPixel() * size.getWidth()) { + throw new IllegalArgumentException("Invalid stride "+strideInBytes+", must be greater than bytesPerPixel "+pixelformat.bytesPerPixel()+" * width "+size.getWidth()); + } + } else { + strideInBytes = pixelformat.bytesPerPixel() * size.getWidth(); + } + final int reqBytes = strideInBytes * size.getHeight(); + if( pixels.limit() < reqBytes ) { + throw new IndexOutOfBoundsException("Dest buffer has insufficient bytes left, needs "+reqBytes+": "+pixels); + } + this.pixelformat = pixelformat; + this.size = size; + this.strideInBytes = strideInBytes; + this.isGLOriented = isGLOriented; + this.pixels = pixels; + } + + /** + * Copy ctor validating src. + * @param src + * @throws IllegalArgumentException if <code>strideInBytes</code> is invalid. + * @throws IndexOutOfBoundsException if <code>pixels</code> has insufficient bytes left + */ + public GenericPixelRect(final PixelRectangle src) + throws IllegalArgumentException, IndexOutOfBoundsException + { + this(src.getPixelformat(), src.getSize(), src.getStride(), src.isGLOriented(), src.getPixels()); + } + + @Override + public int hashCode() { + if( !hashCodeComputed ) { // DBL CHECKED OK VOLATILE + synchronized (this) { + if( !hashCodeComputed ) { + // 31 * x == (x << 5) - x + int hash = 31 + pixelformat.hashCode(); + hash = ((hash << 5) - hash) + size.hashCode(); + hash = ((hash << 5) - hash) + strideInBytes; + hash = ((hash << 5) - hash) + ( isGLOriented ? 1 : 0); + hashCode = ((hash << 5) - hash) + pixels.hashCode(); + hashCodeComputed = true; + } + } + } + return hashCode; + } + + @Override + public PixelFormat getPixelformat() { + return pixelformat; + } + + @Override + public DimensionImmutable getSize() { + return size; + } + + @Override + public int getStride() { + return strideInBytes; + } + + @Override + public boolean isGLOriented() { + return isGLOriented; + } + + @Override + public ByteBuffer getPixels() { + return pixels; + } + + @Override + public final String toString() { + return "PixelRect[obj 0x"+Integer.toHexString(super.hashCode())+", "+pixelformat+", "+size+", stride "+strideInBytes+", isGLOrient "+isGLOriented+", pixels "+pixels+"]"; + } + } +} + diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index c53b16928..331c1388e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -42,10 +42,12 @@ public class Point implements Cloneable, PointImmutable { this(0, 0); } + @Override public Object cloneMutable() { return clone(); } - + + @Override public Object clone() { try { return super.clone(); @@ -54,6 +56,20 @@ public class Point implements Cloneable, PointImmutable { } } + @Override + public int compareTo(final PointImmutable d) { + final int sq = x*y; + final int xsq = d.getX()*d.getY(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + return 0; + } + + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Point) { @@ -63,14 +79,17 @@ public class Point implements Cloneable, PointImmutable { return false; } + @Override public final int getX() { return x; } + @Override public final int getY() { return y; } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + x; @@ -78,29 +97,31 @@ public class Point implements Cloneable, PointImmutable { return hash; } + @Override public String toString() { - return new String( x + " / " + y ); + return x + " / " + y; } - public void setX(int x) { this.x = x; } - public void setY(int y) { this.y = y; } + public final void set(int x, int y) { this.x = x; this.y = y; } + public final void setX(int x) { this.x = x; } + public final void setY(int y) { this.y = y; } - public Point translate(Point pd) { + public final Point translate(Point pd) { x += pd.x ; y += pd.y ; return this; } - public Point translate(int dx, int dy) { + public final Point translate(int dx, int dy) { x += dx ; y += dy ; return this; } - public Point scale(int sx, int sy) { + public final Point scale(int sx, int sy) { x *= sx ; y *= sy ; return this; } - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java index d7eb0e7b4..08c628cc1 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java @@ -32,21 +32,32 @@ package javax.media.nativewindow.util; import com.jogamp.common.type.WriteCloneable; /** Immutable Point interface */ -public interface PointImmutable extends WriteCloneable { +public interface PointImmutable extends WriteCloneable, Comparable<PointImmutable> { int getX(); int getY(); /** + * <p> + * Compares the square of the position. + * </p> + * {@inheritDoc} + */ + @Override + public int compareTo(final PointImmutable d); + + /** * Checks whether two points objects are equal. Two instances * of <code>PointReadOnly</code> are equal if the two components * <code>y</code> and <code>x</code> are equal. * @return <code>true</code> if the two points are equal; * otherwise <code>false</code>. */ + @Override public boolean equals(Object obj); + @Override public int hashCode(); - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 8d6bfe48f..d0d8bfb13 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,14 +20,16 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; +import java.util.List; + public class Rectangle implements Cloneable, RectangleImmutable { int x; int y; @@ -44,11 +46,13 @@ public class Rectangle implements Cloneable, RectangleImmutable { this.width=width; this.height=height; } - + + @Override public Object cloneMutable() { return clone(); } - + + @Override protected Object clone() { try { return super.clone(); @@ -57,15 +61,118 @@ public class Rectangle implements Cloneable, RectangleImmutable { } } + @Override public final int getX() { return x; } + @Override public final int getY() { return y; } + @Override public final int getWidth() { return width; } + @Override public final int getHeight() { return height; } - public void setX(int x) { this.x = x; } - public void setY(int y) { this.y = y; } - public void setWidth(int width) { this.width = width; } - public void setHeight(int height) { this.height = height; } + public final void set(int x, int y, int width, int height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + public final void setX(int x) { this.x = x; } + public final void setY(int y) { this.y = y; } + public final void setWidth(int width) { this.width = width; } + public final void setHeight(int height) { this.height = height; } + + @Override + public final RectangleImmutable union(final RectangleImmutable r) { + return union(r.getX(), r.getY(), r.getX() + r.getWidth(), r.getY() + r.getHeight()); + } + @Override + public final RectangleImmutable union(final int rx1, final int ry1, final int rx2, final int ry2) { + final int x1 = Math.min(x, rx1); + final int y1 = Math.min(y, ry1); + final int x2 = Math.max(x + width, rx2); + final int y2 = Math.max(y + height, ry2); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + } + /** + * Calculates the union of the given rectangles, stores it in this instance and returns this instance. + * @param rectangles given list of rectangles + * @return this instance holding the union of given rectangles. + */ + public final Rectangle union(final List<RectangleImmutable> rectangles) { + int x1=Integer.MAX_VALUE, y1=Integer.MAX_VALUE; + int x2=Integer.MIN_VALUE, y2=Integer.MIN_VALUE; + for(int i=rectangles.size()-1; i>=0; i--) { + final RectangleImmutable vp = rectangles.get(i); + x1 = Math.min(x1, vp.getX()); + x2 = Math.max(x2, vp.getX() + vp.getWidth()); + y1 = Math.min(y1, vp.getY()); + y2 = Math.max(y2, vp.getY() + vp.getHeight()); + } + set(x1, y1, x2 - x1, y2 - y1); + return this; + } + + @Override + public final RectangleImmutable intersection(RectangleImmutable r) { + return intersection(r.getX(), r.getY(), r.getX() + r.getWidth(), r.getY() + r.getHeight()); + } + @Override + public final RectangleImmutable intersection(final int rx1, final int ry1, final int rx2, final int ry2) { + final int x1 = Math.max(x, rx1); + final int y1 = Math.max(y, ry1); + final int x2 = Math.min(x + width, rx2); + final int y2 = Math.min(y + height, ry2); + final int ix, iy, iwidth, iheight; + if( x2 < x1 ) { + ix = 0; + iwidth = 0; + } else { + ix = x1; + iwidth = x2 - x1; + } + if( y2 < y1 ) { + iy = 0; + iheight = 0; + } else { + iy = y1; + iheight = y2 - y1; + } + return new Rectangle (ix, iy, iwidth, iheight); + } + @Override + public final float coverage(RectangleImmutable r) { + final RectangleImmutable isect = intersection(r); + final float sqI = (float) ( isect.getWidth()*isect.getHeight() ); + final float sqT = (float) ( width*height ); + return sqI / sqT; + } + + @Override + public int compareTo(final RectangleImmutable d) { + { + final int sq = width*height; + final int xsq = d.getWidth()*d.getHeight(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + } + { + final int sq = x*y; + final int xsq = d.getX()*d.getY(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + } + return 0; + } + + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Rectangle) { @@ -76,6 +183,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { return false; } + @Override public int hashCode() { int sum1 = x + height; int sum2 = width + y; @@ -85,8 +193,9 @@ public class Rectangle implements Cloneable, RectangleImmutable { return sum3 * (sum3 + 1)/2 + val2; } + @Override public String toString() { - return new String("[ "+x+" / "+y+" "+width+" x "+height+" ]"); + return "[ "+x+" / "+y+" "+width+" x "+height+" ]"; } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java index d3b43c864..7ca92ff53 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java @@ -31,7 +31,7 @@ package javax.media.nativewindow.util; import com.jogamp.common.type.WriteCloneable; /** Immutable Rectangle interface */ -public interface RectangleImmutable extends WriteCloneable { +public interface RectangleImmutable extends WriteCloneable, Comparable<RectangleImmutable> { int getHeight(); @@ -41,6 +41,35 @@ public interface RectangleImmutable extends WriteCloneable { int getY(); + /** Returns the union of this rectangle and the given rectangle. */ + RectangleImmutable union(final RectangleImmutable r); + /** Returns the union of this rectangleand the given coordinates. */ + RectangleImmutable union(final int rx1, final int ry1, final int rx2, final int ry2); + /** Returns the intersection of this rectangleand the given rectangle. */ + RectangleImmutable intersection(RectangleImmutable r); + /** Returns the intersection of this rectangleand the given coordinates. */ + RectangleImmutable intersection(final int rx1, final int ry1, final int rx2, final int ry2); + /** + * Returns the coverage of given rectangle w/ this this one, i.e. between <code>0.0</code> and <code>1.0</code>. + * <p> + * Coverage is computed by: + * <pre> + * isect = this.intersection(r); + * coverage = area( isect ) / area( this ) ; + * </pre> + * </p> + */ + float coverage(RectangleImmutable r); + + /** + * <p> + * Compares square of size 1st, if equal the square of position. + * </p> + * {@inheritDoc} + */ + @Override + public int compareTo(final RectangleImmutable d); + /** * Checks whether two rect objects are equal. Two instances * of <code>Rectangle</code> are equal if the four integer values @@ -49,8 +78,10 @@ public interface RectangleImmutable extends WriteCloneable { * @return <code>true</code> if the two rectangles are equal; * otherwise <code>false</code>. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index 8f21bc49b..77619731f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -4,14 +4,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -21,23 +21,24 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; -/** Immutable SurfaceSize Class, consisting of it's read only components:<br> +/** + * Immutable SurfaceSize Class, consisting of it's read only components:<br> * <ul> * <li>{@link javax.media.nativewindow.util.DimensionImmutable} size in pixels</li> * <li><code>bits per pixel</code></li> * </ul> */ -public class SurfaceSize { - DimensionImmutable resolution; - int bitsPerPixel; +public class SurfaceSize implements Comparable<SurfaceSize> { + final DimensionImmutable resolution; + final int bitsPerPixel; public SurfaceSize(DimensionImmutable resolution, int bitsPerPixel) { if(null==resolution || bitsPerPixel<=0) { @@ -55,8 +56,30 @@ public class SurfaceSize { return bitsPerPixel; } + @Override public final String toString() { - return new String("[ "+resolution+" x "+bitsPerPixel+" bpp ]"); + return "[ "+resolution+" x "+bitsPerPixel+" bpp ]"; + } + + /** + * <p> + * Compares {@link DimensionImmutable#compareTo(DimensionImmutable) resolution} 1st, if equal the bitsPerPixel. + * </p> + * {@inheritDoc} + */ + @Override + public int compareTo(final SurfaceSize ssz) { + final int rres = resolution.compareTo(ssz.getResolution()); + if( 0 != rres ) { + return rres; + } + final int xbpp = ssz.getBitsPerPixel(); + if(bitsPerPixel > xbpp) { + return 1; + } else if(bitsPerPixel < xbpp) { + return -1; + } + return 0; } /** @@ -67,6 +90,7 @@ public class SurfaceSize { * @return <code>true</code> if the two dimensions are equal; * otherwise <code>false</code>. */ + @Override public final boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof SurfaceSize) { @@ -77,6 +101,7 @@ public class SurfaceSize { return false; } + @Override public final int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + getResolution().hashCode(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java index e07fd1b57..b7197dbca 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java +++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java @@ -1,21 +1,22 @@ /* - * Copyright (c) 2003-2005 Sun Microsystems, Inc. All Rights Reserved. - * + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2010 JogAmp Community. All rights reserved. + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,17 +29,20 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package jogamp.nativewindow; +import java.security.AccessController; +import java.security.PrivilegedAction; + import com.jogamp.common.util.PropertyAccess; /** Helper routines for logging and debugging. */ @@ -47,9 +51,14 @@ public class Debug extends PropertyAccess { // Some common properties private static final boolean verbose; private static final boolean debugAll; - + static { - PropertyAccess.addTrustedPrefix("nativewindow.", Debug.class); + AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override + public Object run() { + PropertyAccess.addTrustedPrefix("nativewindow."); + return null; + } } ); verbose = isPropertyDefined("nativewindow.verbose", true); debugAll = isPropertyDefined("nativewindow.debug", true); @@ -61,27 +70,18 @@ public class Debug extends PropertyAccess { } } - public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) { - return PropertyAccess.isPropertyDefined(property, jnlpAlias, null); - } - - public static String getProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getProperty(property, jnlpAlias, null); - } - - public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getBooleanProperty(property, jnlpAlias, null); - } - - public static boolean verbose() { + /** Ensures static init block has been issues, i.e. if calling through to {@link PropertyAccess#isPropertyDefined(String, boolean)}. */ + public static final void initSingleton() {} + + public static final boolean verbose() { return verbose; } - public static boolean debugAll() { + public static final boolean debugAll() { return debugAll; } - public static boolean debug(String subcomponent) { + public static final boolean debug(String subcomponent) { return debugAll() || isPropertyDefined("nativewindow.debug." + subcomponent, true); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java index f34b740d4..8fb819251 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -36,8 +36,9 @@ package jogamp.nativewindow; import javax.media.nativewindow.*; public class DefaultGraphicsConfigurationFactoryImpl extends GraphicsConfigurationFactory { + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen) { + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) { return new DefaultGraphicsConfiguration(screen, capsChosen, capsRequested); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java index 743d371b7..cadef9bf1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java @@ -1,5 +1,5 @@ /** - * Copyright 2010 JogAmp Community. All rights reserved. + * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: @@ -25,52 +25,55 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ -package jogamp.nativewindow.jawt.x11; -import jogamp.nativewindow.jawt.*; -import jogamp.nativewindow.x11.X11Lib; -import jogamp.nativewindow.x11.X11Util; +package jogamp.nativewindow; + import javax.media.nativewindow.ToolkitLock; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; /** - * Implementing a recursive {@link javax.media.nativewindow.ToolkitLock} - * utilizing JAWT's AWT lock via {@link JAWTUtil#lockToolkit()} and {@link X11Util#XLockDisplay(long)}. - * <br> - * This strategy should only be used if AWT is using the underlying native windowing toolkit - * in a not intrinsic thread safe manner, e.g. under X11 where no XInitThreads() call - * is issued before any other X11 usage. This is the current situation for e.g. Webstart or Applets. + * Implementing a global recursive {@link javax.media.nativewindow.ToolkitLock}. + * <p> + * This is the last resort for unstable driver where multiple X11 display connections + * to the same connection name are not treated thread safe within the GL/X11 driver. + * </p> */ -public class X11JAWTToolkitLock implements ToolkitLock { - long displayHandle; - RecursiveLock lock; +public class GlobalToolkitLock implements ToolkitLock { + private static final RecursiveLock globalLock = LockFactory.createRecursiveLock(); + private static GlobalToolkitLock singleton = new GlobalToolkitLock(); - public X11JAWTToolkitLock(long displayHandle) { - this.displayHandle = displayHandle; - if(!X11Util.isNativeLockAvailable()) { - lock = LockFactory.createRecursiveLock(); - } + public static final GlobalToolkitLock getSingleton() { + return singleton; } + private GlobalToolkitLock() { } + + @Override public final void lock() { - if(TRACE_LOCK) { System.err.println("X11JAWTToolkitLock.lock() - native: "+(null==lock)); } - JAWTUtil.lockToolkit(); - if(null == lock) { - X11Lib.XLockDisplay(displayHandle); - } else { - lock.lock(); - } + globalLock.lock(); + if(TRACE_LOCK) { System.err.println("GlobalToolkitLock.lock()"); } } + @Override public final void unlock() { - if(TRACE_LOCK) { System.err.println("X11JAWTToolkitLock.unlock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XUnlockDisplay(displayHandle); - } else { - lock.unlock(); - } - JAWTUtil.unlockToolkit(); + if(TRACE_LOCK) { System.err.println("GlobalToolkitLock.unlock()"); } + globalLock.unlock(); // implicit lock validation + } + + @Override + public final void validateLocked() throws RuntimeException { + globalLock.validateLocked(); + } + + @Override + public final void dispose() { + // nop + } + + @Override + public String toString() { + return "GlobalToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+globalLock.isOwner(Thread.currentThread())+", "+globalLock.toString()+"]"; } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java index 99bc71c4a..e7eb13756 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,12 +20,12 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.nativewindow; @@ -37,18 +37,17 @@ import com.jogamp.common.os.Platform; import com.jogamp.common.util.cache.TempJarCache; public class NWJNILibLoader extends JNILibLoaderBase { - - public static boolean loadNativeWindow(final String ossuffix) { - return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { - public Boolean run() { - Platform.initSingleton(); - final String libName = "nativewindow_"+ossuffix ; - if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { - addNativeJarLibs(NWJNILibLoader.class, "jogl-all", new String[] { "nativewindow" } ); - } - return new Boolean(loadLibrary(libName, false, NWJNILibLoader.class.getClassLoader())); - } - }).booleanValue(); - } - + public static boolean loadNativeWindow(final String ossuffix) { + return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { + @Override + public Boolean run() { + Platform.initSingleton(); + final String libName = "nativewindow_"+ossuffix ; + if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { + JNILibLoaderBase.addNativeJarLibsJoglCfg(new Class<?>[] { NWJNILibLoader.class }); + } + return Boolean.valueOf(loadLibrary(libName, false, NWJNILibLoader.class.getClassLoader())); + } + }).booleanValue(); + } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index 9e18439db..22ac3bd94 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -39,7 +39,6 @@ import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; -import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.ReflectionUtil.AWTNames; @@ -47,11 +46,12 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { private static final ToolkitLock nullToolkitLock = new NullToolkitLock(); public static ToolkitLock getNullToolkitLock() { - return nullToolkitLock; + return nullToolkitLock; } - + // This subclass of NativeWindowFactory handles the case of // NativeWindows being passed in + @Override protected NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException { if (winObj instanceof NativeWindow) { // Use the NativeWindow directly @@ -70,31 +70,31 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { winObj.getClass().getName() + " is unsupported; expected " + "javax.media.nativewindow.NativeWindow or "+AWTNames.ComponentClass); } - + private Constructor<?> nativeWindowConstructor = null; private NativeWindow getAWTNativeWindow(Object winObj, AbstractGraphicsConfiguration config) { if (nativeWindowConstructor == null) { try { - String windowingType = getNativeWindowType(true); - String windowClassName = null; + final String windowingType = getNativeWindowType(true); + final String windowClassName; // We break compile-time dependencies on the AWT here to // make it easier to run this code on mobile devices - if (windowingType.equals(TYPE_WINDOWS)) { + if (TYPE_WINDOWS == windowingType) { windowClassName = "jogamp.nativewindow.jawt.windows.WindowsJAWTWindow"; - } else if (windowingType.equals(TYPE_MACOSX)) { + } else if (TYPE_MACOSX == windowingType) { windowClassName = "jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow"; - } else if (windowingType.equals(TYPE_X11)) { + } else if (TYPE_X11 == windowingType) { // Assume Linux, Solaris, etc. Should probably test for these explicitly. windowClassName = "jogamp.nativewindow.jawt.x11.X11JAWTWindow"; } else { - throw new IllegalArgumentException("OS " + Platform.getOSName() + " not yet supported"); + throw new IllegalArgumentException("Native windowing type " + windowingType + " (custom) not yet supported, platform reported native windowing type: "+getNativeWindowType(false)); } nativeWindowConstructor = ReflectionUtil.getConstructor( - windowClassName, new Class[] { Object.class, AbstractGraphicsConfiguration.class }, + windowClassName, new Class[] { Object.class, AbstractGraphicsConfiguration.class }, getClass().getClassLoader()); } catch (Exception e) { throw new IllegalArgumentException(e); diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index 1af6bf279..bda20522c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -28,18 +28,18 @@ package jogamp.nativewindow; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; /** - * Implementing a singleton global recursive {@link javax.media.nativewindow.ToolkitLock} - * without any locking. Since there is no locking it all, - * it is intrinsically recursive. + * Implementing a singleton global NOP {@link javax.media.nativewindow.ToolkitLock} + * without any locking. Since there is no locking it all, it is intrinsically recursive. */ public class NullToolkitLock implements ToolkitLock { - /** Singleton via {@link NativeWindowFactoryImpl#getNullToolkitLock()} */ protected NullToolkitLock() { } - + + @Override public final void lock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.lock()"); @@ -47,7 +47,26 @@ public class NullToolkitLock implements ToolkitLock { } } + @Override public final void unlock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.unlock()"); } } + + @Override + public final void validateLocked() throws RuntimeException { + if( NativeWindowFactory.requiresToolkitLock() ) { + throw new RuntimeException("NullToolkitLock does not lock, but locking is required."); + } + } + + @Override + public final void dispose() { + // nop + } + + @Override + public String toString() { + return "NullToolkitLock[]"; + } + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java new file mode 100644 index 000000000..fbff7128e --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -0,0 +1,325 @@ +/** + * Copyright 2010 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.SurfaceUpdatedListener; +import javax.media.nativewindow.UpstreamSurfaceHook; + + +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +public abstract class ProxySurfaceImpl implements ProxySurface { + private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); + private AbstractGraphicsConfiguration config; // control access due to delegation + private UpstreamSurfaceHook upstream; + private long surfaceHandle_old; + private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + private int implBitfield; + private boolean upstreamSurfaceHookLifecycleEnabled; + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. Owning the device implies closing it at {@link #destroyNotify()}. + */ + protected ProxySurfaceImpl(AbstractGraphicsConfiguration cfg, UpstreamSurfaceHook upstream, boolean ownsDevice) { + if(null == cfg) { + throw new IllegalArgumentException("null AbstractGraphicsConfiguration"); + } + if(null == upstream) { + throw new IllegalArgumentException("null UpstreamSurfaceHook"); + } + this.config = cfg; + this.upstream = upstream; + this.surfaceHandle_old = 0; + this.implBitfield = 0; + this.upstreamSurfaceHookLifecycleEnabled = true; + if(ownsDevice) { + addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + } + + @Override + public NativeSurface getUpstreamSurface() { return null; } + + @Override + public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + + @Override + public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook) { + if(null == hook) { + throw new IllegalArgumentException("null UpstreamSurfaceHook"); + } + upstream = hook; + } + + @Override + public final void enableUpstreamSurfaceHookLifecycle(boolean enable) { + upstreamSurfaceHookLifecycleEnabled = enable; + } + + @Override + public void createNotify() { + if(upstreamSurfaceHookLifecycleEnabled) { + upstream.create(this); + } + this.surfaceHandle_old = 0; + } + + @Override + public void destroyNotify() { + if(upstreamSurfaceHookLifecycleEnabled) { + upstream.destroy(this); + if( containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ) ) { + final AbstractGraphicsDevice aDevice = getGraphicsConfiguration().getScreen().getDevice(); + aDevice.close(); + clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + invalidateImpl(); + } + this.surfaceHandle_old = 0; + } + + /** + * Must be overridden by implementations allowing having a {@link UpstreamSurfaceHook} being passed. + * @see #destroyNotify() + */ + protected void invalidateImpl() { + throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); + } + + @Override + public final AbstractGraphicsConfiguration getGraphicsConfiguration() { + return config.getNativeGraphicsConfiguration(); + } + + @Override + public final long getDisplayHandle() { + return config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + } + + @Override + public final void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg) { + config = cfg; + } + + @Override + public final int getScreenIndex() { + return getGraphicsConfiguration().getScreen().getIndex(); + } + + @Override + public abstract long getSurfaceHandle(); + + @Override + public abstract void setSurfaceHandle(long surfaceHandle); + + @Override + public final int getWidth() { + return upstream.getWidth(this); + } + + @Override + public final int getHeight() { + return upstream.getHeight(this); + } + + @Override + public boolean surfaceSwap() { + return false; + } + + @Override + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + } + + @Override + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + } + + @Override + public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + } + + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); + } + + @Override + public int lockSurface() throws NativeWindowException, RuntimeException { + surfaceLock.lock(); + int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? + + if ( LOCK_SURFACE_NOT_READY == res ) { + try { + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + adevice.lock(); + try { + res = lockSurfaceImpl(); + if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) { + res = LOCK_SURFACE_CHANGED; + if(DEBUG) { + System.err.println("ProxySurfaceImpl: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle())); + // Thread.dumpStack(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + adevice.unlock(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + surfaceLock.unlock(); + } + } + } + return res; + } + + @Override + public final void unlockSurface() { + surfaceLock.validateLocked(); + surfaceHandle_old = getSurfaceHandle(); + + if (surfaceLock.getHoldCount() == 1) { + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + try { + unlockSurfaceImpl(); + } finally { + adevice.unlock(); + } + } + surfaceLock.unlock(); + } + + protected abstract int lockSurfaceImpl(); + + protected abstract void unlockSurfaceImpl() ; + + public final void validateSurfaceLocked() { + surfaceLock.validateLocked(); + } + + @Override + public final boolean isSurfaceLockedByOtherThread() { + return surfaceLock.isLockedByOtherThread(); + } + + @Override + public final Thread getSurfaceLockOwner() { + return surfaceLock.getOwner(); + } + + @Override + public final StringBuilder getUpstreamOptionBits(StringBuilder sink) { + if(null == sink) { + sink = new StringBuilder(); + } + sink.append("UOB[ "); + if(0 == implBitfield) { + sink.append("]"); + return sink; + } + boolean needsOr = false; + if( 0 != ( implBitfield & OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + sink.append("OWNS_SURFACE"); + needsOr = true; + } + if( 0 != ( implBitfield & OPT_PROXY_OWNS_UPSTREAM_DEVICE ) ) { + if(needsOr) { + sink.append(" | "); + } + sink.append("OWNS_DEVICE"); + needsOr = true; + } + if( 0 != ( implBitfield & OPT_UPSTREAM_WINDOW_INVISIBLE ) ) { + if(needsOr) { + sink.append(" | "); + } + sink.append("WINDOW_INVISIBLE"); + needsOr = true; + } + sink.append(" ]"); + return sink; + } + + @Override + public final int getUpstreamOptionBits() { return implBitfield; } + + @Override + public final boolean containsUpstreamOptionBits(int v) { + return v == ( implBitfield & v ) ; + } + + @Override + public final void addUpstreamOptionBits(int v) { implBitfield |= v; } + + @Override + public final void clearUpstreamOptionBits(int v) { implBitfield &= ~v; } + + @Override + public StringBuilder toString(StringBuilder sink) { + if(null == sink) { + sink = new StringBuilder(); + } + sink.append("displayHandle 0x" + Long.toHexString(getDisplayHandle())). + append("\n, surfaceHandle 0x" + Long.toHexString(getSurfaceHandle())). + append("\n, size " + getWidth() + "x" + getHeight()).append("\n, "); + getUpstreamOptionBits(sink); + sink.append("\n, "+config). + append("\n, surfaceLock "+surfaceLock+"\n, "). + append(getUpstreamSurfaceHook()). + append("\n, upstreamSurface "+(null != getUpstreamSurface())); + // append("\n, upstreamSurface "+getUpstreamSurface()); + return sink; + } + + @Override + public String toString() { + StringBuilder msg = new StringBuilder(); + msg.append(getClass().getSimpleName()).append("[ "); + toString(msg); + msg.append(" ]"); + return msg.toString(); + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java index 5166ef577..f1efb8133 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java @@ -1,5 +1,5 @@ /** - * Copyright 2010 JogAmp Community. All rights reserved. + * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: @@ -25,7 +25,8 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ -package jogamp.nativewindow.x11; + +package jogamp.nativewindow; import javax.media.nativewindow.ToolkitLock; @@ -33,38 +34,47 @@ import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; /** - * Implementing a recursive {@link javax.media.nativewindow.ToolkitLock} - * utilizing {@link X11Util#XLockDisplay(long)}. - * <br> - * This strategy should not be used in case XInitThreads() is being used, - * or a higher level toolkit lock is required, ie AWT lock. + * Implementing a resource based recursive {@link javax.media.nativewindow.ToolkitLock}. + * <p> + * A resource handle maybe used within a unique object + * and can be synchronized across threads via an instance of ResourceToolkitLock. + * </p> */ -public class X11ToolkitLock implements ToolkitLock { - long displayHandle; - RecursiveLock lock; +public class ResourceToolkitLock implements ToolkitLock { + public static final ResourceToolkitLock create() { + return new ResourceToolkitLock(); + } + + private final RecursiveLock lock; - public X11ToolkitLock(long displayHandle) { - this.displayHandle = displayHandle; - if(!X11Util.isNativeLockAvailable()) { - lock = LockFactory.createRecursiveLock(); - } + private ResourceToolkitLock() { + this.lock = LockFactory.createRecursiveLock(); } + @Override public final void lock() { - if(TRACE_LOCK) { System.err.println("X11ToolkitLock.lock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XLockDisplay(displayHandle); - } else { - lock.lock(); - } + lock.lock(); + if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.lock()"); } } + @Override public final void unlock() { - if(TRACE_LOCK) { System.err.println("X11ToolkitLock.unlock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XUnlockDisplay(displayHandle); - } else { - lock.unlock(); - } + if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.unlock()"); } + lock.unlock(); // implicit lock validation + } + + @Override + public final void validateLocked() throws RuntimeException { + lock.validateLocked(); + } + + @Override + public final void dispose() { + // nop + } + + @Override + public String toString() { + return "ResourceToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java new file mode 100644 index 000000000..7b74e1f1f --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java @@ -0,0 +1,149 @@ +/** + * Copyright 2012 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import java.util.Iterator; + +import javax.media.nativewindow.ToolkitLock; + +import com.jogamp.common.util.LongObjectHashMap; +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +/** + * Implementing a shared resource based recursive {@link javax.media.nativewindow.ToolkitLock}. + * <p> + * A resource handle maybe used within many objects + * and can be synchronized across threads via an unique instance of SharedResourceToolkitLock. + * </p> + * <p> + * Implementation holds a synchronized map from handle to reference counted {@link SharedResourceToolkitLock}. + * New elements are added via {@link #get(long)} if new + * and removed via {@link #dispose()} if no more referenced. + * </p> + */ +public class SharedResourceToolkitLock implements ToolkitLock { + private static final LongObjectHashMap handle2Lock; + static { + handle2Lock = new LongObjectHashMap(); + handle2Lock.setKeyNotFoundValue(null); + } + + /** + * @return number of unclosed EGL Displays.<br> + */ + public static int shutdown(boolean verbose) { + if(DEBUG || verbose || handle2Lock.size() > 0 ) { + System.err.println("SharedResourceToolkitLock: Shutdown (open: "+handle2Lock.size()+")"); + if(DEBUG) { + Thread.dumpStack(); + } + if( handle2Lock.size() > 0) { + dumpOpenDisplayConnections(); + } + } + return handle2Lock.size(); + } + + public static void dumpOpenDisplayConnections() { + System.err.println("SharedResourceToolkitLock: Open ResourceToolkitLock's: "+handle2Lock.size()); + int i=0; + for(Iterator<LongObjectHashMap.Entry> iter = handle2Lock.iterator(); iter.hasNext(); i++) { + final LongObjectHashMap.Entry e = iter.next(); + System.err.println("SharedResourceToolkitLock: Open["+i+"]: "+e.value); + } + } + + public static final SharedResourceToolkitLock get(long handle) { + SharedResourceToolkitLock res; + synchronized(handle2Lock) { + res = (SharedResourceToolkitLock) handle2Lock.get(handle); + if( null == res ) { + res = new SharedResourceToolkitLock(handle); + res.refCount++; + handle2Lock.put(handle, res); + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.get() * NEW *: "+res); } + } else { + res.refCount++; + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.get() * EXIST *: "+res); } + } + } + return res; + } + + private final RecursiveLock lock; + private final long handle; + private volatile int refCount; + + private SharedResourceToolkitLock(long handle) { + this.lock = LockFactory.createRecursiveLock(); + this.handle = handle; + this.refCount = 0; + } + + + @Override + public final void lock() { + lock.lock(); + if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.lock()"); } + } + + @Override + public final void unlock() { + if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.unlock()"); } + lock.unlock(); + } + + @Override + public final void validateLocked() throws RuntimeException { + lock.validateLocked(); + } + + @Override + public final void dispose() { + if(0 < refCount) { // volatile OK + synchronized(handle2Lock) { + refCount--; + if(0 == refCount) { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * REMOV *: "+this); } + handle2Lock.remove(handle); + } else { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * DOWN *: "+this); } + } + } + } else { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * NULL *: "+this); } + } + } + + @Override + public String toString() { + return "SharedResourceToolkitLock[refCount "+refCount+", handle 0x"+Long.toHexString(handle)+", obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java index 4877d5c4f..0b033955e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,7 +20,7 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -34,50 +34,58 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.SurfaceUpdatedListener; public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { - private Object surfaceUpdatedListenersLock = new Object(); - private ArrayList<SurfaceUpdatedListener> surfaceUpdatedListeners = new ArrayList<SurfaceUpdatedListener>(); + private final Object surfaceUpdatedListenersLock = new Object(); + private final ArrayList<SurfaceUpdatedListener> surfaceUpdatedListeners = new ArrayList<SurfaceUpdatedListener>(); + private volatile boolean isEmpty = true; // // Management Utils - // - public int size() { return surfaceUpdatedListeners.size(); } - public SurfaceUpdatedListener get(int i) { return surfaceUpdatedListeners.get(i); } - + // + public final int size() { return surfaceUpdatedListeners.size(); } + public final SurfaceUpdatedListener get(int i) { return surfaceUpdatedListeners.get(i); } + // // Implementation of NativeSurface SurfaceUpdatedListener methods - // - - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + // + + public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { addSurfaceUpdatedListener(-1, l); } - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) + public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { if(l == null) { return; } synchronized(surfaceUpdatedListenersLock) { - if(0>index) { - index = surfaceUpdatedListeners.size(); + if(0>index) { + index = surfaceUpdatedListeners.size(); } surfaceUpdatedListeners.add(index, l); + isEmpty = false; } } - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + public final boolean removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { if (l == null) { - return; + return false; } synchronized(surfaceUpdatedListenersLock) { - surfaceUpdatedListeners.remove(l); + final boolean res = surfaceUpdatedListeners.remove(l); + isEmpty = 0 == surfaceUpdatedListeners.size(); + return res; } } - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + @Override + public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { + if( isEmpty ) { + return; + } synchronized(surfaceUpdatedListenersLock) { for(int i = 0; i < surfaceUpdatedListeners.size(); i++ ) { - SurfaceUpdatedListener l = surfaceUpdatedListeners.get(i); + final SurfaceUpdatedListener l = surfaceUpdatedListeners.get(i); l.surfaceUpdated(updater, ns, when); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java new file mode 100644 index 000000000..47b3e63fa --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java @@ -0,0 +1,47 @@ +package jogamp.nativewindow; + +import javax.media.nativewindow.NativeWindowFactory; + +/** + * Marker interface. + * <p> + * Implementation requires to provide static methods: + * <pre> + public static void initSingleton() {} + + public static void shutdown() {} + + public static boolean requiresToolkitLock() {} + + public static boolean hasThreadingIssues() {} + * </pre> + * Above static methods are invoked by {@link NativeWindowFactory#initSingleton()}, + * or {@link NativeWindowFactory#shutdown()} via reflection. + * </p> + */ +public interface ToolkitProperties { + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // void initSingleton(); + + /** + * Cleanup resources. + * <p> + * Called by {@link NativeWindowFactory#shutdown()} + * </p> + */ + // void shutdown(); + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // boolean requiresToolkitLock(); + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // boolean hasThreadingIssues(); + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java new file mode 100644 index 000000000..f622db8cc --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java @@ -0,0 +1,100 @@ +/** + * Copyright 2010 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +/** + * Generic Surface implementation which wraps an existing window handle. + * + * @see ProxySurface + */ +public class WrappedSurface extends ProxySurfaceImpl { + protected long surfaceHandle; + + /** + * Utilizes a {@link UpstreamSurfaceHook.MutableSize} to hold the size information, + * which is being passed to the {@link ProxySurface} instance. + * + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param initialWidth + * @param initialHeight + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, int initialWidth, int initialHeight, boolean ownsDevice) { + super(cfg, new UpstreamSurfaceHookMutableSize(initialWidth, initialHeight), ownsDevice); + surfaceHandle=handle; + } + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. + */ + public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, UpstreamSurfaceHook upstream, boolean ownsDevice) { + super(cfg, upstream, ownsDevice); + surfaceHandle=handle; + } + + @Override + protected void invalidateImpl() { + surfaceHandle = 0; + } + + @Override + public final long getSurfaceHandle() { + return surfaceHandle; + } + + @Override + public final void setSurfaceHandle(long surfaceHandle) { + this.surfaceHandle=surfaceHandle; + } + + @Override + protected final int lockSurfaceImpl() { + return LOCK_SUCCESS; + } + + @Override + protected final void unlockSurfaceImpl() { + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java new file mode 100644 index 000000000..edb65eb06 --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java @@ -0,0 +1,98 @@ +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSizePos; + +public class WrappedWindow extends WrappedSurface implements NativeWindow { + private final InsetsImmutable insets = new Insets(0, 0, 0, 0); + private long windowHandle; + + /** + * Utilizes a {@link UpstreamSurfaceHookMutableSizePos} to hold the size and postion information, + * which is being passed to the {@link ProxySurface} instance. + * + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param surfaceHandle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param initialX + * @param initialY + * @param initialWidth + * @param initialHeight + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, int initialX, int initialY, int initialWidth, int initialHeight, boolean ownsDevice, long windowHandle) { + this(cfg, surfaceHandle, new UpstreamSurfaceHookMutableSizePos(initialX, initialY, initialWidth, initialHeight), ownsDevice, windowHandle); + } + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param surfaceHandle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. + */ + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, UpstreamSurfaceHookMutableSizePos upstream, boolean ownsDevice, long windowHandle) { + super(cfg, surfaceHandle, upstream, ownsDevice); + this.windowHandle = windowHandle; + } + + @Override + protected void invalidateImpl() { + super.invalidateImpl(); + windowHandle = 0; + } + + @Override + public void destroy() { + destroyNotify(); + } + + @Override + public NativeWindow getParent() { + return null; + } + + @Override + public long getWindowHandle() { + return windowHandle; + } + + @Override + public InsetsImmutable getInsets() { + return insets; + } + + @Override + public int getX() { + return ((UpstreamSurfaceHookMutableSizePos)getUpstreamSurfaceHook()).getX(); + } + + @Override + public int getY() { + return ((UpstreamSurfaceHookMutableSizePos)getUpstreamSurfaceHook()).getY(); + } + + @Override + public Point getLocationOnScreen(Point point) { + if(null!=point) { + return point; + } else { + return new Point(0, 0); + } + } + + @Override + public boolean hasFocus() { + return false; + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index d77cd75ef..069cffeb8 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -27,15 +27,27 @@ */ package jogamp.nativewindow.awt; +import java.awt.Cursor; +import java.awt.FocusTraversalPolicy; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Toolkit; import java.awt.Window; import java.awt.Component; import java.awt.Container; import java.awt.Frame; +import java.awt.image.BufferedImage; +import java.util.HashMap; + +import javax.swing.JComponent; import javax.swing.JFrame; +import javax.swing.JRootPane; import javax.swing.WindowConstants; - import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.WindowClosingProtocol; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.PixelFormatUtil; import javax.swing.MenuSelectionManager; public class AWTMisc { @@ -69,12 +81,145 @@ public class AWTMisc { } /** + * Return insets of the component w/o traversing up to parent, + * i.e. trying Window and JComponent. + * <p> + * Exception is JRootPane. + * Return it's parent's Window component's insets if available, + * otherwise return JRootPane's insets.<br> + * This is due to <i>experience</i> that <i>some</i> JRootPane's + * do not expose valid insets value. + * </p> + * @param topLevelOnly if true only returns insets of top-level components, i.e. Window and JRootPanel, + * otherwise for JComponent as well. + */ + public static Insets getInsets(Component c, boolean topLevelOnly) { + if( c instanceof Window ) { + return ((Window)c).getInsets(); + } + if( c instanceof JRootPane ) { + final Window w = getWindow(c); + if( null != w ) { + return w.getInsets(); + } + return ((JRootPane)c).getInsets(); + } + if( !topLevelOnly && c instanceof JComponent ) { + return ((JComponent)c).getInsets(); + } + return null; + } + + public static interface ComponentAction { + /** + * @param c the component to perform the action on + */ + public void run(Component c); + } + + public static int performAction(Container c, Class<?> cType, ComponentAction action) { + int count = 0; + final int cc = c.getComponentCount(); + for(int i=0; i<cc; i++) { + final Component e = c.getComponent(i); + if( e instanceof Container ) { + count += performAction((Container)e, cType, action); + } else if( cType.isInstance(e) ) { + action.run(e); + count++; + } + } + // we come at last .. + if( cType.isInstance(c) ) { + action.run(c); + count++; + } + return count; + } + + /** + * Traverse to the next forward or backward component using the + * container's FocusTraversalPolicy. + * + * @param comp the assumed current focuse component + * @param forward if true, returns the next focus component, otherwise the previous one. + * @return + */ + public static Component getNextFocus(Component comp, boolean forward) { + Container focusContainer = comp.getFocusCycleRootAncestor(); + while ( focusContainer != null && + ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) + { + comp = focusContainer; + focusContainer = comp.getFocusCycleRootAncestor(); + } + Component next = null; + if (focusContainer != null) { + final FocusTraversalPolicy policy = focusContainer.getFocusTraversalPolicy(); + next = forward ? policy.getComponentAfter(focusContainer, comp) : policy.getComponentBefore(focusContainer, comp); + if (next == null) { + next = policy.getDefaultComponent(focusContainer); + } + } + return next; + } + + /** * Issue this when your non AWT toolkit gains focus to clear AWT menu path */ public static void clearAWTMenus() { MenuSelectionManager.defaultManager().clearSelectedPath(); } + static final HashMap<Integer, Cursor> cursorMap = new HashMap<Integer, Cursor>(); + static final Cursor nulCursor; + static { + final Toolkit toolkit = Toolkit.getDefaultToolkit(); + final BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); + nulCursor = toolkit.createCustomCursor(img, new Point(0,0), "nullCursor"); + } + + public static synchronized Cursor getNullCursor() { return nulCursor; } + + public static synchronized Cursor getCursor(PixelRectangle pixelrect, Point hotSpot) { + // 31 * x == (x << 5) - x + int hash = 31 + pixelrect.hashCode(); + hash = ((hash << 5) - hash) + hotSpot.hashCode(); + final Integer key = Integer.valueOf(hash); + + Cursor cursor = cursorMap.get(key); + if( null == cursor ) { + cursor = createCursor(pixelrect, hotSpot); + cursorMap.put(key, cursor); + } + return cursor; + } + private static synchronized Cursor createCursor(PixelRectangle pixelrect, Point hotSpot) { + final int width = pixelrect.getSize().getWidth(); + final int height = pixelrect.getSize().getHeight(); + final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // PixelFormat.BGRA8888 + final PixelFormatUtil.PixelSink32 imgSink = new PixelFormatUtil.PixelSink32() { + public void store(int x, int y, int pixel) { + img.setRGB(x, y, pixel); + } + @Override + public final PixelFormat getPixelformat() { + return PixelFormat.BGRA8888; + } + @Override + public int getStride() { + return width*4; + } + @Override + public final boolean isGLOriented() { + return false; + } + }; + PixelFormatUtil.convert32(imgSink, pixelrect); + final Toolkit toolkit = Toolkit.getDefaultToolkit(); + return toolkit.createCustomCursor(img, hotSpot, pixelrect.toString()); + } + public static WindowClosingProtocol.WindowClosingMode AWT2NWClosingOperation(int awtClosingOperation) { switch (awtClosingOperation) { case WindowConstants.DISPOSE_ON_CLOSE: diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java index 2377c2be6..a5da41424 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,11 +28,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -47,20 +47,21 @@ import java.awt.Toolkit; import java.security.AccessController; import java.security.PrivilegedAction; -public class JAWTJNILibLoader extends NWJNILibLoader { +public class JAWTJNILibLoader extends NWJNILibLoader { static { AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override public Object run() { // Make sure that awt.dll is loaded before loading jawt.dll. Otherwise // a Dialog with "awt.dll not found" might pop up. // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4481947. Toolkit.getDefaultToolkit(); - + // Must pre-load JAWT on all non-Mac platforms to // ensure references from jogl_awt shared object // will succeed since JAWT shared object isn't in // default library path - if ( ! NativeWindowFactory.TYPE_MACOSX.equals( NativeWindowFactory.getNativeWindowType(false) ) ) { + if ( NativeWindowFactory.TYPE_MACOSX != NativeWindowFactory.getNativeWindowType(false) ) { try { loadLibrary("jawt", null, true, JAWTJNILibLoader.class.getClassLoader()); } catch (Throwable t) { @@ -74,9 +75,9 @@ public class JAWTJNILibLoader extends NWJNILibLoader { } }); } - + public static void initSingleton() { - // just exist to ensure static init has been run + // just exist to ensure static init has been run } - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 8098bdb1b..5a1d915ce 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,7 +29,7 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. @@ -48,25 +48,28 @@ import java.util.ArrayList; import java.util.Map; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; import jogamp.nativewindow.Debug; import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; public class JAWTUtil { public static final boolean DEBUG = Debug.debug("JAWT"); /** OSX JAWT version option to use CALayer */ public static final int JAWT_MACOSX_USE_CALAYER = 0x80000000; - + /** OSX JAWT CALayer availability on Mac OS X >= 10.6 Update 4 (recommended) */ public static final VersionNumber JAWT_MacOSXCALayerMinVersion = new VersionNumber(10,6,4); - + /** OSX JAWT CALayer required with Java >= 1.7.0 (implies OS X >= 10.7 */ - public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = new VersionNumber(1,7,0); - + public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = Platform.Version17; + // See whether we're running in headless mode private static final boolean headlessMode; private static final JAWT jawtLockObject; @@ -79,52 +82,170 @@ public class JAWTUtil { private static final Method sunToolkitAWTUnlockMethod; private static final boolean hasSunToolkitAWTLock; + private static final RecursiveLock jawtLock; private static final ToolkitLock jawtToolkitLock; private static class PrivilegedDataBlob1 { PrivilegedDataBlob1() { ok = false; - } + } Method sunToolkitAWTLockMethod; Method sunToolkitAWTUnlockMethod; boolean ok; } - + /** * Returns true if this platform's JAWT implementation supports offscreen layer. */ public static boolean isOffscreenLayerSupported() { - return Platform.OS_TYPE == Platform.OSType.MACOS && - Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; + return Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; } - + /** * Returns true if this platform's JAWT implementation requires using offscreen layer. */ public static boolean isOffscreenLayerRequired() { - return Platform.OS_TYPE == Platform.OSType.MACOS && - Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0; + return Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0; + } + + /** + * CALayer size needs to be set using the AWT component size. + * <p> + * AWT's super-calayer, i.e. the AWT's own component CALayer, + * does not layout our root-calayer in respect to this component's + * position and size, at least when resizing programmatically. + * </p> + * <p> + * As of today, this flag is enabled for all known AWT versions. + * </p> + * <p> + * Sync w/ NativeWindowProtocols.h + * </p> + */ + public static final int JAWT_OSX_CALAYER_QUIRK_SIZE = 1 << 0; + + /** + * CALayer position needs to be set to zero. + * <p> + * AWT's super-calayer, i.e. the AWT's own component CALayer, + * has a broken layout and needs it's sub-layers to be located at position 0/0. + * </p> + * <p> + * See <code>http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187</code>. + * </p> + * <p> + * Further more a re-layout seems to be required in this case, + * i.e. a programmatic forced resize +1 and it's inverted resize -1. + * </p> + * <p> + * This flag is enabled w/ AWT < 1.7.0_40. + * </p> + * <p> + * Sync w/ NativeWindowProtocols.h + * </p> + */ + public static final int JAWT_OSX_CALAYER_QUIRK_POSITION = 1 << 1; + + /** + * CALayer position needs to be derived from AWT position + * in relation to super CALayer. + * <p> + * AWT's super-calayer, i.e. the AWT top-container's CALayer, + * does not layout our root-calayer in respect to this component's + * position and size, at least when resizing programmatically. + * </p> + * <p> + * CALayer position has origin 0/0 at bottom/left, + * where AWT component has origin 0/0 at top/left. + * </p> + * <p> + * The super-calayer bounds exclude the frame's heavyweight border/insets. + * </p> + * <p> + * The super-calayer lies within the AWT top-container client space (content). + * </p> + * <p> + * Component's location in super-calayer: + * <pre> + p0 = c.locationOnScreen(); + p0 -= c.getOutterComp.getPos(); + p0 -= c.getOutterComp.getInsets(); + * </pre> + * Where 'locationOnScreen()' is: + * <pre> + p0 = 0/0; + while( null != c ) { + p0 += c.getPos(); + } + * </pre> + * </p> + * <p> + * This flags also sets {@link #JAWT_OSX_CALAYER_QUIRK_SIZE}, + * i.e. they are related. + * </p> + * <p> + * As of today, this flag is enabled for w/ AWT >= 1.7.0_40. + * </p> + * <p> + * Sync w/ NativeWindowProtocols.h + * </p> + */ + public static final int JAWT_OSX_CALAYER_QUIRK_LAYOUT = 1 << 2; + + /** + * Returns bitfield of required JAWT OSX CALayer quirks to mediate AWT impl. bugs. + * <p> + * Returns zero, if platform is not {@link Platform.OSType#MACOS} + * or not supporting CALayer, i.e. OSX < 10.6.4. + * </p> + * <p> + * Otherwise includes + * <ul> + * <li>{@link #JAWT_OSX_CALAYER_QUIRK_SIZE} (always)</li> + * <li>{@link #JAWT_OSX_CALAYER_QUIRK_POSITION} if JVM < 1.7.0_40</li> + * <li>{@link #JAWT_OSX_CALAYER_QUIRK_LAYOUT} if JVM >= 1.7.0_40</li> + * </ul> + * </p> + */ + public static int getOSXCALayerQuirks() { + int res = 0; + if( Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0 ) { + + /** Knowing impl. all expose the SIZE bug */ + res |= JAWT_OSX_CALAYER_QUIRK_SIZE; + + final int c = Platform.JAVA_VERSION_NUMBER.compareTo(Platform.Version17); + if( c < 0 || c == 0 && Platform.JAVA_VERSION_UPDATE < 40 ) { + res |= JAWT_OSX_CALAYER_QUIRK_POSITION; + } else { + res |= JAWT_OSX_CALAYER_QUIRK_LAYOUT; + } + } + return res; } - + /** * @param useOffscreenLayerIfAvailable * @return */ public static JAWT getJAWT(boolean useOffscreenLayerIfAvailable) { - final int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4; + final int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4; JAWT jawt = JAWT.create(); - + // default queries - boolean tryOffscreenLayer = false; - boolean tryOnscreenLayer = true; + boolean tryOffscreenLayer; + boolean tryOnscreen; int jawt_version_flags_offscreen = jawt_version_flags; - + if(isOffscreenLayerRequired()) { if(Platform.OS_TYPE == Platform.OSType.MACOS) { if(Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0) { jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER; tryOffscreenLayer = true; - tryOnscreenLayer = false; + tryOnscreen = false; } else { throw new RuntimeException("OSX: Invalid version of Java ("+Platform.JAVA_VERSION_NUMBER+") / OS X ("+Platform.OS_VERSION_NUMBER+")"); } @@ -135,11 +256,18 @@ public class JAWTUtil { if(Platform.OS_TYPE == Platform.OSType.MACOS) { jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER; tryOffscreenLayer = true; + tryOnscreen = true; } else { throw new InternalError("offscreen requested and supported, but n/a for: "+Platform.OS_TYPE); } + } else { + tryOffscreenLayer = false; + tryOnscreen = true; + } + if(DEBUG) { + System.err.println("JAWTUtil.getJAWT(tryOffscreenLayer "+tryOffscreenLayer+", tryOnscreen "+tryOnscreen+")"); } - + StringBuilder errsb = new StringBuilder(); if(tryOffscreenLayer) { errsb.append("Offscreen 0x").append(Integer.toHexString(jawt_version_flags_offscreen)); @@ -147,22 +275,22 @@ public class JAWTUtil { return jawt; } } - if(tryOnscreenLayer) { + if(tryOnscreen) { if(tryOffscreenLayer) { errsb.append(", "); } errsb.append("Onscreen 0x").append(Integer.toHexString(jawt_version_flags)); if( JAWT.getJAWT(jawt, jawt_version_flags) ) { return jawt; - } + } } throw new RuntimeException("Unable to initialize JAWT, trials: "+errsb.toString()); } - + public static boolean isJAWTUsingOffscreenLayer(JAWT jawt) { return 0 != ( jawt.getCachedVersion() & JAWTUtil.JAWT_MACOSX_USE_CALAYER ); } - + static { if(DEBUG) { System.err.println("JAWTUtil initialization (JAWT/JNI/..."); @@ -191,10 +319,11 @@ public class JAWTUtil { isQueueFlusherThread = m; j2dExist = ok; - PrivilegedDataBlob1 pdb1 = (PrivilegedDataBlob1) AccessController.doPrivileged(new PrivilegedAction<Object>() { + PrivilegedDataBlob1 pdb1 = (PrivilegedDataBlob1) AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override public Object run() { PrivilegedDataBlob1 d = new PrivilegedDataBlob1(); - try { + try { final Class<?> sunToolkitClass = Class.forName("sun.awt.SunToolkit"); d.sunToolkitAWTLockMethod = sunToolkitClass.getDeclaredMethod("awtLock", new Class[]{}); d.sunToolkitAWTLockMethod.setAccessible(true); @@ -209,7 +338,7 @@ public class JAWTUtil { }); sunToolkitAWTLockMethod = pdb1.sunToolkitAWTLockMethod; sunToolkitAWTUnlockMethod = pdb1.sunToolkitAWTUnlockMethod; - + boolean _hasSunToolkitAWTLock = false; if ( pdb1.ok ) { try { @@ -221,15 +350,30 @@ public class JAWTUtil { } hasSunToolkitAWTLock = _hasSunToolkitAWTLock; // hasSunToolkitAWTLock = false; + jawtLock = LockFactory.createRecursiveLock(); jawtToolkitLock = new ToolkitLock() { + @Override public final void lock() { JAWTUtil.lockToolkit(); - } + } + @Override public final void unlock() { JAWTUtil.unlockToolkit(); } - }; + @Override + public final void validateLocked() throws RuntimeException { + JAWTUtil.validateLocked(); + } + @Override + public final void dispose() { + // nop + } + @Override + public String toString() { + return "JAWTToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+jawtLock.isOwner(Thread.currentThread())+", "+jawtLock+"]"; + } + }; // trigger native AWT toolkit / properties initialization Map<?,?> desktophints = null; @@ -239,6 +383,7 @@ public class JAWTUtil { } else { final ArrayList<Map<?,?>> desktophintsBucket = new ArrayList<Map<?,?>>(1); EventQueue.invokeAndWait(new Runnable() { + @Override public void run() { Map<?,?> _desktophints = (Map<?,?>)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); if(null!=_desktophints) { @@ -260,13 +405,22 @@ public class JAWTUtil { System.err.println("JAWTUtil: Is headless " + headlessMode); int hints = ( null != desktophints ) ? desktophints.size() : 0 ; System.err.println("JAWTUtil: AWT Desktop hints " + hints); + System.err.println("JAWTUtil: OffscreenLayer Supported: "+isOffscreenLayerSupported()+" - Required "+isOffscreenLayerRequired()); } } + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ public static void initSingleton() { // just exist to ensure static init has been run } + /** + * Called by {@link NativeWindowFactory#shutdown()} + */ + public static void shutdown() { + } public static boolean hasJava2D() { return j2dExist; @@ -287,58 +441,69 @@ public class JAWTUtil { } /** - * Locks the AWT's global ReentrantLock.<br> - * + * Locks the AWT's global ReentrantLock. + * <p> * JAWT's native Lock() function calls SunToolkit.awtLock(), - * which just uses AWT's global ReentrantLock.<br> + * which just uses AWT's global ReentrantLock. + * </p> + * <p> + * AWT locking is wrapped through a recursive lock object. + * </p> */ - private static void awtLock() { - if(hasSunToolkitAWTLock) { - try { - sunToolkitAWTLockMethod.invoke(null, (Object[])null); - } catch (Exception e) { - throw new NativeWindowException("SunToolkit.awtLock failed", e); + public static void lockToolkit() throws NativeWindowException { + jawtLock.lock(); + if( 1 == jawtLock.getHoldCount() ) { + if(!headlessMode && !isJava2DQueueFlusherThread()) { + if(hasSunToolkitAWTLock) { + try { + sunToolkitAWTLockMethod.invoke(null, (Object[])null); + } catch (Exception e) { + throw new NativeWindowException("SunToolkit.awtLock failed", e); + } + } else { + jawtLockObject.Lock(); + } } - } else { - jawtLockObject.Lock(); } + if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock(): "+jawtLock); } } /** - * Unlocks the AWT's global ReentrantLock.<br> - * + * Unlocks the AWT's global ReentrantLock. + * <p> * JAWT's native Unlock() function calls SunToolkit.awtUnlock(), - * which just uses AWT's global ReentrantLock.<br> + * which just uses AWT's global ReentrantLock. + * </p> + * <p> + * AWT unlocking is wrapped through a recursive lock object. + * </p> */ - private static void awtUnlock() { - if(hasSunToolkitAWTLock) { - try { - sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); - } catch (Exception e) { - throw new NativeWindowException("SunToolkit.awtUnlock failed", e); + public static void unlockToolkit() { + jawtLock.validateLocked(); + if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock(): "+jawtLock); } + if( 1 == jawtLock.getHoldCount() ) { + if(!headlessMode && !isJava2DQueueFlusherThread()) { + if(hasSunToolkitAWTLock) { + try { + sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); + } catch (Exception e) { + throw new NativeWindowException("SunToolkit.awtUnlock failed", e); + } + } else { + jawtLockObject.Unlock(); + } } - } else { - jawtLockObject.Unlock(); - } - } - - public static void lockToolkit() throws NativeWindowException { - if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock()"); } - if(!headlessMode && !isJava2DQueueFlusherThread()) { - awtLock(); } + jawtLock.unlock(); } - public static void unlockToolkit() { - if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock()"); } - if(!headlessMode && !isJava2DQueueFlusherThread()) { - awtUnlock(); - } + public static final void validateLocked() throws RuntimeException { + jawtLock.validateLocked(); } public static ToolkitLock getJAWTToolkitLock() { return jawtToolkitLock; } - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java index 40d7b8032..4f12d1925 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -28,11 +28,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 0ca5cd297..8d46d805a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,17 +29,18 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package jogamp.nativewindow.jawt.macosx; +import java.awt.Component; import java.nio.Buffer; import java.security.AccessController; import java.security.PrivilegedAction; @@ -48,12 +49,13 @@ import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.Capabilities; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Point; -import com.jogamp.nativewindow.MutableGraphicsConfiguration; import com.jogamp.nativewindow.awt.JAWTWindow; +import jogamp.nativewindow.Debug; +import jogamp.nativewindow.awt.AWTMisc; import jogamp.nativewindow.jawt.JAWT; import jogamp.nativewindow.jawt.JAWTFactory; import jogamp.nativewindow.jawt.JAWTUtil; @@ -62,7 +64,15 @@ import jogamp.nativewindow.jawt.JAWT_DrawingSurfaceInfo; import jogamp.nativewindow.jawt.macosx.JAWT_MacOSXDrawingSurfaceInfo; import jogamp.nativewindow.macosx.OSXUtil; -public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { +public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { + /** May lead to deadlock, due to AWT pos comparison .. don't enable for Applets! */ + private static final boolean DEBUG_CALAYER_POS_CRITICAL; + + static { + Debug.initSingleton(); + DEBUG_CALAYER_POS_CRITICAL = Debug.isPropertyDefined("nativewindow.debug.JAWT.OSXCALayerPos", true /* jnlpAlias */); + } + public MacOSXJAWTWindow(Object comp, AbstractGraphicsConfiguration config) { super(comp, config); if(DEBUG) { @@ -70,70 +80,152 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { } } + @Override protected void invalidateNative() { - surfaceHandle=0; - if(isOffscreenLayerSurfaceEnabled()) { - if(0 != rootSurfaceLayerHandle) { - OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); - rootSurfaceLayerHandle = 0; - } - if(0 != drawable) { - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; + if(DEBUG) { + System.err.println("MacOSXJAWTWindow.invalidateNative(): osh-enabled "+isOffscreenLayerSurfaceEnabled()+ + ", osd-set "+offscreenSurfaceDrawableSet+ + ", osd "+toHexString(offscreenSurfaceDrawable)+ + ", osl "+toHexString(getAttachedSurfaceLayer())+ + ", rsl "+toHexString(rootSurfaceLayer)+ + ", wh "+toHexString(windowHandle)+" - "+Thread.currentThread().getName()); + } + offscreenSurfaceDrawable=0; + offscreenSurfaceDrawableSet=false; + if( isOffscreenLayerSurfaceEnabled() ) { + if(0 != windowHandle) { + OSXUtil.DestroyNSWindow(windowHandle); } + OSXUtil.RunOnMainThread(false, new Runnable() { + @Override + public void run() { + if( 0 != rootSurfaceLayer ) { + if( 0 != jawtSurfaceLayersHandle) { + UnsetJAWTRootSurfaceLayer0(jawtSurfaceLayersHandle, rootSurfaceLayer); + } + OSXUtil.DestroyCALayer(rootSurfaceLayer); + rootSurfaceLayer = 0; + } + jawtSurfaceLayersHandle = 0; + } + }); } + windowHandle=0; } + @Override protected void attachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.AddCASublayer(rootSurfaceLayerHandle, layerHandle); - } - - protected void detachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.RemoveCASublayer(rootSurfaceLayerHandle, layerHandle); - } - - public long getSurfaceHandle() { - return isOffscreenLayerSurfaceEnabled() ? surfaceHandle : super.getSurfaceHandle() ; + OSXUtil.RunOnMainThread(false, new Runnable() { + @Override + public void run() { + // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. + // Determine p0: components location on screen w/o insets. + // CALayer position will be determined in native code. + // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} + final Point p0 = new Point(); + final Component outterComp = getLocationOnScreenNonBlocking(p0, component); + final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); + final Point p1 = (Point)p0.cloneMutable(); + p1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + p1.translate(-outterInsets.left, -outterInsets.top); + } + + if( DEBUG_CALAYER_POS_CRITICAL ) { + final java.awt.Point pA0 = component.getLocationOnScreen(); + final Point pA1 = new Point(pA0.x, pA0.y); + pA1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + pA1.translate(-outterInsets.left, -outterInsets.top); + } + System.err.println("JAWTWindow.attachSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ + ", p0 "+p0+" -> "+p1+", bounds "+bounds); + } else if( DEBUG ) { + System.err.println("JAWTWindow.attachSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], p0 "+p0+" -> "+p1+", bounds "+bounds); + } + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); + } } ); } - - public void setSurfaceHandle(long surfaceHandle) { - if( !isOffscreenLayerSurfaceEnabled() ) { - throw new java.lang.UnsupportedOperationException("Not using CALAYER"); + + @Override + protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) { + final int caLayerQuirks = JAWTUtil.getOSXCALayerQuirks(); + // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. + // Determine p0: components location on screen w/o insets. + // CALayer position will be determined in native code. + // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} + final Point p0 = new Point(); + final Component outterComp = getLocationOnScreenNonBlocking(p0, component); + final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); + final Point p1 = (Point)p0.cloneMutable(); + p1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + p1.translate(-outterInsets.left, -outterInsets.top); } - if(DEBUG) { - System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); + + if( DEBUG_CALAYER_POS_CRITICAL ) { + final java.awt.Point pA0 = component.getLocationOnScreen(); + final Point pA1 = new Point(pA0.x, pA0.y); + pA1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + pA1.translate(-outterInsets.left, -outterInsets.top); + } + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", quirks "+caLayerQuirks+", visible "+visible+ + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ + ", p0 "+p0+" -> "+p1+", bounds "+bounds); + } else if( DEBUG ) { + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", quirks "+caLayerQuirks+", visible "+visible+ + ", [ins "+outterInsets+"], p0 "+p0+" -> "+p1+", bounds "+bounds); } - sscSet &= 0 != surfaceHandle; // reset ssc flag if NULL surfaceHandle, ie. back to JAWT - this.surfaceHandle = surfaceHandle; + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, visible, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); } - public void surfaceSizeChanged(int width, int height) { - sscSet = true; - sscWidth = width; - sscHeight = height; + @Override + protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { + OSXUtil.RunOnMainThread(false, new Runnable() { + @Override + public void run() { + detachNotify.run(); + OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); + } } ); } - public int getWidth() { - return sscSet ? sscWidth : super.getWidth(); + @Override + public final long getWindowHandle() { + return windowHandle; } - public int getHeight() { - return sscSet ? sscHeight: super.getHeight(); + @Override + public final long getSurfaceHandle() { + return offscreenSurfaceDrawableSet ? offscreenSurfaceDrawable : drawable /* super.getSurfaceHandle() */ ; + } + + @Override + public void setSurfaceHandle(long surfaceHandle) { + if( !isOffscreenLayerSurfaceEnabled() ) { + throw new java.lang.UnsupportedOperationException("Not using CALAYER"); + } + if(DEBUG) { + System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): "+toHexString(surfaceHandle)); + } + this.offscreenSurfaceDrawable = surfaceHandle; + this.offscreenSurfaceDrawableSet = true; } + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { // use offscreen if supported and [ applet or requested ] return JAWTUtil.getJAWT(getShallUseOffscreenLayer() || isApplet()); } + + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SURFACE_NOT_READY; - if(null == ds) { - ds = getJAWT().GetDrawingSurface(component); - if (ds == null) { - // Widget not yet realized - unlockSurfaceImpl(); - return NativeWindow.LOCK_SURFACE_NOT_READY; - } + ds = getJAWT().GetDrawingSurface(component); + if (ds == null) { + // Widget not yet realized + unlockSurfaceImpl(); + return NativeWindow.LOCK_SURFACE_NOT_READY; } int res = ds.Lock(); dsLocked = ( 0 == ( res & JAWTFactory.JAWT_LOCK_ERROR ) ) ; @@ -149,21 +241,20 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { if ((res & JAWTFactory.JAWT_LOCK_SURFACE_CHANGED) != 0) { ret = NativeWindow.LOCK_SURFACE_CHANGED; } - if(null == dsi) { - if (firstLock) { - AccessController.doPrivileged(new PrivilegedAction<Object>() { - public Object run() { - dsi = ds.GetDrawingSurfaceInfo(); - return null; - } - }); - } else { - dsi = ds.GetDrawingSurfaceInfo(); - } - if (dsi == null) { - unlockSurfaceImpl(); - return NativeWindow.LOCK_SURFACE_NOT_READY; - } + if (firstLock) { + AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override + public Object run() { + dsi = ds.GetDrawingSurfaceInfo(); + return null; + } + }); + } else { + dsi = ds.GetDrawingSurfaceInfo(); + } + if (dsi == null) { + unlockSurfaceImpl(); + return NativeWindow.LOCK_SURFACE_NOT_READY; } updateBounds(dsi.getBounds()); if (DEBUG && firstLock ) { @@ -177,58 +268,83 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { return NativeWindow.LOCK_SURFACE_NOT_READY; } drawable = macosxdsi.getCocoaViewRef(); - + if (drawable == 0) { unlockSurfaceImpl(); return NativeWindow.LOCK_SURFACE_NOT_READY; } else { + windowHandle = OSXUtil.GetNSWindow(drawable); ret = NativeWindow.LOCK_SUCCESS; } } else { /** * Only create a fake invisible NSWindow for the drawable handle * to please frameworks requiring such (eg. NEWT). - * - * The actual surface/ca-layer shall be created/attached - * by the upper framework (JOGL) since they require more information. + * + * The actual surface/ca-layer shall be created/attached + * by the upper framework (JOGL) since they require more information. */ + String errMsg = null; if(0 == drawable) { - drawable = OSXUtil.CreateNSWindow(0, 0, getBounds().getWidth(), getBounds().getHeight()); - if(0 == drawable) { - unlockSurfaceImpl(); - throw new NativeWindowException("Unable to created dummy NSWindow (layered case)"); + windowHandle = OSXUtil.CreateNSWindow(0, 0, 64, 64); + if(0 == windowHandle) { + errMsg = "Unable to create dummy NSWindow (layered case)"; + } else { + drawable = OSXUtil.GetNSView(windowHandle); + if(0 == drawable) { + errMsg = "Null NSView of NSWindow "+toHexString(windowHandle); + } } - // fix caps reflecting offscreen! - Capabilities caps = (Capabilities) getPrivateGraphicsConfiguration().getChosenCapabilities().cloneMutable(); - caps.setOnscreen(false); - getPrivateGraphicsConfiguration().setChosenCapabilities(caps); - caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); - caps.setOnscreen(false); - ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); - } - if(0 == rootSurfaceLayerHandle) { - rootSurfaceLayerHandle = OSXUtil.CreateCALayer(); - if(0 == rootSurfaceLayerHandle) { - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; - unlockSurfaceImpl(); - throw new NativeWindowException("Could not create root CALayer: "+this); + if(null == errMsg) { + // Fix caps reflecting offscreen! (no GL available here ..) + final Capabilities caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); + caps.setOnscreen(false); + setChosenCapabilities(caps); } - if(!AttachJAWTSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { - OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); - rootSurfaceLayerHandle = 0; - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; - unlockSurfaceImpl(); - throw new NativeWindowException("Could not attach JAWT surfaceLayerHandle: "+this); + } + if(null == errMsg) { + jawtSurfaceLayersHandle = GetJAWTSurfaceLayersHandle0(dsi.getBuffer()); + OSXUtil.RunOnMainThread(false, new Runnable() { + @Override + public void run() { + String errMsg = null; + if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { + rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getWidth(), bounds.getHeight()); + if(0 == rootSurfaceLayer) { + errMsg = "Could not create root CALayer"; + } else { + try { + SetJAWTRootSurfaceLayer0(jawtSurfaceLayersHandle, rootSurfaceLayer); + } catch(Exception e) { + errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)+", cause: "+e.getMessage(); + } + } + if(null != errMsg) { + if(0 != rootSurfaceLayer) { + OSXUtil.DestroyCALayer(rootSurfaceLayer); + rootSurfaceLayer = 0; + } + throw new NativeWindowException(errMsg+": "+MacOSXJAWTWindow.this); + } + } + } } ); + } + if(null != errMsg) { + if(0 != windowHandle) { + OSXUtil.DestroyNSWindow(windowHandle); + windowHandle = 0; } + drawable = 0; + unlockSurfaceImpl(); + throw new NativeWindowException(errMsg+": "+this); } ret = NativeWindow.LOCK_SUCCESS; } - + return ret; } - + + @Override protected void unlockSurfaceImpl() throws NativeWindowException { if(null!=ds) { if (null!=dsi) { @@ -247,7 +363,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { System.err.println("MaxOSXJAWTWindow: 0x"+Integer.toHexString(this.hashCode())+" - thread: "+Thread.currentThread().getName()); dumpJAWTInfo(); } - + /** * {@inheritDoc} * <p> @@ -257,32 +373,48 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { * .. * ds = getJAWT().GetDrawingSurface(component); * due to a SIGSEGV. - * + * * Hence we have some threading / sync issues with the native JAWT implementation. - * </p> + * </p> */ @Override - public Point getLocationOnScreen(Point storage) { - return getLocationOnScreenNonBlocking(storage, component); - } + public Point getLocationOnScreen(Point storage) { + if( null == storage ) { + storage = new Point(); + } + getLocationOnScreenNonBlocking(storage, component); + return storage; + } + @Override protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } - private static native boolean AttachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); - // private static native boolean DetachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); - + + private static native long GetJAWTSurfaceLayersHandle0(Buffer jawtDrawingSurfaceInfoBuffer); + + /** + * Set the given root CALayer in the JAWT surface + */ + private static native void SetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); + + /** + * Unset the given root CALayer in the JAWT surface, passing the NIO DrawingSurfaceInfo buffer + */ + private static native void UnsetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); + // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; private boolean dsLocked; private JAWT_DrawingSurfaceInfo dsi; - + private long jawtSurfaceLayersHandle; + private JAWT_MacOSXDrawingSurfaceInfo macosxdsi; - - private long rootSurfaceLayerHandle = 0; // attached to the JAWT_SurfaceLayer - - private long surfaceHandle = 0; - private int sscWidth, sscHeight; - private boolean sscSet = false; - + + private volatile long rootSurfaceLayer = 0; // attached to the JAWT_SurfaceLayer + + private long windowHandle = 0; + private long offscreenSurfaceDrawable = 0; + private boolean offscreenSurfaceDrawableSet = false; + // Workaround for instance of 4796548 private boolean firstLock = true; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java index 74dabb67f..8b9dfabfd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -65,6 +65,7 @@ public class Win32SunJDKReflection { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { try { win32GraphicsDeviceClass = Class.forName("sun.awt.Win32GraphicsDevice"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java index 5d1d43792..54bdb34f6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -60,21 +60,17 @@ public class WindowsJAWTWindow extends JAWTWindow { super(comp, config); } + @Override protected void invalidateNative() { windowHandle = 0; } - protected void attachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected void detachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } - + + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); @@ -117,6 +113,7 @@ public class WindowsJAWTWindow extends JAWTWindow { return ret; } + @Override protected void unlockSurfaceImpl() throws NativeWindowException { drawable = 0; // invalid HDC if(null!=ds) { @@ -138,6 +135,7 @@ public class WindowsJAWTWindow extends JAWTWindow { return windowHandle; } + @Override protected Point getLocationOnScreenNativeImpl(int x, int y) { return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index 736718de8..4599b9021 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,7 +29,7 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. @@ -57,19 +57,15 @@ public class X11JAWTWindow extends JAWTWindow { super(comp, config); } + @Override protected void invalidateNative() { } - protected void attachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected void detachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } - + + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); @@ -111,6 +107,7 @@ public class X11JAWTWindow extends JAWTWindow { return ret; } + @Override protected void unlockSurfaceImpl() throws NativeWindowException { if(null!=ds) { if (null!=dsi) { @@ -126,14 +123,16 @@ public class X11JAWTWindow extends JAWTWindow { x11dsi = null; } + @Override protected Point getLocationOnScreenNativeImpl(int x, int y) { - return X11Lib.GetRelativeLocation( getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); + // surface is locked and hence the device + return X11Lib.GetRelativeLocation(getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); } - + // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; private boolean dsLocked; private JAWT_DrawingSurfaceInfo dsi; private JAWT_X11DrawingSurfaceInfo x11dsi; - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java index 27e0a5e50..b2c3a931b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -29,11 +29,11 @@ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * + * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -65,6 +65,7 @@ public class X11SunJDKReflection { static { AccessController.doPrivileged(new PrivilegedAction<Object>() { + @Override public Object run() { try { x11GraphicsDeviceClass = Class.forName("sun.awt.X11GraphicsDevice"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..b71af1042 --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java @@ -0,0 +1,56 @@ +package jogamp.nativewindow.macosx; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +public class OSXDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + long nsWindow; + + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public OSXDummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + nsWindow = 0; + } + + @Override + public final void create(ProxySurface s) { + if(0 == nsWindow && 0 == s.getSurfaceHandle()) { + nsWindow = OSXUtil.CreateNSWindow(0, 0, 64, 64); + if(0 == nsWindow) { + throw new NativeWindowException("Error NS window 0"); + } + long nsView = OSXUtil.GetNSView(nsWindow); + if(0 == nsView) { + throw new NativeWindowException("Error NS view 0"); + } + s.setSurfaceHandle(nsView); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + if( 0 == nsWindow || 0 == s.getSurfaceHandle() ) { + throw new InternalError("Owns upstream surface, but no OSX view/window: "+s+", nsWindow 0x"+Long.toHexString(nsWindow)); + } + OSXUtil.DestroyNSWindow(nsWindow); + nsWindow = 0; + s.setSurfaceHandle(0); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 3ca76a84a..bac07b85a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -28,46 +28,98 @@ package jogamp.nativewindow.macosx; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; +import com.jogamp.common.util.Function; +import com.jogamp.common.util.FunctionTask; +import com.jogamp.common.util.RunnableTask; + import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; +import jogamp.nativewindow.ToolkitProperties; -public class OSXUtil { - private static boolean isInit = false; +public class OSXUtil implements ToolkitProperties { + private static boolean isInit = false; private static final boolean DEBUG = Debug.debug("OSXUtil"); - - public static synchronized void initSingleton(boolean firstX11ActionOnProcess) { + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static synchronized void initSingleton() { if(!isInit) { + if(DEBUG) { + System.out.println("OSXUtil.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("macosx")) { throw new NativeWindowException("NativeWindow MacOSX native library load error."); } - + if( !initIDs0() ) { throw new NativeWindowException("MacOSX: Could not initialized native stub"); } - - if(DEBUG) { - System.out.println("OSX.isFirstX11ActionOnProcess: "+firstX11ActionOnProcess); - } - isInit = true; } } - public static boolean requiresToolkitLock() { - return false; + /** + * Called by {@link NativeWindowFactory#shutdown()} + * @see ToolkitProperties + */ + public static void shutdown() { } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static boolean requiresToolkitLock() { return false; } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean hasThreadingIssues() { return false; } + + public static boolean isNSView(long object) { + return 0 != object ? isNSView0(object) : false; } - - public static Point GetLocationOnScreen(long windowOrView, int src_x, int src_y) { - return (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); + + public static boolean isNSWindow(long object) { + return 0 != object ? isNSWindow0(object) : false; } - - public static long CreateNSView(int x, int y, int width, int height) { - return CreateNSView0(x, y, width, height); + + /** + * In case the <code>windowOrView</code> is top-level, + * you shall set <code>topLevel</code> to true where + * insets gets into account to compute the client position as follows: + * <pre> + if(topLevel) { + // top-level position -> client window position + final Insets insets = GetInsets(windowOrView); + los.setX(los.getX() + insets.getLeftWidth()); + los.setY(los.getY() + insets.getTopHeight()); + } + * </pre> + * @param windowOrView + * @param topLevel + * @param src_x + * @param src_y + * @return the client position + */ + public static Point GetLocationOnScreen(long windowOrView, boolean topLevel, int src_x, int src_y) { + final Point los = (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); + if(topLevel) { + // top-level position -> client window position + final Insets insets = GetInsets(windowOrView); + los.set(los.getX() + insets.getLeftWidth(), los.getY() + insets.getTopHeight()); + } + return los; } - public static void DestroyNSView(long nsView) { - DestroyNSView0(nsView); + + public static Insets GetInsets(long windowOrView) { + return (Insets) GetInsets0(windowOrView); } public static long CreateNSWindow(int x, int y, int width, int height) { @@ -76,51 +128,241 @@ public class OSXUtil { public static void DestroyNSWindow(long nsWindow) { DestroyNSWindow0(nsWindow); } - - public static long CreateCALayer() { - return CreateCALayer0(); + public static long GetNSView(long nsWindow) { + return GetNSView0(nsWindow); } - public static void AddCASublayer(long rootCALayer, long subCALayer) { + public static long GetNSWindow(long nsView) { + return GetNSWindow0(nsView); + } + + /** + * Create a CALayer suitable to act as a root CALayer. + * @see #DestroyCALayer(long) + * @see #AddCASublayer(long, long) + */ + public static long CreateCALayer(final int width, final int height) { + final long l = CreateCALayer0(width, height); + if(DEBUG) { + System.err.println("OSXUtil.CreateCALayer: 0x"+Long.toHexString(l)+" - "+Thread.currentThread().getName()); + } + return l; + } + + /** + * Attach a sub CALayer to the root CALayer + * <p> + * Method will trigger a <code>display</code> + * call to the CALayer hierarchy to enforce resource creation if required, e.g. an NSOpenGLContext. + * </p> + * <p> + * Hence it is important that related resources are not locked <i>if</i> + * they will be used for creation. + * </p> + * @param caLayerQuirks TODO + * @see #CreateCALayer(int, int) + * @see #RemoveCASublayer(long, long, boolean) + */ + public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int x, final int y, final int width, final int height, final int caLayerQuirks) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - AddCASublayer0(rootCALayer, subCALayer); + if(DEBUG) { + System.err.println("OSXUtil.AttachCALayer: caLayerQuirks "+caLayerQuirks+", 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + } + AddCASublayer0(rootCALayer, subCALayer, x, y, width, height, caLayerQuirks); } - public static void RemoveCASublayer(long rootCALayer, long subCALayer) { + + /** + * Fix root and sub CALayer position to 0/0 and size + * <p> + * If the sub CALayer implements the Objective-C NativeWindow protocol NWDedicatedSize (e.g. JOGL's MyNSOpenGLLayer), + * the dedicated size is passed to the layer, which propagates it appropriately. + * </p> + * <p> + * On OSX/Java7 our root CALayer's frame position and size gets corrupted by its NSView, + * hence we have created the NWDedicatedSize protocol. + * </p> + * + * @param rootCALayer the root surface layer, maybe null. + * @param subCALayer the client surface layer, maybe null. + * @param visible TODO + * @param width the expected width + * @param height the expected height + * @param caLayerQuirks TODO + */ + public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final boolean visible, final int x, final int y, final int width, final int height, final int caLayerQuirks) { + if( 0==rootCALayer && 0==subCALayer ) { + return; + } + FixCALayerLayout0(rootCALayer, subCALayer, visible, x, y, width, height, caLayerQuirks); + } + + /** + * Detach a sub CALayer from the root CALayer. + */ + public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } + if(DEBUG) { + System.err.println("OSXUtil.DetachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + } RemoveCASublayer0(rootCALayer, subCALayer); } - public static void DestroyCALayer(long caLayer) { + + /** + * Destroy a CALayer. + * @see #CreateCALayer(int, int) + */ + public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - DestroyCALayer0(caLayer); + if(DEBUG) { + System.err.println("OSXUtil.DestroyCALayer: 0x"+Long.toHexString(caLayer)+" - "+Thread.currentThread().getName()); + } + DestroyCALayer0(caLayer); } - + + /** + * Run on OSX UI main thread. + * <p> + * 'waitUntilDone' is implemented on Java site via lock/wait on {@link RunnableTask} to not freeze OSX main thread. + * </p> + * + * @param waitUntilDone + * @param runnable + */ public static void RunOnMainThread(boolean waitUntilDone, Runnable runnable) { - if(IsMainThread0()) { + if( IsMainThread0() ) { runnable.run(); // don't leave the JVM } else { - RunOnMainThread0(waitUntilDone, runnable); + // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, + // otherwise we may freeze the OSX main thread. + Throwable throwable = null; + final Object sync = new Object(); + final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); + synchronized(sync) { + RunOnMainThread0(rt); + if( waitUntilDone ) { + try { + sync.wait(); + } catch (InterruptedException ie) { + throwable = ie; + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + } + } + } + } + + /** + * Run later on .. + * @param onMain if true, run on main-thread, otherwise on the current OSX thread. + * @param runnable + * @param delay delay to run the runnable in milliseconds + */ + public static void RunLater(boolean onMain, Runnable runnable, int delay) { + RunLater0(onMain, new RunnableTask( runnable, null, true, System.err ), delay); + } + + private static Runnable _nop = new Runnable() { @Override public void run() {}; }; + + /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an <i>NOP</i> runnable, while waiting until done. */ + public static void WaitUntilFinish() { + RunOnMainThread(true, _nop); + } + + /** + * Run on OSX UI main thread. + * <p> + * 'waitUntilDone' is implemented on Java site via lock/wait on {@link FunctionTask} to not freeze OSX main thread. + * </p> + * + * @param waitUntilDone + * @param func + */ + public static <R,A> R RunOnMainThread(boolean waitUntilDone, Function<R,A> func, A... args) { + if( IsMainThread0() ) { + return func.eval(args); // don't leave the JVM + } else { + // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, + // otherwise we may freeze the OSX main thread. + Throwable throwable = null; + final Object sync = new Object(); + final FunctionTask<R,A> rt = new FunctionTask<R,A>( func, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); + synchronized(sync) { + rt.setArgs(args); + RunOnMainThread0(rt); + if( waitUntilDone ) { + try { + sync.wait(); + } catch (InterruptedException ie) { + throwable = ie; + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + } + } + return rt.getResult(); } } - + public static boolean IsMainThread() { return IsMainThread0(); } - + + /** Returns the screen refresh rate in Hz. If unavailable, returns 60Hz. */ + public static int GetScreenRefreshRate(int scrn_idx) { + return GetScreenRefreshRate0(scrn_idx); + } + + /*** + private static boolean isAWTEDTMainThreadInit = false; + private static boolean isAWTEDTMainThread; + + public synchronized static boolean isAWTEDTMainThread() { + if(!isAWTEDTMainThreadInit) { + isAWTEDTMainThreadInit = true; + if(Platform.AWT_AVAILABLE) { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + isAWTEDTMainThread = IsMainThread(); + System.err.println("XXX: "+Thread.currentThread().getName()+" - isAWTEDTMainThread "+isAWTEDTMainThread); + } + }); + } else { + isAWTEDTMainThread = false; + } + } + return isAWTEDTMainThread; + } */ + private static native boolean initIDs0(); + private static native boolean isNSView0(long object); + private static native boolean isNSWindow0(long object); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); - private static native long CreateNSView0(int x, int y, int width, int height); - private static native void DestroyNSView0(long nsView); + private static native Object GetInsets0(long windowOrView); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); - private static native long CreateCALayer0(); - private static native void AddCASublayer0(long rootCALayer, long subCALayer); + private static native long GetNSView0(long nsWindow); + private static native long GetNSWindow0(long nsView); + private static native long CreateCALayer0(int width, int height); + private static native void AddCASublayer0(long rootCALayer, long subCALayer, int x, int y, int width, int height, int caLayerQuirks); + private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, boolean visible, int x, int y, int width, int height, int caLayerQuirks); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); - private static native void RunOnMainThread0(boolean waitUntilDone, Runnable runnable); + private static native void RunOnMainThread0(Runnable runnable); + private static native void RunLater0(boolean onMain, Runnable runnable, int delay); private static native boolean IsMainThread0(); + private static native int GetScreenRefreshRate0(int scrn_idx); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..e5de43c0a --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java @@ -0,0 +1,50 @@ +package jogamp.nativewindow.windows; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +public class GDIDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public GDIDummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + } + + @Override + public final void create(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if(0 == ms.getWindowHandle()) { + final long windowHandle = GDIUtil.CreateDummyWindow(0, 0, 64, 64); + if(0 == windowHandle) { + throw new NativeWindowException("Error windowHandle 0, werr: "+GDI.GetLastError()); + } + ms.setWindowHandle(windowHandle); + ms.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if( ms.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + if( 0 == ms.getWindowHandle() ) { + throw new InternalError("Owns upstream surface, but no GDI window: "+ms); + } + GDI.ShowWindow(ms.getWindowHandle(), GDI.SW_HIDE); + GDIUtil.DestroyDummyWindow(ms.getWindowHandle()); + ms.setWindowHandle(0); + ms.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index bc02ac5dc..3e07b2a9e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -29,8 +29,13 @@ package jogamp.nativewindow.windows; import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import jogamp.nativewindow.ProxySurfaceImpl; +import jogamp.nativewindow.windows.GDI; /** @@ -38,25 +43,64 @@ import javax.media.nativewindow.ProxySurface; * allowing the use of HDC via lockSurface()/unlockSurface() protocol. * The latter will get and release the HDC. * The size via getWidth()/getHeight() is invalid. + * + * @see ProxySurface */ -public class GDISurface extends ProxySurface { +public class GDISurface extends ProxySurfaceImpl { protected long windowHandle; protected long surfaceHandle; - public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle) { - super(cfg); - if(0 == windowHandle) { - throw new NativeWindowException("Error hwnd 0, werr: "+GDI.GetLastError()); - } + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param windowHandle the wrapped pre-existing native window handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice <code>true</code> if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise <code>false</code>. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle, UpstreamSurfaceHook upstream, boolean ownsDevice) { + super(cfg, upstream, ownsDevice); this.windowHandle=windowHandle; + this.surfaceHandle=0; + } + + @Override + protected void invalidateImpl() { + if(0 != surfaceHandle) { + throw new NativeWindowException("didn't release surface Handle: "+this); + } + windowHandle = 0; + // surfaceHandle = 0; + } + + /** + * {@inheritDoc} + * <p> + * Actually the window handle (HWND), since the surfaceHandle (HDC) is derived + * from it at {@link #lockSurface()}. + * </p> + */ + @Override + public final void setSurfaceHandle(long surfaceHandle) { + this.windowHandle = surfaceHandle; } - protected final void invalidateImpl() { - windowHandle=0; - surfaceHandle=0; + /** + * Sets the window handle (HWND). + */ + public final void setWindowHandle(long windowHandle) { + this.windowHandle = windowHandle; } + public final long getWindowHandle() { + return windowHandle; + } + + @Override final protected int lockSurfaceImpl() { + if (0 == windowHandle) { + throw new NativeWindowException("null window handle: "+this); + } if (0 != surfaceHandle) { throw new InternalError("surface not released"); } @@ -70,27 +114,18 @@ public class GDISurface extends ProxySurface { return (0 != surfaceHandle) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY; } + @Override final protected void unlockSurfaceImpl() { - if (0 == surfaceHandle) { - throw new InternalError("surface not acquired: "+this+", thread: "+Thread.currentThread().getName()); - } - if(0 == GDI.ReleaseDC(windowHandle, surfaceHandle)) { - throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); + if (0 != surfaceHandle) { + if(0 == GDI.ReleaseDC(windowHandle, surfaceHandle)) { + throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); + } + surfaceHandle=0; } - surfaceHandle=0; } + @Override final public long getSurfaceHandle() { return surfaceHandle; } - - final public String toString() { - return "GDISurface[config "+getPrivateGraphicsConfiguration()+ - ", displayHandle 0x"+Long.toHexString(getDisplayHandle())+ - ", windowHandle 0x"+Long.toHexString(windowHandle)+ - ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+ - ", size "+getWidth()+"x"+getHeight()+ - ", surfaceLock "+surfaceLock+"]"; - } - } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index d17a1898c..720ff9bdb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -29,75 +29,119 @@ package jogamp.nativewindow.windows; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.Debug; -import jogamp.nativewindow.x11.X11Util; +import jogamp.nativewindow.ToolkitProperties; -public class GDIUtil { +public class GDIUtil implements ToolkitProperties { private static final boolean DEBUG = Debug.debug("GDIUtil"); - + private static final String dummyWindowClassNameBase = "_dummyWindow_clazz" ; private static RegisteredClassFactory dummyWindowClassFactory; private static boolean isInit = false; - - public static synchronized void initSingleton(boolean firstX11ActionOnProcess) { + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static synchronized void initSingleton() { if(!isInit) { - synchronized(X11Util.class) { + synchronized(GDIUtil.class) { if(!isInit) { - isInit = true; + if(DEBUG) { + System.out.println("GDI.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("win32")) { throw new NativeWindowException("NativeWindow Windows native library load error."); } - if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0(), + true /* useDummyDispatchThread */, + 0 /* iconSmallHandle */, 0 /* iconBigHandle */); if(DEBUG) { - System.out.println("GDI.isFirstX11ActionOnProcess: "+firstX11ActionOnProcess); + System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); } - - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + isInit = true; } } } } - + + /** + * Called by {@link NativeWindowFactory#shutdown()} + * @see ToolkitProperties + */ + public static void shutdown() { + } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ public static boolean requiresToolkitLock() { return false; } - + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean hasThreadingIssues() { return false; } + private static RegisteredClass dummyWindowClass = null; private static Object dummyWindowSync = new Object(); - + public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { dummyWindowClass = dummyWindowClassFactory.getSharedClass(); - return CreateDummyWindow0(dummyWindowClass.getHandle(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); + if(DEBUG) { + System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); + System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); + } + return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getHDispThreadContext(), dummyWindowClass.getName(), x, y, width, height); } } - + public static boolean DestroyDummyWindow(long hwnd) { boolean res; synchronized(dummyWindowSync) { if( null == dummyWindowClass ) { throw new InternalError("GDI Error ("+dummyWindowClassFactory.getSharedRefCount()+"): SharedClass is null"); } - res = GDI.DestroyWindow(hwnd); + res = DestroyWindow0(dummyWindowClass.getHDispThreadContext(), hwnd); dummyWindowClassFactory.releaseSharedClass(); } return res; } - + public static Point GetRelativeLocation(long src_win, long dest_win, int src_x, int src_y) { return (Point) GetRelativeLocation0(src_win, dest_win, src_x, src_y); } - - public static native boolean CreateWindowClass(long hInstance, String clazzName, long wndProc); - public static native boolean DestroyWindowClass(long hInstance, String className); - + + public static boolean IsUndecorated(long win) { + return IsUndecorated0(win); + } + + public static boolean IsChild(long win) { + return IsChild0(win); + } + + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + + /** Creates WNDCLASSEX instance */ + static native boolean CreateWindowClass0(long hInstance, String clazzName, long wndProc, long iconSmallHandle, long iconBigHandle); + /** Destroys WNDCLASSEX instance */ + static native boolean DestroyWindowClass0(long hInstance, String className, long dispThreadCtx); + static native long CreateDummyDispatchThread0(); + private static native boolean initIDs0(); - private static native long getDummyWndProc0(); + private static native long getDummyWndProc0(); private static native Object GetRelativeLocation0(long src_win, long dest_win, int src_x, int src_y); - - static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); + private static native boolean IsChild0(long win); + private static native boolean IsUndecorated0(long win); + + private static native long CreateDummyWindow0(long hInstance, String className, long dispThreadCtx, String windowName, int x, int y, int width, int height); + private static native boolean DestroyWindow0(long dispThreadCtx, long win); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java index afb3daf7c..1f6cb7c05 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java @@ -29,17 +29,25 @@ package jogamp.nativewindow.windows; public class RegisteredClass { - long hInstance; - String className; + private final long hInstance; + private final String className; + private final long hDDTCtx; - RegisteredClass(long hInst, String name) { - hInstance = hInst; - className = name; + RegisteredClass(long hInst, String name, long hDispatchThreadCtx) { + this.hInstance = hInst; + this.className = name; + this.hDDTCtx = hDispatchThreadCtx; } - public final long getHandle() { return hInstance; } + /** Application handle, same as {@link RegisteredClassFactory#getHInstance()}. */ + public final long getHInstance() { return hInstance; } + + /** Unique Window Class Name */ public final String getName() { return className; } + /** Unique associated dispatch thread context for this Window Class, or 0 for none. */ + public final long getHDispThreadContext() { return hDDTCtx; } + @Override - public final String toString() { return "RegisteredClass[handle 0x"+Long.toHexString(hInstance)+", "+className+"]"; } + public final String toString() { return "RegisteredClass[handle 0x"+Long.toHexString(hInstance)+", "+className+", dtx 0x"+Long.toHexString(hDDTCtx)+"]"; } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index 00bedfc8e..c4b4d145c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -29,46 +29,76 @@ package jogamp.nativewindow.windows; import jogamp.nativewindow.Debug; + import java.util.ArrayList; + import javax.media.nativewindow.NativeWindowException; public class RegisteredClassFactory { - static final boolean DEBUG = Debug.debug("RegisteredClass"); - private static ArrayList<RegisteredClassFactory> registeredFactories = new ArrayList<RegisteredClassFactory>(); - - private String classBaseName; - private long wndProc; + private static final boolean DEBUG = Debug.debug("RegisteredClass"); + private static final ArrayList<RegisteredClassFactory> registeredFactories; + private static final long hInstance; + + static { + hInstance = GDI.GetApplicationHandle(); + if( 0 == hInstance ) { + throw new NativeWindowException("Error: Null ModuleHandle for Application"); + } + registeredFactories = new ArrayList<RegisteredClassFactory>(); + } + + private final String classBaseName; + private final long wndProc; + private final boolean useDummyDispatchThread; + private final long iconSmallHandle, iconBigHandle; private RegisteredClass sharedClass = null; private int classIter = 0; private int sharedRefCount = 0; private final Object sync = new Object(); + private String toHexString(long l) { return "0x"+Long.toHexString(l); } + + @Override + public final String toString() { return "RegisteredClassFactory[moduleHandle "+toHexString(hInstance)+", "+classBaseName+ + ", wndProc "+toHexString(wndProc)+", useDDT "+useDummyDispatchThread+", shared[refCount "+sharedRefCount+", class "+sharedClass+"]]"; } + /** - * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. + * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. */ public static void shutdownSharedClasses() { synchronized(registeredFactories) { + if( DEBUG ) { + System.err.println("RegisteredClassFactory.shutdownSharedClasses: "+registeredFactories.size()); + } for(int j=0; j<registeredFactories.size(); j++) { final RegisteredClassFactory rcf = registeredFactories.get(j); synchronized(rcf.sync) { if(null != rcf.sharedClass) { - GDIUtil.DestroyWindowClass(rcf.sharedClass.getHandle(), rcf.sharedClass.getName()); + GDIUtil.DestroyWindowClass0(rcf.sharedClass.getHInstance(), rcf.sharedClass.getName(), rcf.sharedClass.getHDispThreadContext()); rcf.sharedClass = null; rcf.sharedRefCount = 0; - rcf.classIter = 0; + rcf.classIter = 0; if(DEBUG) { - System.err.println("RegisteredClassFactory #"+j+"/"+registeredFactories.size()+" shutdownSharedClasses : "+rcf.sharedClass); + System.err.println("RegisteredClassFactory #"+j+"/"+registeredFactories.size()+": shutdownSharedClasses : "+rcf.sharedClass); } + } else if(DEBUG) { + System.err.println("RegisteredClassFactory #"+j+"/"+registeredFactories.size()+": null"); } } } } } - public RegisteredClassFactory(String classBaseName, long wndProc) { + /** Application handle. */ + public static long getHInstance() { return hInstance; } + + public RegisteredClassFactory(String classBaseName, long wndProc, boolean useDummyDispatchThread, long iconSmallHandle, long iconBigHandle) { this.classBaseName = classBaseName; this.wndProc = wndProc; + this.useDummyDispatchThread = useDummyDispatchThread; + this.iconSmallHandle = iconSmallHandle; + this.iconBigHandle = iconBigHandle; synchronized(registeredFactories) { registeredFactories.add(this); } @@ -80,23 +110,28 @@ public class RegisteredClassFactory { if( null != sharedClass ) { throw new InternalError("Error ("+sharedRefCount+"): SharedClass not null: "+sharedClass); } - long hInstance = GDI.GetApplicationHandle(); - if( 0 == hInstance ) { - throw new NativeWindowException("Error: Null ModuleHandle for Application"); - } String clazzName = null; boolean registered = false; - final int classIterMark = classIter - 1; + final int classIterMark = classIter - 1; while ( !registered && classIterMark != classIter ) { // Retry with next clazz name, this could happen if more than one JVM is running clazzName = classBaseName + classIter; classIter++; - registered = GDIUtil.CreateWindowClass(hInstance, clazzName, wndProc); + registered = GDIUtil.CreateWindowClass0(hInstance, clazzName, wndProc, iconSmallHandle, iconBigHandle); } if( !registered ) { throw new NativeWindowException("Error: Could not create WindowClass: "+clazzName); } - sharedClass = new RegisteredClass(hInstance, clazzName); + final long hDispatchThread; + if( useDummyDispatchThread ) { + hDispatchThread = GDIUtil.CreateDummyDispatchThread0(); + if( 0 == hDispatchThread ) { + throw new NativeWindowException("Error: Could not create DDT "+clazzName); + } + } else { + hDispatchThread = 0; + } + sharedClass = new RegisteredClass(hInstance, clazzName, hDispatchThread); if(DEBUG) { System.err.println("RegisteredClassFactory getSharedClass ("+sharedRefCount+") initialized: "+sharedClass); } @@ -121,7 +156,7 @@ public class RegisteredClassFactory { throw new InternalError("Error ("+sharedRefCount+"): SharedClass is null"); } if( 0 == sharedRefCount ) { - GDIUtil.DestroyWindowClass(sharedClass.getHandle(), sharedClass.getName()); + GDIUtil.DestroyWindowClass0(sharedClass.getHInstance(), sharedClass.getName(), sharedClass.getHDispThreadContext()); if(DEBUG) { System.err.println("RegisteredClassFactory releaseSharedClass ("+sharedRefCount+") released: "+sharedClass); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java index 0e69c738f..4f8cff8c5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java @@ -40,10 +40,12 @@ public class X11Capabilities extends Capabilities { this.xVisualInfo = xVisualInfo; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -68,9 +70,10 @@ public class X11Capabilities extends Capabilities { return VisualIDHolder.VID_UNDEFINED; default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..2c8ef642c --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java @@ -0,0 +1,70 @@ +package jogamp.nativewindow.x11; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import jogamp.nativewindow.x11.X11Lib; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; +import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; + +public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public X11DummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + } + + @Override + public final void create(ProxySurface s) { + final X11GraphicsConfiguration cfg = (X11GraphicsConfiguration) s.getGraphicsConfiguration(); + final X11GraphicsScreen screen = (X11GraphicsScreen) cfg.getScreen(); + final X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); + device.lock(); + try { + if(0 == device.getHandle()) { + device.open(); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( 0 == s.getSurfaceHandle() ) { + final long windowHandle = X11Lib.CreateWindow(0, device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64, false, false); + if(0 == windowHandle) { + throw new NativeWindowException("Creating dummy window failed w/ "+cfg); + } + s.setSurfaceHandle(windowHandle); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } finally { + device.unlock(); + } + } + + @Override + public final void destroy(ProxySurface s) { + if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + final X11GraphicsDevice device = (X11GraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); + if( 0 == s.getSurfaceHandle() ) { + throw new InternalError("Owns upstream surface, but no X11 window: "+s); + } + device.lock(); + try { + X11Lib.DestroyWindow(device.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(0); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } finally { + device.unlock(); + } + } + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java index 070f87216..6258632cd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -39,33 +39,40 @@ import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactory { public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, new X11GraphicsConfigurationFactory()); - } + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class, new X11GraphicsConfigurationFactory()); + } private X11GraphicsConfigurationFactory() { } - + + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen) + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { if(!(screen instanceof X11GraphicsScreen)) { throw new NativeWindowException("Only valid X11GraphicsScreen are allowed"); } - final X11Capabilities x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, capsChosen)); - AbstractGraphicsConfiguration res = new X11GraphicsConfiguration((X11GraphicsScreen)screen, x11CapsChosen, capsRequested, x11CapsChosen.getXVisualInfo()); + final X11Capabilities x11CapsChosen; + if(VisualIDHolder.VID_UNDEFINED == nativeVisualID) { + x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, capsChosen)); + } else { + x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, nativeVisualID)); + } + final AbstractGraphicsConfiguration res = new X11GraphicsConfiguration((X11GraphicsScreen)screen, x11CapsChosen, capsRequested, x11CapsChosen.getXVisualInfo()); if(DEBUG) { - System.err.println("X11GraphicsConfigurationFactory.chooseGraphicsConfigurationImpl("+screen+","+capsChosen+"): "+res); + System.err.println("X11GraphicsConfigurationFactory.chooseGraphicsConfigurationImpl(visualID 0x"+Integer.toHexString(nativeVisualID)+", "+screen+","+capsChosen+"): "+res); } return res; } - public static XVisualInfo getXVisualInfo(AbstractGraphicsScreen screen, long visualID) + public static XVisualInfo getXVisualInfo(AbstractGraphicsScreen screen, int visualID) { XVisualInfo xvi_temp = XVisualInfo.create(); xvi_temp.setVisualid(visualID); @@ -103,7 +110,7 @@ public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactor XVisualInfo best=null; int rdepth = capabilities.getRedBits() + capabilities.getGreenBits() + capabilities.getBlueBits() + capabilities.getAlphaBits(); for (int i = 0; vinfos!=null && i < num[0]; i++) { - if ( best == null || + if ( best == null || best.getDepth() < vinfos[i].getDepth() ) { best = vinfos[i]; diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index c42bcf816..02e43791c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -34,6 +34,7 @@ package jogamp.nativewindow.x11; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -42,22 +43,27 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; +import jogamp.nativewindow.ToolkitProperties; import com.jogamp.common.util.LongObjectHashMap; +import com.jogamp.common.util.PropertyAccess; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; /** * Contains a thread safe X11 utility to retrieve display connections. */ -public class X11Util { - /** +public class X11Util implements ToolkitProperties { + public static final boolean DEBUG = Debug.debug("X11Util"); + + /** * See Bug 515 - https://jogamp.org/bugzilla/show_bug.cgi?id=515 - * <p> + * <p> * It is observed that ATI X11 drivers, eg. - * <ul> + * <ul> * <li>fglrx 8.78.6,</li> * <li>fglrx 11.08/8.881 and </li> * <li>fglrx 11.11/8.911</li> - * </ul> + * </ul> * are quite sensitive to multiple Display connections. * </p> * <p> @@ -67,113 +73,206 @@ public class X11Util { * </p> * <p> * You may test this, ie just reverse the destroy order below. - * See also native test: jogl/test/native/displayMultiple02.c + * See also native test: jogl/test-native/displayMultiple02.c + * </p> + * <p> + * Workaround is to not close them at all if driver vendor is ATI + * during operation. * </p> * <p> - * Workaround is to not close them at all if driver vendor is ATI. + * With ATI X11 drivers all connections must be closed at JVM shutdown, + * otherwise a SIGSEGV (after JVM safepoint) will be caused. * </p> */ - public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = true; + public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); - /** Value is <code>true</code>, best 'stable' results if always using XInitThreads(). */ - public static final boolean XINITTHREADS_ALWAYS_ENABLED = true; - - /** Value is <code>true</code>, best 'stable' results if not using XLockDisplay/XUnlockDisplay at all. */ - public static final boolean HAS_XLOCKDISPLAY_BUG = true; - - private static final boolean DEBUG = Debug.debug("X11Util"); - private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.getBooleanProperty("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); + /** See {@link #ATI_HAS_XCLOSEDISPLAY_BUG}. */ + public static final boolean HAS_XCLOSEDISPLAY_BUG = Debug.isPropertyDefined("nativewindow.debug.X11Util.HAS_XCLOSEDISPLAY_BUG", true); + /** + * See Bug 623 - https://jogamp.org/bugzilla/show_bug.cgi?id=623 + */ + public static final boolean ATI_HAS_MULTITHREADING_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_MULTITHREADING_BUG", true); + + public static final boolean XSYNC_ENABLED = Debug.isPropertyDefined("nativewindow.debug.X11Util.XSync", true); + public static final boolean XERROR_STACKDUMP = DEBUG || Debug.isPropertyDefined("nativewindow.debug.X11Util.XErrorStackDump", true); + private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.isPropertyDefined("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); private static String nullDisplayName = null; - private static boolean isX11LockAvailable = false; - private static boolean requiresX11Lock = true; private static volatile boolean isInit = false; - private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues + private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues, or GLRendererQuirks.DontCloseX11Display + private static boolean hasThreadingIssues = false; // ATI/AMD X11 driver issues - private static int setX11ErrorHandlerRecCount = 0; - private static Object setX11ErrorHandlerLock = new Object(); + private static final Object setX11ErrorHandlerLock = new Object(); + private static final String X11_EXTENSION_ATIFGLRXDRI = "ATIFGLRXDRI"; + private static final String X11_EXTENSION_ATIFGLEXTENSION = "ATIFGLEXTENSION"; - - @SuppressWarnings("unused") - public static void initSingleton(final boolean firstX11ActionOnProcess) { + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static void initSingleton() { if(!isInit) { synchronized(X11Util.class) { if(!isInit) { isInit = true; + if(DEBUG) { + System.out.println("X11Util.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("x11")) { throw new NativeWindowException("NativeWindow X11 native library load error."); } - - final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess; - final boolean isXInitThreadsOK = initialize0( XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess ); - isX11LockAvailable = isXInitThreadsOK && !HAS_XLOCKDISPLAY_BUG ; - - final long dpy = X11Lib.XOpenDisplay(null); - try { - nullDisplayName = X11Lib.XDisplayString(dpy); - } finally { - X11Lib.XCloseDisplay(dpy); + + final boolean isInitOK = initialize0( XERROR_STACKDUMP ); + + final boolean hasX11_EXTENSION_ATIFGLRXDRI, hasX11_EXTENSION_ATIFGLEXTENSION; + final long dpy = X11Lib.XOpenDisplay(PropertyAccess.getProperty("nativewindow.x11.display.default", true)); + if(0 != dpy) { + if(XSYNC_ENABLED) { + X11Lib.XSynchronize(dpy, true); + } + try { + nullDisplayName = X11Lib.XDisplayString(dpy); + hasX11_EXTENSION_ATIFGLRXDRI = X11Lib.QueryExtension(dpy, X11_EXTENSION_ATIFGLRXDRI); + hasX11_EXTENSION_ATIFGLEXTENSION = X11Lib.QueryExtension(dpy, X11_EXTENSION_ATIFGLEXTENSION); + } finally { + X11Lib.XCloseDisplay(dpy); + } + } else { + nullDisplayName = "nil"; + hasX11_EXTENSION_ATIFGLRXDRI = false; + hasX11_EXTENSION_ATIFGLEXTENSION = false; + } + final boolean isATIFGLRX = hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ; + hasThreadingIssues = ATI_HAS_MULTITHREADING_BUG && isATIFGLRX; + if ( !markAllDisplaysUnclosable ) { + markAllDisplaysUnclosable = ( ATI_HAS_XCLOSEDISPLAY_BUG && isATIFGLRX ) || HAS_XCLOSEDISPLAY_BUG; } - + if(DEBUG) { - System.err.println("X11Util firstX11ActionOnProcess: "+firstX11ActionOnProcess+ - ", requiresX11Lock "+requiresX11Lock+ - ", XInitThreads [called "+callXInitThreads+", OK "+isXInitThreadsOK+"]"+ - ", isX11LockAvailable "+isX11LockAvailable+ - ", X11 Display(NULL) <"+nullDisplayName+">"); + System.err.println("X11Util.initSingleton(): OK "+isInitOK+"]"+ + ",\n\t X11 Display(NULL) <"+nullDisplayName+">"+ + ",\n\t XSynchronize Enabled: " + XSYNC_ENABLED+ + ",\n\t X11_EXTENSION_ATIFGLRXDRI " + hasX11_EXTENSION_ATIFGLRXDRI+ + ",\n\t X11_EXTENSION_ATIFGLEXTENSION " + hasX11_EXTENSION_ATIFGLEXTENSION+ + ",\n\t requiresToolkitLock "+requiresToolkitLock()+ + ",\n\t hasThreadingIssues "+hasThreadingIssues()+ + ",\n\t markAllDisplaysUnclosable "+getMarkAllDisplaysUnclosable() + ); // Thread.dumpStack(); } } } } } - - public static synchronized boolean isNativeLockAvailable() { - return isX11LockAvailable; + + // not exactly thread safe, but good enough for our purpose, + // which is to tag a NamedDisplay uncloseable after creation. + private static Object globalLock = new Object(); + private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name + private static List<NamedDisplay> openDisplayList = new ArrayList<NamedDisplay>(); // open, no close attempt + private static List<NamedDisplay> reusableDisplayList = new ArrayList<NamedDisplay>(); // close attempt, marked uncloseable, for reuse + private static List<NamedDisplay> pendingDisplayList = new ArrayList<NamedDisplay>(); // all open (close attempt or reusable) in creation order + private static final HashMap<String /* displayName */, Boolean> displayXineramaEnabledMap = new HashMap<String, Boolean>(); + + /** + * Cleanup resources. + * <p> + * Called by {@link NativeWindowFactory#shutdown()} + * </p> + * @see ToolkitProperties + */ + public static void shutdown() { + if(isInit) { + synchronized(X11Util.class) { + if(isInit) { + final boolean isJVMShuttingDown = NativeWindowFactory.isJVMShuttingDown() ; + if( DEBUG || + ( ( openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) && + ( reusableDisplayList.size() != pendingDisplayList.size() || !markAllDisplaysUnclosable ) + ) ) { + System.err.println("X11Util.Display: Shutdown (JVM shutdown: "+isJVMShuttingDown+ + ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ + ", reusable (open, marked uncloseable): "+reusableDisplayList.size()+ + ", pending (open in creation order): "+pendingDisplayList.size()+ + ")"); + if(DEBUG) { + Thread.dumpStack(); + } + if( openDisplayList.size() > 0) { + X11Util.dumpOpenDisplayConnections(); + } + if(DEBUG) { + if( reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) { + X11Util.dumpPendingDisplayConnections(); + } + } + } + + // Only at JVM shutdown time, since AWT impl. seems to + // dislike closing of X11 Display's (w/ ATI driver). + if( isJVMShuttingDown ) { + synchronized(globalLock) { + isInit = false; + closePendingDisplayConnections(); + openDisplayList.clear(); + reusableDisplayList.clear(); + pendingDisplayList.clear(); + openDisplayMap.clear(); + displayXineramaEnabledMap.clear(); + shutdown0(); + } + } + } + } + } } - public static synchronized boolean requiresToolkitLock() { - return requiresX11Lock; + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean requiresToolkitLock() { + return true; // JAWT locking: yes, instead of native X11 locking w use a recursive lock per display connection. + } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean hasThreadingIssues() { + return hasThreadingIssues; // JOGL impl. may utilize special locking "somewhere" } public static void setX11ErrorHandler(boolean onoff, boolean quiet) { synchronized(setX11ErrorHandlerLock) { - if(onoff) { - if(0==setX11ErrorHandlerRecCount) { - setX11ErrorHandler0(true, quiet); - } - setX11ErrorHandlerRecCount++; - } else { - if(0 >= setX11ErrorHandlerRecCount) { - throw new InternalError(); - } - setX11ErrorHandlerRecCount--; - if(0==setX11ErrorHandlerRecCount) { - setX11ErrorHandler0(false, false); - } - } + setX11ErrorHandler0(onoff, quiet); } } public static String getNullDisplayName() { return nullDisplayName; } - + + public static void markAllDisplaysUnclosable() { + synchronized(globalLock) { + markAllDisplaysUnclosable = true; + for(int i=0; i<openDisplayList.size(); i++) { + openDisplayList.get(i).setUncloseable(true); + } + for(int i=0; i<reusableDisplayList.size(); i++) { + reusableDisplayList.get(i).setUncloseable(true); + } + for(int i=0; i<pendingDisplayList.size(); i++) { + pendingDisplayList.get(i).setUncloseable(true); + } + } + } + public static boolean getMarkAllDisplaysUnclosable() { return markAllDisplaysUnclosable; } - public static void setMarkAllDisplaysUnclosable(boolean v) { - markAllDisplaysUnclosable = v; - } - - private X11Util() {} - // not exactly thread safe, but good enough for our purpose, - // which is to tag a NamedDisplay uncloseable after creation. - private static Object globalLock = new Object(); - private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name - private static List<NamedDisplay> openDisplayList = new ArrayList<NamedDisplay>(); - private static List<NamedDisplay> pendingDisplayList = new ArrayList<NamedDisplay>(); + private X11Util() {} public static class NamedDisplay { final String name; @@ -201,22 +300,23 @@ public class X11Util { } } + @Override public final int hashCode() { return hash32; } - + + @Override public final boolean equals(Object obj) { if(this == obj) { return true; } if(obj instanceof NamedDisplay) { - NamedDisplay n = (NamedDisplay) obj; - return handle == n.handle; + return handle == ((NamedDisplay) obj).handle; } return false; } - + public final void addRef() { refCount++; } public final void removeRef() { refCount--; } - + public final String getName() { return name; } public final long getHandle() { return handle; } public final int getRefCount() { return refCount; } @@ -226,71 +326,32 @@ public class X11Util { public final Throwable getCreationStack() { return creationStack; } @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override public String toString() { return "NamedX11Display["+name+", 0x"+Long.toHexString(handle)+", refCount "+refCount+", unCloseable "+unCloseable+"]"; } } - /** - * Cleanup resources. - * If <code>realXCloseOpenAndPendingDisplays</code> is <code>false</code>, - * keep alive all references (open display connection) for restart on same ClassLoader. - * - * @return number of unclosed X11 Displays.<br> - * @param realXCloseOpenAndPendingDisplays if true, {@link #closePendingDisplayConnections()} is called. - */ - public static int shutdown(boolean realXCloseOpenAndPendingDisplays, boolean verbose) { - int num=0; - if(DEBUG||verbose||pendingDisplayList.size() > 0) { - System.err.println("X11Util.Display: Shutdown (close open / pending Displays: "+realXCloseOpenAndPendingDisplays+ - ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ - ", pending (not closed, marked uncloseable): "+pendingDisplayList.size()+")"); - if(DEBUG) { - Thread.dumpStack(); - } - if( openDisplayList.size() > 0) { - X11Util.dumpOpenDisplayConnections(); - } - if( pendingDisplayList.size() > 0 ) { - X11Util.dumpPendingDisplayConnections(); - } - } - - synchronized(globalLock) { - if(realXCloseOpenAndPendingDisplays) { - closePendingDisplayConnections(); - openDisplayList.clear(); - pendingDisplayList.clear(); - openDisplayMap.clear(); - shutdown0(); - } - } - return num; - } - /** - * Closing pending Display connections in reverse order. + * Closing pending Display connections in original creation order, if {@link #getMarkAllDisplaysUnclosable()} is true. * * @return number of closed Display connections */ - public static int closePendingDisplayConnections() { + private static int closePendingDisplayConnections() { int num=0; synchronized(globalLock) { - if(DEBUG) { - System.err.println("X11Util: Closing Pending X11 Display Connections: "+pendingDisplayList.size()); - } - for(int i=pendingDisplayList.size()-1; i>=0; i--) { - NamedDisplay ndpy = (NamedDisplay) pendingDisplayList.get(i); + if( getMarkAllDisplaysUnclosable() ) { + for(int i=0; i<pendingDisplayList.size(); i++) { + final NamedDisplay ndpy = (NamedDisplay) pendingDisplayList.get(i); + if(DEBUG) { + final boolean closeAttempted = !openDisplayMap.containsKey(ndpy.getHandle()); + System.err.println("X11Util.closePendingDisplayConnections(): Closing ["+i+"]: "+ndpy+" - closeAttempted "+closeAttempted); + } + XCloseDisplay(ndpy.getHandle()); + num++; + } if(DEBUG) { - System.err.println("X11Util.closePendingDisplayConnections(): Closing ["+i+"]: "+ndpy); + System.err.println("X11Util.closePendingDisplayConnections(): Closed "+num+" pending display connections"); } - XCloseDisplay(ndpy.getHandle()); - num++; } } return num; @@ -301,7 +362,7 @@ public class X11Util { return openDisplayList.size(); } } - + public static void dumpOpenDisplayConnections() { synchronized(globalLock) { System.err.println("X11Util: Open X11 Display Connections: "+openDisplayList.size()); @@ -317,7 +378,13 @@ public class X11Util { } } } - + + public static int getReusableDisplayConnectionNumber() { + synchronized(globalLock) { + return reusableDisplayList.size(); + } + } + public static int getPendingDisplayConnectionNumber() { synchronized(globalLock) { return pendingDisplayList.size(); @@ -326,7 +393,18 @@ public class X11Util { public static void dumpPendingDisplayConnections() { synchronized(globalLock) { - System.err.println("X11Util: Pending X11 Display Connections: "+pendingDisplayList.size()); + System.err.println("X11Util: Reusable X11 Display Connections: "+reusableDisplayList.size()); + for(int i=0; i<reusableDisplayList.size(); i++) { + NamedDisplay ndpy = (NamedDisplay) reusableDisplayList.get(i); + System.err.println("X11Util: Reusable["+i+"]: "+ndpy); + if(null!=ndpy) { + Throwable t = ndpy.getCreationStack(); + if(null!=t) { + t.printStackTrace(); + } + } + } + System.err.println("X11Util: Pending X11 Display Connections (creation order): "+pendingDisplayList.size()); for(int i=0; i<pendingDisplayList.size(); i++) { NamedDisplay ndpy = (NamedDisplay) pendingDisplayList.get(i); System.err.println("X11Util: Pending["+i+"]: "+ndpy); @@ -358,11 +436,11 @@ public class X11Util { NamedDisplay namedDpy = null; name = validateDisplayName(name); boolean reused = false; - - synchronized(globalLock) { - for(int i=0; i<pendingDisplayList.size(); i++) { - if(pendingDisplayList.get(i).getName().equals(name)) { - namedDpy = pendingDisplayList.remove(i); + + synchronized(globalLock) { + for(int i=0; i<reusableDisplayList.size(); i++) { + if(reusableDisplayList.get(i).getName().equals(name)) { + namedDpy = reusableDisplayList.remove(i); dpy = namedDpy.getHandle(); reused = true; break; @@ -376,6 +454,7 @@ public class X11Util { // if you like to debug and synchronize X11 commands .. // setSynchronizeDisplay(dpy, true); namedDpy = new NamedDisplay(name, dpy); + pendingDisplayList.add(namedDpy); } namedDpy.addRef(); openDisplayMap.put(dpy, namedDpy); @@ -392,10 +471,8 @@ public class X11Util { } public static void closeDisplay(long handle) { - NamedDisplay namedDpy; - synchronized(globalLock) { - namedDpy = (NamedDisplay) openDisplayMap.remove(handle); + final NamedDisplay namedDpy = (NamedDisplay) openDisplayMap.remove(handle); if(null==namedDpy) { X11Util.dumpPendingDisplayConnections(); throw new RuntimeException("X11Util.Display: Display(0x"+Long.toHexString(handle)+") with given handle is not mapped. Thread "+Thread.currentThread().getName()); @@ -404,20 +481,26 @@ public class X11Util { X11Util.dumpPendingDisplayConnections(); throw new RuntimeException("X11Util.Display: Display(0x"+Long.toHexString(handle)+") Mapping error: "+namedDpy+". Thread "+Thread.currentThread().getName()); } - + namedDpy.removeRef(); if(!openDisplayList.remove(namedDpy)) { throw new RuntimeException("Internal: "+namedDpy); } - - if(!namedDpy.isUncloseable()) { + + if( markAllDisplaysUnclosable ) { + // if set-mark 'slipped' this one .. just to be safe! + namedDpy.setUncloseable(true); + } + if( !namedDpy.isUncloseable() ) { XCloseDisplay(namedDpy.getHandle()); + pendingDisplayList.remove(namedDpy); } else { // for reuse - pendingDisplayList.add(namedDpy); + X11Lib.XSync(namedDpy.getHandle(), true); // flush output buffer and discard all events + reusableDisplayList.add(namedDpy); } - + if(DEBUG) { System.err.println("X11Util.Display: Closed (real: "+(!namedDpy.isUncloseable())+") "+namedDpy+". Thread "+Thread.currentThread().getName()); - } + } } } @@ -427,7 +510,7 @@ public class X11Util { } } - /** + /** * @return If name is null, it returns the previous queried NULL display name, * otherwise the name. */ public static String validateDisplayName(String name) { @@ -448,50 +531,60 @@ public class X11Util { *******************************/ public static long XOpenDisplay(String arg0) { - NativeWindowFactory.getDefaultToolkitLock().lock(); - try { - long handle = X11Lib.XOpenDisplay(arg0); - if(TRACE_DISPLAY_LIFECYCLE) { - System.err.println(Thread.currentThread()+" - X11Util.XOpenDisplay("+arg0+") 0x"+Long.toHexString(handle)); - // Thread.dumpStack(); - } - return handle; - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); + long handle = X11Lib.XOpenDisplay(arg0); + if(XSYNC_ENABLED && 0 != handle) { + X11Lib.XSynchronize(handle, true); + } + if(TRACE_DISPLAY_LIFECYCLE) { + System.err.println(Thread.currentThread()+" - X11Util.XOpenDisplay("+arg0+") 0x"+Long.toHexString(handle)); + // Thread.dumpStack(); } + return handle; } public static int XCloseDisplay(long display) { - NativeWindowFactory.getDefaultToolkitLock().lock(); + if(TRACE_DISPLAY_LIFECYCLE) { + System.err.println(Thread.currentThread()+" - X11Util.XCloseDisplay() 0x"+Long.toHexString(display)); + // Thread.dumpStack(); + } + int res = -1; try { - if(TRACE_DISPLAY_LIFECYCLE) { - System.err.println(Thread.currentThread()+" - X11Util.XCloseDisplay() 0x"+Long.toHexString(display)); - // Thread.dumpStack(); - } - int res = -1; - X11Util.setX11ErrorHandler(true, DEBUG ? false : true); - try { - res = X11Lib.XCloseDisplay(display); - } catch (Exception ex) { - System.err.println("X11Util: Catched Exception:"); - ex.printStackTrace(); - } finally { - X11Util.setX11ErrorHandler(false, false); - } - return res; - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); + res = X11Lib.XCloseDisplay(display); + } catch (Exception ex) { + System.err.println("X11Util: Catched Exception:"); + ex.printStackTrace(); } + return res; } static volatile boolean XineramaFetched = false; static long XineramaLibHandle = 0; static long XineramaQueryFunc = 0; - - public static boolean XineramaIsEnabled(long display) { - if(0==display) { - throw new IllegalArgumentException("Display NULL"); + + public static boolean XineramaIsEnabled(X11GraphicsDevice device) { + if(null == device) { + throw new IllegalArgumentException("X11 Display device is NULL"); + } + device.lock(); + try { + return XineramaIsEnabled(device.getHandle()); + } finally { + device.unlock(); + } + } + + public static boolean XineramaIsEnabled(long displayHandle) { + if( 0 == displayHandle ) { + throw new IllegalArgumentException("X11 Display handle is NULL"); } + final String displayName = X11Lib.XDisplayString(displayHandle); + synchronized(displayXineramaEnabledMap) { + final Boolean b = displayXineramaEnabledMap.get(displayName); + if(null != b) { + return b.booleanValue(); + } + } + final boolean res; if(!XineramaFetched) { // volatile: ok synchronized(X11Util.class) { if( !XineramaFetched ) { @@ -504,19 +597,27 @@ public class X11Util { } } if(0!=XineramaQueryFunc) { - final boolean res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, display); + res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, displayHandle); + } else { if(DEBUG) { - System.err.println("XineramaIsEnabled: "+res); + System.err.println("XineramaIsEnabled: Couldn't bind to Xinerama - lib 0x"+Long.toHexString(XineramaLibHandle)+ + "query 0x"+Long.toHexString(XineramaQueryFunc)); } - return res; - } else if(DEBUG) { - System.err.println("XineramaIsEnabled: Couldn't bind to Xinerama - lib 0x"+Long.toHexString(XineramaLibHandle)+ - "query 0x"+Long.toHexString(XineramaQueryFunc)); + res = false; } - return false; + synchronized(displayXineramaEnabledMap) { + if(DEBUG) { + System.err.println("XineramaIsEnabled Cache: Display "+displayName+" (0x"+Long.toHexString(displayHandle)+") -> "+res); + } + displayXineramaEnabledMap.put(displayName, Boolean.valueOf(res)); + } + return res; } - - private static native boolean initialize0(boolean firstUIActionOnProcess); + + private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + + private static native boolean initialize0(boolean debug); private static native void shutdown0(); private static native void setX11ErrorHandler0(boolean onoff, boolean quiet); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java index b6bf63d44..062040232 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A @@ -59,16 +59,17 @@ import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFactory { - + public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new X11AWTGraphicsConfigurationFactory()); - } + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, CapabilitiesImmutable.class, new X11AWTGraphicsConfigurationFactory()); + } private X11AWTGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (absScreen != null && !(absScreen instanceof AWTGraphicsScreen)) { throw new IllegalArgumentException("This GraphicsConfigurationFactory accepts only AWTGraphicsScreen objects"); @@ -77,21 +78,21 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac absScreen = AWTGraphicsScreen.createDefault(); } - return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, (AWTGraphicsScreen)absScreen); + return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, (AWTGraphicsScreen)absScreen, nativeVisualID); } - + public static AWTGraphicsConfiguration chooseGraphicsConfigurationStatic( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AWTGraphicsScreen awtScreen) { + CapabilitiesChooser chooser, AWTGraphicsScreen awtScreen, int nativeVisualID) { if(DEBUG) { System.err.println("X11AWTGraphicsConfigurationFactory: got "+awtScreen); } - + final GraphicsDevice device = ((AWTGraphicsDevice)awtScreen.getDevice()).getGraphicsDevice(); final long displayHandleAWT = X11SunJDKReflection.graphicsDeviceGetDisplay(device); final long displayHandle; - boolean owner = false; + final boolean owner; if(0==displayHandleAWT) { displayHandle = X11Util.openDisplay(null); owner = true; @@ -101,8 +102,8 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac } else { /** * Using the AWT display handle works fine with NVidia. - * However we experienced different results w/ AMD drivers, - * some work, but some behave erratic. + * However we experienced different results w/ AMD drivers, + * some work, but some behave erratic. * I.e. hangs in XQueryExtension(..) via X11GraphicsScreen. */ final String displayName = X11Lib.XDisplayString(displayHandleAWT); @@ -112,17 +113,16 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac System.err.println(getThreadName()+" - X11AWTGraphicsConfigurationFactory: AWT dpy "+displayName+" / "+toHexString(displayHandleAWT)+", create X11 display "+toHexString(displayHandle)); } } - final ToolkitLock lock = owner ? - NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_AWT) : // own non-shared X11 display connection, no X11 lock - NativeWindowFactory.createDefaultToolkitLock(NativeWindowFactory.TYPE_X11, NativeWindowFactory.TYPE_AWT, displayHandle); - final X11GraphicsDevice x11Device = new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, lock, owner); + // Global JAWT lock required - No X11 resource locking due to private display connection + final ToolkitLock lock = NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_AWT); + final X11GraphicsDevice x11Device = new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, lock, owner); final X11GraphicsScreen x11Screen = new X11GraphicsScreen(x11Device, awtScreen.getIndex()); if(DEBUG) { System.err.println("X11AWTGraphicsConfigurationFactory: made "+x11Screen); } - - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(x11Device); - AbstractGraphicsConfiguration aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen); + + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(x11Device, capsChosen); + AbstractGraphicsConfiguration aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen, nativeVisualID); if (aConfig == null) { throw new NativeWindowException("Unable to choose a GraphicsConfiguration (1): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen); } @@ -130,7 +130,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac System.err.println("X11AWTGraphicsConfigurationFactory: chosen config: "+aConfig); // Thread.dumpStack(); } - + // // Match the X11/GL Visual with AWT: // - choose a config AWT agnostic and then @@ -138,7 +138,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac // // The resulting GraphicsConfiguration has to be 'forced' on the AWT native peer, // ie. returned by GLCanvas's getGraphicsConfiguration() befor call by super.addNotify(). - // + // final GraphicsConfiguration[] configs = device.getConfigurations(); int visualID = aConfig.getVisualID(VIDType.NATIVE); if(VisualIDHolder.VID_UNDEFINED != visualID) { @@ -160,7 +160,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac // try again using an AWT Colormodel compatible configuration GraphicsConfiguration gc = device.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsChosen, gc); - aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen); + aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen, nativeVisualID); if (aConfig == null) { throw new NativeWindowException("Unable to choose a GraphicsConfiguration (2): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen); } diff --git a/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c b/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c index 2a6651007..5c77b6d46 100644 --- a/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c +++ b/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c @@ -43,7 +43,7 @@ #define PLATFORM_DSI_SIZE sizeof(JAWT_Win32DrawingSurfaceInfo) #elif defined(linux) || defined(__sun) || defined(__FreeBSD__) || defined(_HPUX) #define PLATFORM_DSI_SIZE sizeof(JAWT_X11DrawingSurfaceInfo) -#elif defined(macosx) +#elif defined(__APPLE__) #define PLATFORM_DSI_SIZE sizeof(JAWT_MacOSXDrawingSurfaceInfo) #else ERROR: port JAWT_DrawingSurfaceInfo.c to your platform diff --git a/src/nativewindow/native/NativewindowCommon.c b/src/nativewindow/native/NativewindowCommon.c index b866646a6..e65f87272 100644 --- a/src/nativewindow/native/NativewindowCommon.c +++ b/src/nativewindow/native/NativewindowCommon.c @@ -1,20 +1,57 @@ #include "NativewindowCommon.h" +#include <string.h> +#include <sys/time.h> + +// #define STDERR_TO_FILE 1 static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; +static JavaVM *_jvmHandle = NULL; +static int _jvmVersion = 0; + +int NativewindowCommon_init(JNIEnv *env) { + if(NULL==_jvmHandle) { + if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) { + NativewindowCommon_FatalError(env, "Nativewindow: Can't fetch JavaVM handle"); + } else { + _jvmVersion = (*env)->GetVersion(env); + } + jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); + if(NULL==c) { + NativewindowCommon_FatalError(env, "Nativewindow: Can't find %s", ClazzNameRuntimeException); + } + runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==runtimeExceptionClz) { + NativewindowCommon_FatalError(env, "Nativewindow: Can't use %s", ClazzNameRuntimeException); + } + #ifdef STDERR_TO_FILE + FILE * old_stderr = stderr; + FILE * new_stderr = freopen("jogamp_stderr.log", "w", stderr); + fprintf(stderr, "STDERR_TO_FILE: %p -> %p\n", old_stderr, new_stderr); + #endif + return 1; + } + return 0; +} + void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...) { char buffer[512]; va_list ap; - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); - fprintf(stderr, "%s\n", buffer); - (*env)->FatalError(env, buffer); + fprintf(stderr, "%s\n", buffer); + if(NULL != env) { + (*env)->FatalError(env, buffer); + } + } } void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) @@ -22,63 +59,100 @@ void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, . char buffer[512]; va_list ap; - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if(NULL==_jvmHandle) { + NativewindowCommon_FatalError(env, "Nativewindow: NULL JVM handle, call NativewindowCommon_init 1st\n"); + return; + } - (*env)->ThrowNew(env, runtimeExceptionClz, buffer); -} + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); -int NativewindowCommon_init(JNIEnv *env) { - if(NULL==runtimeExceptionClz) { - jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); - if(NULL==c) { - NativewindowCommon_FatalError(env, "Nativewindow: can't find %s", ClazzNameRuntimeException); + if(NULL != env) { + (*env)->ThrowNew(env, runtimeExceptionClz, buffer); } - runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==runtimeExceptionClz) { - NativewindowCommon_FatalError(env, "Nativewindow: can't use %s", ClazzNameRuntimeException); + } +} + +const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText) { + if(NULL != jniEnv && NULL != clazz && NULL != jGetStrID) { + jstring jstr = (jstring) (*jniEnv)->CallStaticObjectMethod(jniEnv, clazz, jGetStrID); + if(NULL != jstr) { + const char * str = (*jniEnv)->GetStringUTFChars(jniEnv, jstr, NULL); + if( NULL != str) { + strncpy(dest, str, destSize-1); + dest[destSize-1] = 0; // EOS + (*jniEnv)->ReleaseStringUTFChars(jniEnv, jstr, str); + return dest; + } } - return 1; } - return 0; + strncpy(dest, altText, destSize-1); + dest[destSize-1] = 0; // EOS + return dest; } jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; - strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); - if (strChars != NULL) { - (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + if( NULL != env && 0 != str ) { + strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); + if (strChars != NULL) { + (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + } } return strChars; } -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * shallBeDetached) { +JNIEnv* NativewindowCommon_GetJNIEnv (int asDaemon, int * shallBeDetached) { JNIEnv* curEnv = NULL; JNIEnv* newEnv = NULL; int envRes; + if(NULL==_jvmHandle) { + fprintf(stderr, "Nativewindow GetJNIEnv: NULL JVM handle, call NativewindowCommon_init 1st\n"); + return NULL; + } + // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; + envRes = (*_jvmHandle)->GetEnv(_jvmHandle, (void **) &curEnv, _jvmVersion) ; if( JNI_EDETACHED == envRes ) { // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes); + if( asDaemon ) { + envRes = (*_jvmHandle)->AttachCurrentThreadAsDaemon(_jvmHandle, (void**) &newEnv, NULL); + } else { + envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL); + } + if( JNI_OK != envRes ) { + fprintf(stderr, "Nativewindow GetJNIEnv: Can't attach thread: %d\n", envRes); return NULL; } curEnv = newEnv; } else if( JNI_OK != envRes ) { // oops .. - fprintf(stderr, "can't GetEnv: %d\n", envRes); + fprintf(stderr, "Nativewindow GetJNIEnv: Can't GetEnv: %d\n", envRes); return NULL; } if (curEnv==NULL) { - fprintf(stderr, "env is NULL\n"); + fprintf(stderr, "Nativewindow GetJNIEnv: env is NULL\n"); return NULL; } *shallBeDetached = NULL != newEnv; return curEnv; } +void NativewindowCommon_ReleaseJNIEnv (int shallBeDetached) { + if(NULL == _jvmHandle) { + fprintf(stderr, "Nativewindow ReleaseJNIEnv: No JavaVM handle registered, call NativewindowCommon_init(..) 1st"); + } else if(shallBeDetached) { + (*_jvmHandle)->DetachCurrentThread(_jvmHandle); + } +} + +int64_t NativewindowCommon_CurrentTimeMillis() { + struct timeval tv; + gettimeofday(&tv,NULL); + return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; +} + diff --git a/src/nativewindow/native/NativewindowCommon.h b/src/nativewindow/native/NativewindowCommon.h index 41c4bd0eb..f19552e33 100644 --- a/src/nativewindow/native/NativewindowCommon.h +++ b/src/nativewindow/native/NativewindowCommon.h @@ -1,17 +1,80 @@ +/** + * Copyright 2011 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ #ifndef NATIVEWINDOW_COMMON_H #define NATIVEWINDOW_COMMON_H 1 #include <jni.h> #include <stdlib.h> +#include <gluegen_stdint.h> int NativewindowCommon_init(JNIEnv *env); +const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText); jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str); void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...); void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * shallBeDetached); +/** + * + * 1) Init static jvmHandle, jvmVersion and clazz references + * from an early initialization call w/ valid 'JNIEnv * env' + + NativewindowCommon_init(env); + + * + * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv + * + + int asDaemon = 0; + int shallBeDetached = 0; + JNIEnv* env = NewtCommon_GetJNIEnv(asDaemon, &shallBeDetached); + if(NULL==env) { + DBG_PRINT("drawRect: null JNIEnv\n"); + return; + } + + * + * 3) Use JNIEnv .. + * + .. your JNIEnv code here .. + + * + * 4) Detach thread from JVM if required, i.e. not attached as daemon! + * Not recommended for recurring _daemon_ threads (performance) + * + NewtCommon_ReleaseJNIEnv(shallBeDetached); + */ +JNIEnv* NativewindowCommon_GetJNIEnv (int asDaemon, int * shallBeDetached); + +void NativewindowCommon_ReleaseJNIEnv (int shallBeDetached); + +int64_t NativewindowCommon_CurrentTimeMillis(); #endif diff --git a/src/nativewindow/native/macosx/NativeWindowProtocols.h b/src/nativewindow/native/macosx/NativeWindowProtocols.h new file mode 100644 index 000000000..98e864f8b --- /dev/null +++ b/src/nativewindow/native/macosx/NativeWindowProtocols.h @@ -0,0 +1,58 @@ +/** + * Copyright 2013 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +#ifndef NATIVEWINDOWPROTOCOLS_H +#define NATIVEWINDOWPROTOCOLS_H 1 + +/** + * CALayer size needs to be set using the AWT component size. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_SIZE ( 1 << 0 ) + +/** + * CALayer position needs to be set to zero. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_POSITION ( 1 << 1 ) + +/** + * CALayer position needs to be derived from AWT position. + * in relation to super CALayer. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_LAYOUT ( 1 << 2 ) + +#import <Foundation/NSGeometry.h> + +@protocol NWDedicatedFrame +- (void)setDedicatedFrame:(CGRect)dFrame quirks:(int)quirks; +@end + +#endif /* NATIVEWINDOWPROTOCOLS_H_ */ + diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 38ffde98b..d95d1cdbf 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -32,13 +32,14 @@ #include <stdarg.h> #include <unistd.h> #include <AppKit/AppKit.h> +#import <QuartzCore/QuartzCore.h> +#import "NativeWindowProtocols.h" #include "NativewindowCommon.h" #include "jogamp_nativewindow_macosx_OSXUtil.h" #include "jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow.h" #include <jawt_md.h> -#import <JavaNativeFoundation.h> // #define VERBOSE 1 // @@ -49,20 +50,34 @@ #define DBG_PRINT(...) #endif +// #define VERBOSE2 1 +// +#ifdef VERBOSE2 + #define DBG_PRINT2(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) +#else + #define DBG_PRINT2(...) +#endif + +// #define DBG_LIFECYCLE 1 + static const char * const ClazzNameRunnable = "java/lang/Runnable"; static jmethodID runnableRunID = NULL; -static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzAnyCstrName = "<init>"; + +static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; -static int _initialized=0; +static const char * const ClazzNameInsets = "javax/media/nativewindow/util/Insets"; +static const char * const ClazzNameInsetsCstrSignature = "(IIII)V"; +static jclass insetsClz = NULL; +static jmethodID insetsCstr = NULL; JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { - if(0==_initialized) { + if( NativewindowCommon_init(env) ) { jclass c; c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { @@ -79,6 +94,21 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } + c = (*env)->FindClass(env, ClazzNameInsets); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't find %s", ClazzNameInsets); + } + insetsClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==insetsClz) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't use %s", ClazzNameInsets); + } + insetsCstr = (*env)->GetMethodID(env, insetsClz, ClazzAnyCstrName, ClazzNameInsetsCstrSignature); + if(NULL==insetsCstr) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't fetch %s.%s %s", + ClazzNameInsets, ClazzAnyCstrName, ClazzNameInsetsCstrSignature); + } + c = (*env)->FindClass(env, ClazzNameRunnable); if(NULL==c) { NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't find %s", ClazzNameRunnable); @@ -87,11 +117,26 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { if(NULL==runnableRunID) { NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't fetch %s.run()V", ClazzNameRunnable); } - _initialized=1; } return JNI_TRUE; } +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_macosx_OSXUtil_isNSView0(JNIEnv *env, jclass _unused, jlong object) { + NSObject *nsObj = (NSObject*) (intptr_t) object; + jboolean u = [nsObj isKindOfClass:[NSView class]]; + DBG_PRINT( "isNSView(obj: %p): %s -> %d\n", nsObj, [[nsObj description] UTF8String], u); + return u; +} + +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_macosx_OSXUtil_isNSWindow0(JNIEnv *env, jclass _unused, jlong object) { + NSObject *nsObj = (NSObject*) (intptr_t) object; + jboolean u = [nsObj isKindOfClass:[NSWindow class]]; + DBG_PRINT( "isNSWindow(obj: %p): %s -> %d\n", nsObj, [[nsObj description] UTF8String], u); + return u; +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: getLocationOnScreen0 @@ -150,33 +195,45 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetLocationOnS /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: CreateNSView0 - * Signature: (IIIIZ)J + * Method: getInsets0 + * Signature: (J)Ljavax/media/nativewindow/util/Insets; */ -JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSView0 - (JNIEnv *env, jclass unused, jint x, jint y, jint width, jint height) +JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetInsets0 + (JNIEnv *env, jclass unused, jlong winOrView) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSRect rect = NSMakeRect(x, y, width, height); - NSView * view = [[NSView alloc] initWithFrame: rect] ; - [view setCanDrawConcurrently: YES]; - [pool release]; - return (jlong) (intptr_t) view; -} + NSObject *nsObj = (NSObject*) (intptr_t) winOrView; + NSWindow* win = NULL; + NSView* view = NULL; + jint il,ir,it,ib; + + if( [nsObj isKindOfClass:[NSWindow class]] ) { + win = (NSWindow*) nsObj; + view = [win contentView]; + } else if( nsObj != NULL && [nsObj isKindOfClass:[NSView class]] ) { + view = (NSView*) nsObj; + win = [view window]; + } else { + NativewindowCommon_throwNewRuntimeException(env, "neither win not view %p\n", nsObj); + } + + NSRect frameRect = [win frame]; + NSRect contentRect = [win contentRectForFrameRect: frameRect]; + + // note: this is a simplistic implementation which doesn't take + // into account DPI and scaling factor + CGFloat l = contentRect.origin.x - frameRect.origin.x; + il = (jint)l; // l + ir = (jint)(frameRect.size.width - (contentRect.size.width + l)); // r + it = (jint)(frameRect.size.height - contentRect.size.height); // t + ib = (jint)(contentRect.origin.y - frameRect.origin.y); // b + + jobject res = (*env)->NewObject(env, insetsClz, insetsCstr, il, ir, it, ib); -/* - * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: DestroyNSView0 - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyNSView0 - (JNIEnv *env, jclass unused, jlong nsView) -{ - NSView* view = (NSView*) (intptr_t) nsView; - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - [view release]; [pool release]; + + return res; } /* @@ -197,6 +254,14 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 defer: YES]; [myWindow setReleasedWhenClosed: YES]; // default [myWindow setPreservesContentDuringLiveResize: YES]; + // Remove animations +NS_DURING + if ( [myWindow respondsToSelector:@selector(setAnimationBehavior:)] ) { + // Available >= 10.7 - Removes default animations + [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; + } +NS_HANDLER +NS_ENDHANDLER // invisible .. [myWindow setOpaque: NO]; @@ -224,31 +289,290 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyNSWindow0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetNSView0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSView0 + (JNIEnv *env, jclass unused, jlong window) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSWindow* win = (NSWindow*) ((intptr_t) window); + + jlong res = (jlong) ((intptr_t) [win contentView]); + + DBG_PRINT( "GetNSView(window: %p): %p\n", win, (void*) (intptr_t) res); + + [pool release]; + return res; +} + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetNSWindow0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 + (JNIEnv *env, jclass unused, jlong view) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSView* v = (NSView*) ((intptr_t) view); + + jlong res = (jlong) ((intptr_t) [v window]); + + DBG_PRINT( "GetNSWindow(view: %p): %p\n", v, (void*) (intptr_t) res); + + [pool release]; + return res; +} + +/** + * Track lifecycle via DBG_PRINT messages, if VERBOSE is enabled! + */ +@interface MyCALayer: CALayer +{ +@private + BOOL fixedFrameSet; + CGRect fixedFrame; + float visibleOpacity; + BOOL visibleOpacityZeroed; +} +- (id)init; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +- (void)dealloc; +#endif +- (id<CAAction>)actionForKey:(NSString *)key ; +- (void)layoutSublayers; +- (void)setFrame:(CGRect) frame; +- (void)fixCALayerLayout: (CALayer*) subLayer visible:(BOOL)visible x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force; + +@end + +@implementation MyCALayer + +- (id)init +{ + DBG_PRINT("MyCALayer::init.0\n"); + MyCALayer * o = [super init]; + o->fixedFrameSet = 0; + o->fixedFrame = CGRectMake(0, 0, 0, 0); + o->visibleOpacity = 1.0; + o->visibleOpacityZeroed = 0; + DBG_PRINT("MyCALayer::init.X: new %p\n", o); + return o; +} + +#ifdef DBG_LIFECYCLE + +- (id)retain +{ + DBG_PRINT("MyCALayer::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::retain: %@",[NSThread callStackSymbols]); + id o = [super retain]; + DBG_PRINT("MyCALayer::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} + +- (oneway void)release +{ + DBG_PRINT("MyCALayer::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::release: %@",[NSThread callStackSymbols]); + [super release]; + // DBG_PRINT("MyCALayer::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); +} + +- (void)dealloc +{ + DBG_PRINT("MyCALayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::dealloc: %@",[NSThread callStackSymbols]); + [super dealloc]; + // DBG_PRINT("MyCALayer.dealloc.X: %p\n", self); +} + +#endif + +- (id<CAAction>)actionForKey:(NSString *)key +{ + DBG_PRINT("MyCALayer::actionForKey.0 %p key %s -> NIL\n", self, [key UTF8String]); + return nil; + // return [super actionForKey: key]; +} + +- (void)layoutSublayers +{ + if( fixedFrameSet ) { + NSArray* subs = [self sublayers]; + if( NULL != subs ) { + CGRect rFrame = [self frame]; + if( !CGRectEqualToRect(fixedFrame, rFrame) ) { + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.0: Root %p frame %lf/%lf %lfx%lf -> %lf/%lf %lfx%lf\n", + self, + rFrame.origin.x, rFrame.origin.y, rFrame.size.width, rFrame.size.height, + fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); + #endif + [super setFrame: fixedFrame]; + } + NSUInteger i = 0; + for(i=0; i<[subs count]; i++) { + CALayer* sub = [subs objectAtIndex: i]; + CGRect sFrame = [sub frame]; + CGRect sFrame2 = CGRectMake(0, 0, fixedFrame.size.width, fixedFrame.size.height); + if( !CGRectEqualToRect(sFrame2, sFrame) ) { + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.1: Sub[%d] %p frame %lf/%lf %lfx%lf -> %lf/%lf %lfx%lf\n", + (int)i, sub, + sFrame.origin.x, sFrame.origin.y, sFrame.size.width, sFrame.size.height, + sFrame2.origin.x, sFrame2.origin.y, sFrame2.size.width, sFrame2.size.height); + #endif + [sub setFrame: sFrame2]; + } + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.X: Root %p . Sub[%d] %p : frame r: %lf/%lf %lfx%lf . s: %lf/%lf %lfx%lf\n", + self, (int)i, sub, + rFrame.origin.x, rFrame.origin.y, rFrame.size.width, rFrame.size.height, + sFrame.origin.x, sFrame.origin.y, sFrame.size.width, sFrame.size.height); + #endif + } + } + } else { + [super layoutSublayers]; + } +} + +- (void) setFrame:(CGRect) frame +{ + if( fixedFrameSet ) { + [super setFrame: fixedFrame]; + } else { + [super setFrame: frame]; + } +} + +- (void)fixCALayerLayout: (CALayer*) subLayer visible:(BOOL)visible x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force +{ + int loutQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_LAYOUT & caLayerQuirks ); + { + CALayer* superLayer = [self superlayer]; + CGRect superFrame = [superLayer frame]; + CGRect lFrame = [self frame]; + if( visible ) { + // Opacity must be 0 to see through the disabled CALayer + [subLayer setOpacity: visibleOpacity]; + [self setOpacity: visibleOpacity]; + [self setHidden: NO]; + [subLayer setHidden: NO]; + visibleOpacityZeroed = 0; + } else { + [subLayer setHidden: YES]; + [self setHidden: YES]; + if( !visibleOpacityZeroed ) { + visibleOpacity = [self opacity]; + } + [subLayer setOpacity: 0.0]; + [self setOpacity: 0.0]; + visibleOpacityZeroed = 1; + } + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); + if( !posQuirk || loutQuirk ) { + // Use root layer position, sub-layer will be on 0/0, + // Given AWT position is location on screen w/o insets and top/left origin! + fixedFrame.origin.x = x; + fixedFrame.origin.y = superFrame.size.height - height - y; // AWT's position top/left -> bottom/left + posQuirk |= 8; + } else { + // Buggy super layer position, always use 0/0 + fixedFrame.origin.x = 0; + fixedFrame.origin.y = 0; + } + if( !sizeQuirk ) { + fixedFrame.size.width = lFrame.size.width; + fixedFrame.size.height = lFrame.size.height; + } else { + fixedFrame.size.width = width; + fixedFrame.size.height = height; + } + DBG_PRINT("CALayer::FixCALayerLayout0.0: Visible %d, Quirks [%d, pos %d, size %d, lout %d, force %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", + (int)visible, caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, (int)force, + superLayer, superFrame.origin.x, superFrame.origin.y, superFrame.size.width, superFrame.size.height, + self, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + x, y, width, height, fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); + if( posQuirk || sizeQuirk || loutQuirk ) { + fixedFrameSet = 1; + [super setFrame: fixedFrame]; + } + } + if( NULL != subLayer ) { + CGRect lFrame = [subLayer frame]; + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); + CGFloat _x, _y, _w, _h; + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); + // Sub rel. to used root layer + _x = 0; + _y = 0; + posQuirk |= 8; + if( !sizeQuirk ) { + _w = lFrame.size.width; + _h = lFrame.size.height; + } else { + _w = width; + _h = height; + } + DBG_PRINT("CALayer::FixCALayerLayout1.0: Visible %d, Quirks [%d, pos %d, size %d, lout %d, force %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + (int)visible, caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, (int)force, + subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + width, height, _x, _y, _w, _h); + if( force || posQuirk || sizeQuirk || loutQuirk ) { + lFrame.origin.x = _x; + lFrame.origin.y = _y; + lFrame.size.width = _w; + lFrame.size.height = _h; + if( [subLayer conformsToProtocol:@protocol(NWDedicatedFrame)] ) { + CALayer <NWDedicatedFrame> * subLayerDS = (CALayer <NWDedicatedFrame> *) subLayer; + [subLayerDS setDedicatedFrame: lFrame quirks: caLayerQuirks]; + } else { + [subLayer setFrame: lFrame]; + } + } + } +} + +@end + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateCALayer0 - * Signature: (V)J + * Signature: (II)J */ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 - (JNIEnv *env, jclass unused) + (JNIEnv *env, jclass unused, jint width, jint height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - CALayer* layer = [[CALayer alloc] init]; - DBG_PRINT("CALayer::CreateCALayer.0: %p (refcnt %d)\n", layer, (int)[layer retainCount]); + MyCALayer* layer = [[MyCALayer alloc] init]; + DBG_PRINT("CALayer::CreateCALayer.0: root %p 0/0 %dx%d (refcnt %d)\n", layer, (int)width, (int)height, (int)[layer retainCount]); + // avoid zero size + if(0 == width) { width = 32; } + if(0 == height) { height = 32; } // initial dummy size ! - CGRect lRect = [layer frame]; - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = 32; - lRect.size.height = 32; - [layer setFrame: lRect]; + CGRect lFrame = [layer frame]; + lFrame.origin.x = 0; + lFrame.origin.y = 0; + lFrame.size.width = width; + lFrame.size.height = height; + [layer setFrame: lFrame]; // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [layer removeAllAnimations]; - DBG_PRINT("CALayer::CreateCALayer.1: %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - DBG_PRINT("CALayer::CreateCALayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - + // [layer addAnimation:nil forKey:kCATransition]; + [layer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [layer setNeedsDisplayOnBoundsChange: YES]; + DBG_PRINT("CALayer::CreateCALayer.1: root %p %lf/%lf %lfx%lf\n", layer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height); [pool release]; + DBG_PRINT("CALayer::CreateCALayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); return (jlong) ((intptr_t) layer); } @@ -256,42 +580,76 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: AddCASublayer0 - * Signature: (JJ)V + * Signature: (JJIIIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint x, jint y, jint width, jint height, jint caLayerQuirks) { - JNF_COCOA_ENTER(env); - CALayer* rootLayer = (CALayer*) ((intptr_t) rootCALayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + [rootLayer retain]; // Pairs w/ RemoveCASublayer + [subLayer retain]; // Pairs w/ RemoveCASublayer + CGRect lRectRoot = [rootLayer frame]; - DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", - rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); - if(lRectRoot.origin.x!=0 || lRectRoot.origin.y!=0) { - lRectRoot.origin.x = 0; - lRectRoot.origin.y = 0; - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [rootLayer setFrame: lRectRoot]; - }]; - DBG_PRINT("CALayer::AddCASublayer0.1: Origin %p frame*: %lf/%lf %lfx%lf\n", - rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); + DBG_PRINT("CALayer::AddCASublayer0.0: Quirks %d, Root %p (refcnt %d), Sub %p (refcnt %d), frame0: %lf/%lf %lfx%lf\n", + caLayerQuirks, rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount], + lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); + + [subLayer setFrame:lRectRoot]; + [rootLayer addSublayer:subLayer]; + + // no animations for add/remove/swap sublayers etc + // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] + [rootLayer removeAllAnimations]; + // [rootLayer addAnimation:nil forKey:kCATransition]; // JAU + [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [rootLayer setNeedsDisplayOnBoundsChange: YES]; + [subLayer removeAllAnimations]; + // [subLayer addAnimation:nil forKey:kCATransition]; // JAU + [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [subLayer setNeedsDisplayOnBoundsChange: YES]; + + if( 0 != caLayerQuirks ) { + [rootLayer fixCALayerLayout: subLayer visible:1 x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_TRUE]; } - DBG_PRINT("CALayer::AddCASublayer0.2: %p . %p %lf/%lf %lfx%lf (refcnt %d)\n", - rootLayer, subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - // simple 1:1 layout ! - [subLayer setFrame:lRectRoot]; - [rootLayer addSublayer:subLayer]; + [CATransaction commit]; + + [pool release]; + DBG_PRINT("CALayer::AddCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); +} + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: FixCALayerLayout0 + * Signature: (JJIII)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jboolean visible, jint x, jint y, jint width, jint height, jint caLayerQuirks) +{ + if( 0 != caLayerQuirks ) { + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); + if( NULL == rootLayer ) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"rootLayer\" is null"); + } + CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - // no animations for add/remove/swap sublayers etc - // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] - [rootLayer removeAllAnimations]; - [subLayer removeAllAnimations]; - }]; - DBG_PRINT("CALayer::AddCASublayer0.X: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]); - JNF_COCOA_EXIT(env); + [rootLayer fixCALayerLayout: subLayer visible:(BOOL)visible x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_FALSE]; + + [CATransaction commit]; + + [pool release]; + } } /* @@ -302,18 +660,27 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer) { - JNF_COCOA_ENTER(env); - CALayer* rootLayer = (CALayer*) ((intptr_t) rootCALayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); (void)rootLayer; // no warnings - DBG_PRINT("CALayer::RemoveCASublayer0.0: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]); - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [subLayer removeFromSuperlayer]; - }]; - DBG_PRINT("CALayer::RemoveCASublayer0.X: %p . %p\n", rootLayer, subLayer); - JNF_COCOA_EXIT(env); + DBG_PRINT("CALayer::RemoveCASublayer0.0: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + [subLayer removeFromSuperlayer]; + [subLayer release]; // Pairs w/ AddCASublayer + [rootLayer release]; // Pairs w/ AddCASublayer + + [CATransaction commit]; + + [pool release]; + DBG_PRINT("CALayer::RemoveCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); } /* @@ -324,36 +691,113 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 (JNIEnv *env, jclass unused, jlong caLayer) { - JNF_COCOA_ENTER(env); - CALayer* layer = (CALayer*) ((intptr_t) caLayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* layer = (MyCALayer*) ((intptr_t) caLayer); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + DBG_PRINT("CALayer::DestroyCALayer0.0: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); + [layer release]; // Trigger release and dealloc of root CALayer, it's child etc .. + + [CATransaction commit]; + + [pool release]; + DBG_PRINT("CALayer::DestroyCALayer0.X: root %p\n", layer); +} + +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: GetJAWTSurfaceLayersHandle0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_GetJAWTSurfaceLayersHandle0 + (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer) +{ + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); + if (NULL == dsi) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); + return 0; + } + id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo; + return (jlong) ((intptr_t) surfaceLayers); +} + +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: SetJAWTRootSurfaceLayer0 + * Signature: (JJ)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 + (JNIEnv *env, jclass unused, jlong jawtSurfaceLayersHandle, jlong caLayer) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)(intptr_t)jawtSurfaceLayersHandle; + MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", [surfaceLayers layer], layer, (int)[layer retainCount]); + [surfaceLayers setLayer: [layer retain]]; // Pairs w/ Unset + + [CATransaction commit]; + + [pool release]; + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); +} + +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: UnsetJAWTRootSurfaceLayer0 + * Signature: (JJ)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 + (JNIEnv *env, jclass unused, jlong jawtSurfaceLayersHandle, jlong caLayer) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)(intptr_t)jawtSurfaceLayersHandle; + MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; + if(layer != [surfaceLayers layer]) { + NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); + return; + } + DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.0: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); + [layer release]; // Pairs w/ Set + [surfaceLayers setLayer: NULL]; + + [CATransaction commit]; - DBG_PRINT("CALayer::DestroyCALayer0.0: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [layer release]; // performs release! - }]; - DBG_PRINT("CALayer::DestroyCALayer0.X: %p\n", layer); - JNF_COCOA_EXIT(env); + [pool release]; + DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.X: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); } @interface MainRunnable : NSObject { - JavaVM *jvmHandle; - int jvmVersion; jobject runnableObj; } -- (id) initWithRunnable: (jobject)runnable jvmHandle: (JavaVM*)jvm jvmVersion: (int)jvmVers; +- (id) initWithRunnable: (jobject)runnable; - (void) jRun; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +- (void)dealloc; +#endif + + @end @implementation MainRunnable -- (id) initWithRunnable: (jobject)runnable jvmHandle: (JavaVM*)jvm jvmVersion: (int)jvmVers +- (id) initWithRunnable: (jobject)runnable { - jvmHandle = jvm; - jvmVersion = jvmVers; runnableObj = runnable; return [super init]; } @@ -361,58 +805,111 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 - (void) jRun { int shallBeDetached = 0; - JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + JNIEnv* env = NativewindowCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); + DBG_PRINT2("MainRunnable.1 env: %d\n", (int)(NULL!=env)); if(NULL!=env) { + DBG_PRINT2("MainRunnable.1.0\n"); (*env)->CallVoidMethod(env, runnableObj, runnableRunID); + DBG_PRINT2("MainRunnable.1.1\n"); + (*env)->DeleteGlobalRef(env, runnableObj); - if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } + DBG_PRINT2("MainRunnable.1.3\n"); + // detaching thread not required - daemon + // NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } + DBG_PRINT2("MainRunnable.X\n"); } -@end +#ifdef DBG_LIFECYCLE +- (id)retain +{ + DBG_PRINT2("MainRunnable::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + id o = [super retain]; + DBG_PRINT2("MainRunnable::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} -/* - * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: RunOnMainThread0 - * Signature: (ZLjava/lang/Runnable;)V - */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 - (JNIEnv *env, jclass unused, jboolean jwait, jobject runnable) +- (oneway void)release { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT2("MainRunnable::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + [super release]; + // DBG_PRINT2("MainRunnable::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); +} + +- (void)dealloc +{ + DBG_PRINT2("MainRunnable::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); + [super dealloc]; + // DBG_PRINT2("MainRunnable.dealloc.X: %p\n", self); +} + +#endif + +@end + +static void RunOnThread (JNIEnv *env, jobject runnable, BOOL onMain, jint delayInMS) +{ + BOOL isMainThread = [NSThread isMainThread]; + BOOL forkOnMain = onMain && ( NO == isMainThread || 0 < delayInMS ); + + DBG_PRINT2( "RunOnThread0: forkOnMain %d [onMain %d, delay %dms, isMainThread %d], NSApp %d, NSApp-isRunning %d\n", + (int)forkOnMain, (int)onMain, (int)delayInMS, (int)isMainThread, (int)(NULL!=NSApp), (int)([NSApp isRunning])); - if ( NO == [NSThread isMainThread] ) { - jobject runnableGlob = (*env)->NewGlobalRef(env, runnable); + if ( forkOnMain ) { + jobject runnableObj = (*env)->NewGlobalRef(env, runnable); - BOOL wait = (JNI_TRUE == jwait) ? YES : NO; - JavaVM *jvmHandle = NULL; - int jvmVersion = 0; + DBG_PRINT2( "RunOnThread.1.0\n"); + MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj]; - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; + if( onMain ) { + [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; } else { - jvmVersion = (*env)->GetVersion(env); + NSTimeInterval delay = (double)delayInMS/1000.0; + [mr performSelector:@selector(jRun) withObject:nil afterDelay:delay]; } + DBG_PRINT2( "RunOnThread.1.1\n"); - MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableGlob jvmHandle: jvmHandle jvmVersion: jvmVersion]; - [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:wait]; [mr release]; + DBG_PRINT2( "RunOnThread.1.2\n"); - (*env)->DeleteGlobalRef(env, runnableGlob); } else { + DBG_PRINT2( "RunOnThread.2\n"); (*env)->CallVoidMethod(env, runnable, runnableRunID); } + DBG_PRINT2( "RunOnThread.X\n"); +} +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: RunOnMainThread0 + * Signature: (ZLjava/lang/Runnable;)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 + (JNIEnv *env, jclass unused, jobject runnable) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + RunOnThread (env, runnable, YES, 0); [pool release]; } /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: RunOnMainThread0 - * Signature: (V)V + * Method: RunLater0 + * Signature: (ZLjava/lang/Runnable;I)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunLater0 + (JNIEnv *env, jclass unused, jboolean onMain, jobject runnable, jint delay) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + RunOnThread (env, runnable, onMain ? YES : NO, delay); + [pool release]; +} + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: IsMainThread0 + * Signature: (V)Z */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 (JNIEnv *env, jclass unused) @@ -420,60 +917,63 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 return ( [NSThread isMainThread] == YES ) ? JNI_TRUE : JNI_FALSE ; } -/* - * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: AttachJAWTSurfaceLayer - * Signature: (JJ)Z +/*** + * The following static functions are copied out of NEWT's OSX impl. <src/newt/native/MacWindow.m> + * May need to push code to NativeWindow, to remove duplication. */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_AttachJAWTSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) +static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) { + NSArray *screens = [NSScreen screens]; + if(screen_idx<0) screen_idx=0; + if(screen_idx>=[screens count]) screen_idx=0; + return (NSScreen *) [screens objectAtIndex: screen_idx]; +} +static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) { + // Mind: typedef uint32_t CGDirectDisplayID; - however, we assume it's 64bit on 64bit ?! + NSDictionary * dict = [screen deviceDescription]; + NSNumber * val = (NSNumber *) [dict objectForKey: @"NSScreenNumber"]; + // [NSNumber integerValue] returns NSInteger which is 32 or 64 bit native size + return (CGDirectDisplayID) [val integerValue]; +} +static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) { - JNF_COCOA_ENTER(env); - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; - } - CALayer* layer = (CALayer*) (intptr_t) caLayer; - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo; - DBG_PRINT("CALayer::attachJAWTSurfaceLayer: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); - surfaceLayers.layer = layer; // already incr. retain count - DBG_PRINT("CALayer::attachJAWTSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - }]; - JNF_COCOA_EXIT(env); - return JNI_TRUE; + long value = 0; + CFNumberRef numRef; + numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); + if (numRef != NULL) + CFNumberGetValue(numRef, kCFNumberLongType, &value); + return value; } +#define CGDDGetModeRefreshRate(mode) GetDictionaryLong((mode), kCGDisplayRefreshRate) /* - * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: DetachJAWTSurfaceLayer - * Signature: (JJ)Z -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_DetachJAWTSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetScreenRefreshRate + * Signature: (I)I + */ +JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshRate0 + (JNIEnv *env, jclass unused, jint scrn_idx) { - JNF_COCOA_ENTER(env); - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; - } - CALayer* layer = (CALayer*) (intptr_t) caLayer; - { - id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo; - if(layer != surfaceLayers.layer) { - NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); - return JNI_FALSE; + int res = 0; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); + DBG_PRINT("GetScreenRefreshRate.0: screen %p\n", (void *)screen); + if(NULL != screen) { + CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); + DBG_PRINT("GetScreenRefreshRate.1: display %p\n", (void *)(intptr_t)display); + if(0 != display) { + CFDictionaryRef mode = CGDisplayCurrentMode(display); + DBG_PRINT("GetScreenRefreshRate.2: mode %p\n", (void *)mode); + if(NULL != mode) { + res = CGDDGetModeRefreshRate(mode); + DBG_PRINT("GetScreenRefreshRate.3: res %d\n", res); + } } } - // [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo; - DBG_PRINT("CALayer::detachJAWTSurfaceLayer: (%p) %p -> NULL\n", layer, surfaceLayers.layer); - surfaceLayers.layer = NULL; - [layer release]; - // }]; - JNF_COCOA_EXIT(env); - return JNI_TRUE; + if(0 == res) { + res = 60; // default .. (experienced on OSX 10.6.8) + } + DBG_PRINT("GetScreenRefreshRate.X: %d\n", (int)res); + [pool release]; + return res; } - */ diff --git a/src/nativewindow/native/win32/DeviceDriverQuery.txt b/src/nativewindow/native/win32/DeviceDriverQuery.txt new file mode 100644 index 000000000..7401ed83b --- /dev/null +++ b/src/nativewindow/native/win32/DeviceDriverQuery.txt @@ -0,0 +1,41 @@ + + // INCOMPLETE ! + // + // See Bug 706 and Bug 520 + // https://jogamp.org/bugzilla/show_bug.cgi?id=520 + // https://jogamp.org/bugzilla/show_bug.cgi?id=706 + // + // Device Driver SDK + // http://msdn.microsoft.com/en-us/library/ff553567.aspx#ddk_setupdi_device_information_functions_dg + { + /** + System-Defined Device Setup Classes Available to Vendors (GUID) + + Display Adapters + Class = Display + ClassGuid = {4d36e968-e325-11ce-bfc1-08002be10318} + This class includes video adapters. Drivers for this class include display drivers and video miniport drivers. + + /opt-windows/mingw/include/devguid.h GUID_DEVCLASS_DISPLAY + GUID_DEVCLASS_DISPLAY + HDEVINFO SetupDiGetClassDevs( + _In_opt_ const GUID *ClassGuid, + _In_opt_ PCTSTR Enumerator, + _In_opt_ HWND hwndParent, + _In_ DWORD Flags + ); + + */ + const GUID devClassDisplay = GUID_DEVCLASS_DISPLAY; + // http://msdn.microsoft.com/en-us/library/ff551069.aspx + HDEVINFO DeviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_DISPLAY, NULL /* bus */, NULL /* windows */, DIGCF_PRESENT | DIGCF_PROFILE /* flags */); + DWORD MemberIndex = 0; + SP_DEVINFO_DATA DeviceInfoData; + DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + while( TRUE == SetupDiEnumDeviceInfo(DeviceInfoSet, MemberIndex, &DeviceInfoData) ) { + SetupDiGetSelectedDevice(); + MemberIndex++; + } + SetupDiDestroyDeviceInfoList(hDevInfo); + } + diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index 3ab7f9859..bec1d4922 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -20,8 +20,10 @@ #ifdef VERBOSE_ON #define DBG_PRINT(args...) fprintf(stderr, args); + #define DBG_PRINT_FLUSH(args...) fprintf(stderr, args); fflush(stderr); #else #define DBG_PRINT(args...) + #define DBG_PRINT_FLUSH(args...) #endif static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; @@ -30,6 +32,162 @@ static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; +static jmethodID dumpStackID = NULL; + +typedef struct { + HANDLE threadHandle; + DWORD threadId; + volatile BOOL threadReady; + volatile BOOL threadDead; +} DummyThreadContext; + +typedef struct { + HINSTANCE hInstance; + const TCHAR* wndClassName; + const TCHAR* wndName; + jint x; + jint y; + jint width; + jint height; + volatile HWND hWnd; + volatile BOOL threadReady; +} DummyThreadCommand; + +#define TM_OPENWIN WM_APP+1 +#define TM_CLOSEWIN WM_APP+2 +#define TM_STOP WM_APP+3 + +static const char * sTM_OPENWIN = "TM_OPENWIN"; +static const char * sTM_CLOSEWIN = "TM_CLOSEWIN"; +static const char * sTM_STOP = "TM_STOP"; + +/** 3s timeout */ +static const int64_t TIME_OUT = 3000000; + +static jboolean DDT_CheckAlive(JNIEnv *env, const char *msg, DummyThreadContext *ctx) { + if( ctx->threadDead ) { + NativewindowCommon_throwNewRuntimeException(env, "DDT is dead at %s", msg); + return JNI_FALSE; + } else { + DBG_PRINT_FLUSH("*** DDT-Check ALIVE @ %s\n", msg); + return JNI_TRUE; + } +} + +static jboolean DDT_WaitUntilCreated(JNIEnv *env, DummyThreadContext *ctx, BOOL created) { + const int64_t t0 = NativewindowCommon_CurrentTimeMillis(); + int64_t t1 = t0; + if( created ) { + while( !ctx->threadReady && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !ctx->threadReady ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT CREATED", (int)(t1-t0)); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check CREATED\n"); + } else { + while( !ctx->threadDead && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !ctx->threadDead ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT DESTROYED", (int)(t1-t0)); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check DEAD\n"); + } + return JNI_TRUE; +} + +static jboolean DDT_WaitUntilReady(JNIEnv *env, const char *msg, DummyThreadCommand *cmd) { + const int64_t t0 = NativewindowCommon_CurrentTimeMillis(); + int64_t t1 = t0; + while( !cmd->threadReady && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !cmd->threadReady ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT %s", (int)(t1-t0), msg); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check READY @ %s\n", msg); + return JNI_TRUE; +} + +static HWND DummyWindowCreate + (HINSTANCE hInstance, const TCHAR* wndClassName, const TCHAR* wndName, jint x, jint y, jint width, jint height) +{ + DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + DWORD dwStyle = WS_OVERLAPPEDWINDOW; + HWND hWnd = CreateWindowEx( dwExStyle, + wndClassName, + wndName, + dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + x, y, width, height, + NULL, NULL, hInstance, NULL ); + return hWnd; +} + +static DWORD WINAPI DummyDispatchThreadFunc(LPVOID param) +{ + MSG msg; + BOOL bRet; + BOOL bEOL=FALSE; + DummyThreadContext *threadContext = (DummyThreadContext*)param; + + /* there can not be any messages for us now, as the creator waits for + threadReady before continuing, but we must use this PeekMessage() to + create the thread message queue */ + PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); + + /* now we can safely say: we have a qeue and are ready to receive messages */ + // threadContext->threadId = GetCurrentThreadId(); + threadContext->threadDead = FALSE; + threadContext->threadReady = TRUE; + + while( !bEOL && (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0 ) { + if ( -1 == bRet ) { + fprintf(stderr, "DummyDispatchThread (id %d): GetMessage Error %d, werr %d\n", + (int)threadContext->threadId, (int)bRet, (int)GetLastError()); + fflush(stderr); + bEOL = TRUE; + break; // EOL + } else { + switch(msg.message) { + case TM_OPENWIN: { + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch OPENWIN\n"); + tParam->hWnd = DummyWindowCreate(tParam->hInstance, tParam->wndClassName, tParam->wndName, tParam->x, tParam->y, tParam->width, tParam->height); + tParam->threadReady = TRUE; + } + break; + case TM_CLOSEWIN: { + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch CLOSEWIN\n"); + DestroyWindow(tParam->hWnd); + tParam->threadReady = TRUE; + } + break; + case TM_STOP: { + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch STOP -> DEAD\n"); + tParam->threadReady = TRUE; + bEOL = TRUE; + } + break; // EOL + default: + TranslateMessage(&msg); + DispatchMessage(&msg); + break; + } + } + } + /* dead */ + DBG_PRINT_FLUSH("*** DDT-Dispatch DEAD\n"); + threadContext->threadDead = TRUE; + ExitThread(0); + return 0; +} + HINSTANCE GetApplicationHandle() { return GetModuleHandle(NULL); @@ -37,16 +195,54 @@ HINSTANCE GetApplicationHandle() { /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: boolean CreateWindowClass(long hInstance, java.lang.String clazzName, long wndProc) - * C function: BOOL CreateWindowClass(HANDLE hInstance, LPCSTR clazzName, HANDLE wndProc); + * Java method: long CreateDummyDispatchThread0() + */ +JNIEXPORT jlong JNICALL +Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyDispatchThread0 + (JNIEnv *env, jclass _unused) +{ + DWORD threadId = 0; + DummyThreadContext * dispThreadCtx = calloc(1, sizeof(DummyThreadContext)); + + dispThreadCtx->threadHandle = CreateThread(NULL, 0, DummyDispatchThreadFunc, (LPVOID)dispThreadCtx, 0, &threadId); + if( NULL == dispThreadCtx->threadHandle || 0 == threadId ) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT CREATE failed handle %p, id %d, werr %d", + (void*)threadHandle, (int)threadId, (int)GetLastError()); + return (jlong)0; + } + if( JNI_FALSE == DDT_WaitUntilCreated(env, dispThreadCtx, TRUE) ) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT CREATE (ack) failed handle %p, id %d, werr %d", + (void*)threadHandle, (int)threadId, (int)GetLastError()); + return (jlong)0; + } + DBG_PRINT_FLUSH("*** DDT Created %d\n", (int)threadId); + dispThreadCtx->threadId = threadId; + return (jlong) (intptr_t) dispThreadCtx; +} + +/* Java->C glue code: + * Java package: jogamp.nativewindow.windows.GDIUtil + * Java method: boolean CreateWindowClass0(long hInstance, java.lang.String clazzName, long wndProc) + * C function: BOOL CreateWindowClass0(HANDLE hInstance, LPCSTR clazzName, HANDLE wndProc); */ JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc) +Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass0 + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc, + jlong iconSmallHandle, jlong iconBigHandle) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; const TCHAR* clazzName = NULL; - WNDCLASS wc; + WNDCLASSEX wc; jboolean res; #ifdef UNICODE @@ -56,23 +252,25 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass #endif ZeroMemory( &wc, sizeof( wc ) ); - if( GetClassInfo( hInstance, clazzName, &wc ) ) { + if( GetClassInfoEx( hInstance, clazzName, &wc ) ) { // registered already res = JNI_TRUE; } else { // register now ZeroMemory( &wc, sizeof( wc ) ); + wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW ; wc.lpfnWndProc = (WNDPROC) (intptr_t) wndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = LoadCursor( NULL, IDC_ARROW); + wc.hIcon = (HICON) (intptr_t) iconBigHandle; + wc.hCursor = NULL; wc.hbrBackground = NULL; // no background paint - GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = clazzName; - res = ( 0 != RegisterClass( &wc ) ) ? JNI_TRUE : JNI_FALSE ; + wc.hIconSm = (HICON) (intptr_t) iconSmallHandle; + res = ( 0 != RegisterClassEx( &wc ) ) ? JNI_TRUE : JNI_FALSE ; } #ifdef UNICODE @@ -86,15 +284,15 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: boolean DestroyWindowClass(long hInstance, java.lang.String className) - * C function: BOOL DestroyWindowClass(HANDLE hInstance, LPCSTR className); + * Java method: boolean DestroyWindowClass0(long hInstance, java.lang.String className, long dispThreadCtx) */ JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName) +Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass0 + (JNIEnv *env, jclass gdiClazz, jlong jHInstance, jstring jClazzName, jlong jDispThreadCtx) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; const TCHAR* clazzName = NULL; + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; jboolean res; #ifdef UNICODE @@ -111,55 +309,175 @@ Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif + if( NULL != dispThreadCtx) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + DummyThreadCommand tParam = {0}; + tParam.threadReady = FALSE; + DBG_PRINT_FLUSH("*** DDT Destroy %d\n", (int)threadId); +#ifdef VERBOSE_ON + (*env)->CallStaticVoidMethod(env, gdiClazz, dumpStackID); +#endif + + if( JNI_FALSE == DDT_CheckAlive(env, sTM_STOP, dispThreadCtx) ) { + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + if ( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_STOP, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_STOP, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + if( JNI_FALSE == DDT_WaitUntilCreated(env, dispThreadCtx, FALSE) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT KILL %s (ack) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + free(dispThreadCtx); // free after proper DDT shutdown! + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + } + return res; } - /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: long CreateDummyWindow0(long hInstance, java.lang.String className, java.lang.String windowName, int x, int y, int width, int height) - * C function: HANDLE CreateDummyWindow0(HANDLE hInstance, LPCSTR className, LPCSTR windowName, int x, int y, int width, int height); + * Java method: long CreateDummyWindow0(long hInstance, java.lang.String className, jlong dispThreadCtx, java.lang.String windowName, int x, int y, int width, int height) */ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindow0 - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jstring jWndName, jint x, jint y, jint width, jint height) + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jlong jDispThreadCtx, jstring jWndName, jint x, jint y, jint width, jint height) { - HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; - const TCHAR* wndClassName = NULL; - const TCHAR* wndName = NULL; - DWORD dwExStyle; - DWORD dwStyle; - HWND hWnd; + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; + DummyThreadCommand tParam = {0}; + + tParam.hInstance = (HINSTANCE) (intptr_t) jHInstance; + tParam.x = x; + tParam.y = y; + tParam.width = width; + tParam.height = height; + tParam.hWnd = 0; + tParam.threadReady = FALSE; #ifdef UNICODE - wndClassName = NewtCommon_GetNullTerminatedStringChars(env, jWndClassName); - wndName = NewtCommon_GetNullTerminatedStringChars(env, jWndName); + tParam.wndClassName = NewtCommon_GetNullTerminatedStringChars(env, jWndClassName); + tParam.wndName = NewtCommon_GetNullTerminatedStringChars(env, jWndName); #else - wndClassName = (*env)->GetStringUTFChars(env, jWndClassName, NULL); - wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); + tParam.wndClassName = (*env)->GetStringUTFChars(env, jWndClassName, NULL); + tParam.wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); #endif - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; - dwStyle = WS_OVERLAPPEDWINDOW; - - hWnd = CreateWindowEx( dwExStyle, - wndClassName, - wndName, - dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - x, y, width, height, - NULL, NULL, hInstance, NULL ); + if( NULL == dispThreadCtx ) { + tParam.hWnd = DummyWindowCreate(tParam.hInstance, tParam.wndClassName, tParam.wndName, tParam.x, tParam.y, tParam.width, tParam.height); + } else { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + if( JNI_FALSE == DDT_CheckAlive(env, sTM_OPENWIN, dispThreadCtx) ) { + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } else { + if( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_OPENWIN, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_OPENWIN, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + tParam.hWnd = 0; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + tParam.hWnd = 0; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s to handle %p, id %d failed, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } + } #ifdef UNICODE - free((void*) wndClassName); - free((void*) wndName); + free((void*) tParam.wndClassName); + free((void*) tParam.wndName); #else - (*env)->ReleaseStringUTFChars(env, jWndClassName, wndClassName); - (*env)->ReleaseStringUTFChars(env, jWndName, wndName); + (*env)->ReleaseStringUTFChars(env, jWndClassName, tParam.wndClassName); + (*env)->ReleaseStringUTFChars(env, jWndName, tParam.wndName); #endif - return (jlong) (intptr_t) hWnd; + return (jlong) (intptr_t) tParam.hWnd; } +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: DestroyWindow0 + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindow0 +(JNIEnv *env, jclass unused, jlong jDispThreadCtx, jlong jwin) +{ + jboolean res = JNI_TRUE; + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; + HWND hWnd = (HWND) (intptr_t) jwin; + if( NULL == dispThreadCtx ) { + DestroyWindow(hWnd); + } else { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + DummyThreadCommand tParam = {0}; + + tParam.hWnd = hWnd; + tParam.threadReady = FALSE; + + if( JNI_FALSE == DDT_CheckAlive(env, sTM_CLOSEWIN, dispThreadCtx) ) { + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } else { + if ( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_CLOSEWIN, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_CLOSEWIN, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s to handle %p, id %d failed, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } + } + return res; +} /* * Class: jogamp_nativewindow_windows_GDIUtil @@ -167,9 +485,9 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindow0 * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 - (JNIEnv *env, jclass clazz) + (JNIEnv *env, jclass gdiClazz) { - if(NativewindowCommon_init(env)) { + if( NativewindowCommon_init(env) ) { jclass c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't find %s", ClazzNamePoint); @@ -184,12 +502,16 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't fetch %s.%s %s", ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } + dumpStackID = (*env)->GetStaticMethodID(env, gdiClazz, "dumpStack", "()V"); + if(NULL==dumpStackID) { + NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't get method dumpStack"); + } } return JNI_TRUE; } -LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - return DefWindowProc(hWnd,uMsg,wParam,lParam); +static LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd,uMsg,wParam,lParam); } /* @@ -224,3 +546,29 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_windows_GDIUtil_GetRelativeLo return (*env)->NewObject(env, pointClz, pointCstr, (jint)dest.x, (jint)dest.y); } +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: IsChild0 + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsChild0 + (JNIEnv *env, jclass unused, jlong jwin) +{ + HWND hWnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hWnd, GWL_STYLE); + BOOL bIsChild = 0 != (style & WS_CHILD) ; + return bIsChild ? JNI_TRUE : JNI_FALSE; +} + +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: IsUndecorated0 + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsUndecorated0 + (JNIEnv *env, jclass unused, jlong jwin) +{ + HWND hWnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hWnd, GWL_STYLE); + BOOL bIsUndecorated = 0 != (style & (WS_CHILD|WS_POPUP)) ; + return bIsUndecorated ? JNI_TRUE : JNI_FALSE; +} + diff --git a/src/nativewindow/native/win32/WindowsDWM.h b/src/nativewindow/native/win32/WindowsDWM.h index 36f82fc94..6e5160fa4 100644 --- a/src/nativewindow/native/win32/WindowsDWM.h +++ b/src/nativewindow/native/win32/WindowsDWM.h @@ -4,6 +4,8 @@ #include <windows.h> #define DWM_BB_ENABLE 0x00000001 // fEnable has been specified + #define DWM_BB_BLURREGION 0x00000002 + #define DWM_BB_TRANSITIONONMAXIMIZED 0x00000004 #define DWM_EC_DISABLECOMPOSITION 0 #define DWM_EC_ENABLECOMPOSITION 1 diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 439d9b334..247dc1311 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -26,15 +26,27 @@ * or implied, of JogAmp Community. */ +#include "NativewindowCommon.h" +#include "Xmisc.h" +#include "jogamp_nativewindow_x11_X11Lib.h" +#include "jogamp_nativewindow_x11_X11Util.h" + +#include <X11/Xatom.h> + +#include <X11/extensions/Xrender.h> + +/** Remove memcpy GLIBC > 2.4 dependencies */ +#include <glibc-compat-symbols.h> + +// #define VERBOSE_ON 1 + +#ifdef VERBOSE_ON + #define DBG_PRINT(args...) fprintf(stderr, args); +#else + #define DBG_PRINT(args...) +#endif + -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <stdarg.h> -#include <unistd.h> -#include <errno.h> -#include <X11/Xlib.h> -#include <X11/Xutil.h> /* Linux headers don't work properly */ #define __USE_GNU #include <dlfcn.h> @@ -80,16 +92,7 @@ Bool XF86VidModeSetGammaRamp( #define RTLD_DEFAULT NULL #endif -#include "NativewindowCommon.h" -#include "jogamp_nativewindow_x11_X11Lib.h" - -// #define VERBOSE_ON 1 - -#ifdef VERBOSE_ON - #define DBG_PRINT(args...) fprintf(stderr, args); -#else - #define DBG_PRINT(args...) -#endif +#define X11_MOUSE_EVENT_MASK (ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask) static const char * const ClazzNameBuffers = "com/jogamp/common/nio/Buffers"; static const char * const ClazzNameBuffersStaticCstrName = "copyByteBuffer"; @@ -98,6 +101,9 @@ static const char * const ClazzNameByteBuffer = "java/nio/ByteBuffer"; static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzAnyCstrName = "<init>"; static const char * const ClazzNamePointCstrSignature = "(II)V"; +static jclass X11UtilClazz = NULL; +static jmethodID getCurrentThreadNameID = NULL; +static jmethodID dumpStackID = NULL; static jclass clazzBuffers = NULL; static jmethodID cstrBuffers = NULL; static jclass clazzByteBuffer = NULL; @@ -107,121 +113,123 @@ static jmethodID pointCstr = NULL; static void _initClazzAccess(JNIEnv *env) { jclass c; - if(!NativewindowCommon_init(env)) return; - - c = (*env)->FindClass(env, ClazzNameBuffers); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameBuffers); - } - clazzBuffers = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==clazzBuffers) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameBuffers); - } - c = (*env)->FindClass(env, ClazzNameByteBuffer); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameByteBuffer); - } - clazzByteBuffer = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameByteBuffer); - } - - cstrBuffers = (*env)->GetStaticMethodID(env, clazzBuffers, - ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); - if(NULL==cstrBuffers) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't create %s.%s %s", - ClazzNameBuffers, ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); - } + if( NativewindowCommon_init(env) ) { + getCurrentThreadNameID = (*env)->GetStaticMethodID(env, X11UtilClazz, "getCurrentThreadName", "()Ljava/lang/String;"); + if(NULL==getCurrentThreadNameID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method getCurrentThreadName"); + } + dumpStackID = (*env)->GetStaticMethodID(env, X11UtilClazz, "dumpStack", "()V"); + if(NULL==dumpStackID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method dumpStack"); + } - c = (*env)->FindClass(env, ClazzNamePoint); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNamePoint); - } - pointClz = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==pointClz) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNamePoint); - } - pointCstr = (*env)->GetMethodID(env, pointClz, ClazzAnyCstrName, ClazzNamePointCstrSignature); - if(NULL==pointCstr) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't fetch %s.%s %s", - ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); - } -} + c = (*env)->FindClass(env, ClazzNameBuffers); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameBuffers); + } + clazzBuffers = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==clazzBuffers) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameBuffers); + } + c = (*env)->FindClass(env, ClazzNameByteBuffer); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameByteBuffer); + } + clazzByteBuffer = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameByteBuffer); + } -static JavaVM *jvmHandle = NULL; -static int jvmVersion = 0; + cstrBuffers = (*env)->GetStaticMethodID(env, clazzBuffers, + ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); + if(NULL==cstrBuffers) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't create %s.%s %s", + ClazzNameBuffers, ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); + } -static void setupJVMVars(JNIEnv * env) { - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; + c = (*env)->FindClass(env, ClazzNamePoint); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNamePoint); + } + pointClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==pointClz) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNamePoint); + } + pointCstr = (*env)->GetMethodID(env, pointClz, ClazzAnyCstrName, ClazzNamePointCstrSignature); + if(NULL==pointCstr) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't fetch %s.%s %s", + ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); + } } - jvmVersion = (*env)->GetVersion(env); } static XErrorHandler origErrorHandler = NULL ; -static int errorHandlerBlocked = 0 ; -static int errorHandlerQuiet = 0 ; +static int errorHandlerQuiet = 1 ; +static int errorHandlerDebug = 0 ; +static int errorHandlerThrowException = 0; static int x11ErrorHandler(Display *dpy, XErrorEvent *e) { - if(!errorHandlerQuiet) { - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; - const char * errStr = strerror(errno); - - fprintf(stderr, "Info: Nativewindow X11 Error: Display %p, Code 0x%X, errno %s\n", dpy, e->error_code, errStr); + if( !errorHandlerQuiet || errorHandlerDebug ) { + const char * errnoStr = strerror(errno); + char errCodeStr[80]; + char reqCodeStr[80]; + int shallBeDetached = 0; + JNIEnv *jniEnv = NULL; + + snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); + XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); + XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); + + fprintf(stderr, "Info: Nativewindow X11 Error: %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); fflush(stderr); - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "Nativewindow X11 Error: can't attach thread: %d\n", envRes); - return 0; + if( errorHandlerDebug || errorHandlerThrowException ) { + jniEnv = NativewindowCommon_GetJNIEnv(0 /* asDaemon */, &shallBeDetached); + if(NULL == jniEnv) { + fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); + fflush(stderr); } - curEnv = newEnv; - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "Nativewindow X11 Error: can't GetEnv: %d\n", envRes); - return 0; } - NativewindowCommon_throwNewRuntimeException(curEnv, "Info: Nativewindow X11 Error: Display %p, Code 0x%X, errno %s", - dpy, e->error_code, errStr); - if( NULL != newEnv ) { - // detached attached thread - (*jvmHandle)->DetachCurrentThread(jvmHandle); + if( NULL != jniEnv ) { + if( errorHandlerDebug ) { + (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); + } + + if(errorHandlerThrowException) { + NativewindowCommon_throwNewRuntimeException(jniEnv, "Nativewindow X11 Error: %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); + } + NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } } -#if 0 - if(NULL!=origErrorHandler) { - origErrorHandler(dpy, e); - } -#endif - return 0; } -static void x11ErrorHandlerEnable(Display *dpy, int onoff, JNIEnv * env) { - if(errorHandlerBlocked) return; - +static void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int force, int onoff, int quiet, int sync) { + errorHandlerQuiet = quiet; if(onoff) { - if(NULL==origErrorHandler) { - setupJVMVars(env); - if(NULL!=dpy) { + if(force || NULL==origErrorHandler) { + XErrorHandler prevErrorHandler; + prevErrorHandler = XSetErrorHandler(x11ErrorHandler); + if(x11ErrorHandler != prevErrorHandler) { // if forced don't overwrite w/ orig w/ our handler + origErrorHandler = prevErrorHandler; + } + if(sync && NULL!=dpy) { XSync(dpy, False); } - origErrorHandler = XSetErrorHandler(x11ErrorHandler); } } else { if(NULL!=origErrorHandler) { - if(NULL!=dpy) { + if(sync && NULL!=dpy) { XSync(dpy, False); } XSetErrorHandler(origErrorHandler); @@ -230,46 +238,22 @@ static void x11ErrorHandlerEnable(Display *dpy, int onoff, JNIEnv * env) { } } -static void x11ErrorHandlerEnableBlocking(JNIEnv * env, int onoff, int quiet) { - errorHandlerBlocked = 0 ; - x11ErrorHandlerEnable(NULL, onoff, env); - errorHandlerBlocked = onoff ; - errorHandlerQuiet = quiet; -} - - static XIOErrorHandler origIOErrorHandler = NULL; static int x11IOErrorHandler(Display *dpy) { - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; const char * dpyName = XDisplayName(NULL); - const char * errStr = strerror(errno); - - fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errStr); - - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "Nativewindow X11 IOError: can't attach thread: %d\n", envRes); - return; - } - curEnv = newEnv; - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "Nativewindow X11 IOError: can't GetEnv: %d\n", envRes); - return; - } + const char * errnoStr = strerror(errno); + int shallBeDetached = 0; + JNIEnv *jniEnv = NULL; - NativewindowCommon_FatalError(curEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errStr); + fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errnoStr); + fflush(stderr); - if( NULL != newEnv ) { - // detached attached thread - (*jvmHandle)->DetachCurrentThread(jvmHandle); + jniEnv = NativewindowCommon_GetJNIEnv(0 /* asDaemon */, &shallBeDetached); + if (NULL != jniEnv) { + NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errnoStr); + NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } if(NULL!=origIOErrorHandler) { origIOErrorHandler(dpy); @@ -280,7 +264,6 @@ static int x11IOErrorHandler(Display *dpy) static void x11IOErrorHandlerEnable(int onoff, JNIEnv * env) { if(onoff) { if(NULL==origIOErrorHandler) { - setupJVMVars(env); origIOErrorHandler = XSetIOErrorHandler(x11IOErrorHandler); } } else { @@ -289,38 +272,49 @@ static void x11IOErrorHandlerEnable(int onoff, JNIEnv * env) { } } -static int _initialized=0; -static jboolean _xinitThreadsOK=JNI_FALSE; +static int _initialized = 0; JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass _unused, jboolean firstUIActionOnProcess) { - if(0==_initialized) { - if( JNI_TRUE == firstUIActionOnProcess ) { - if( 0 == XInitThreads() ) { - fprintf(stderr, "Warning: XInitThreads() failed\n"); - } else { - _xinitThreadsOK=JNI_TRUE; - DBG_PRINT( "X11: XInitThreads() called for concurrent Thread support\n"); - } - } else { - DBG_PRINT( "X11: XInitThreads() _not_ called for concurrent Thread support\n"); +Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboolean debug) { + if( 0 == _initialized ) { + if(debug) { + errorHandlerDebug = 1; } + X11UtilClazz = (jclass)(*env)->NewGlobalRef(env, clazz); _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 1, debug ? 0 : 1, 0 /* no dpy, force, no sync */); _initialized=1; + if(JNI_TRUE == debug) { + fprintf(stderr, "Info: NativeWindow native init passed\n"); + } } - return _xinitThreadsOK; + return JNI_TRUE; } JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_shutdown0(JNIEnv *env, jclass _unused) { + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, errorHandlerQuiet, 0 /* no dpy, no sync */); x11IOErrorHandlerEnable(0, env); } JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_setX11ErrorHandler0(JNIEnv *env, jclass _unused, jboolean onoff, jboolean quiet) { - x11ErrorHandlerEnableBlocking(env, ( JNI_TRUE == onoff ) ? 1 : 0, ( JNI_TRUE == quiet ) ? 1 : 0); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, onoff ? 1 : 0, quiet ? 1 : 0, 0 /* no dpy, force, no sync */); +} + +/* Java->C glue code: + * Java package: jogamp.nativewindow.x11.X11Lib + * Java method: boolean XRenderFindVisualFormat(long dpy, long visual, XRenderPictFormat dest) + */ +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_x11_X11Lib_XRenderFindVisualFormat1(JNIEnv *env, jclass _unused, jlong dpy, jlong visual, jobject xRenderPictFormat) { + XRenderPictFormat * dest = (XRenderPictFormat *) (*env)->GetDirectBufferAddress(env, xRenderPictFormat); + XRenderPictFormat * src = XRenderFindVisualFormat((Display *) (intptr_t) dpy, (Visual *) (intptr_t) visual); + if (NULL == src) return JNI_FALSE; + memcpy(dest, src, sizeof(XRenderPictFormat)); + return JNI_TRUE; } /* Java->C glue code: @@ -332,45 +326,71 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Ljava_lang_Object_2I(JNIEnv *env, jclass _unused, jlong arg0, jlong arg1, jobject arg2, jobject arg3, jint arg3_byte_offset) { XVisualInfo * _ptr2 = NULL; int * _ptr3 = NULL; - XVisualInfo * _res; - int count; - jobject jbyteSource; - jobject jbyteCopy; - if(0==arg0) { - NativewindowCommon_FatalError(env, "invalid display connection.."); - } - if (arg2 != NULL) { - _ptr2 = (XVisualInfo *) (((char*) (*env)->GetDirectBufferAddress(env, arg2)) + 0); - } - if (arg3 != NULL) { - _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); + XVisualInfo * _res = NULL; + int count = 0; + jobject jbyteSource = NULL; + jobject jbyteCopy = NULL; + if( 0 == arg0 || 0 == arg2 || 0 == arg3 ) { + NativewindowCommon_FatalError(env, "invalid display connection, vinfo_template or nitems_return"); + return NULL; } - x11ErrorHandlerEnable((Display *) (intptr_t) arg0, 1, env); - _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - x11ErrorHandlerEnable((Display *) (intptr_t) arg0, 0, env); - count = _ptr3[0]; - if (arg3 != NULL) { - (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); + _ptr2 = (XVisualInfo *) (((char*) (*env)->GetDirectBufferAddress(env, arg2)) + 0); + if( NULL != _ptr2 ) { + _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); + if( NULL != _ptr3 ) { + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, errorHandlerQuiet, 0); + _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, errorHandlerQuiet, 0); + count = _ptr3[0]; + (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); + } } if (_res == NULL) return NULL; jbyteSource = (*env)->NewDirectByteBuffer(env, _res, count * sizeof(XVisualInfo)); jbyteCopy = (*env)->CallStaticObjectMethod(env, clazzBuffers, cstrBuffers, jbyteSource); + (*env)->DeleteLocalRef(env, jbyteSource); XFree(_res); return jbyteCopy; } -JNIEXPORT jlong JNICALL +JNIEXPORT jint JNICALL +Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _unused, jlong display, jlong window) { + Display * dpy = (Display *)(intptr_t)display; + Window w = (Window) window; + XWindowAttributes xwa; + jlong r = 0; // undefinded + + if(NULL==dpy) { + NativewindowCommon_throwNewRuntimeException(env, "invalid display connection.."); + return 0; + } + + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 1); + memset(&xwa, 0, sizeof(XWindowAttributes)); + XGetWindowAttributes(dpy, w, &xwa); + if(NULL != xwa.visual) { + r = (jint) XVisualIDFromVisual( xwa.visual ); + } else { + r = 0; + } + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); + + return r; +} + + +JNIEXPORT jint JNICALL Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, jlong display, jint screen) { jlong r; if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - x11ErrorHandlerEnable((Display *) (intptr_t) display, 1, env); - r = (jlong) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); - x11ErrorHandlerEnable((Display *) (intptr_t) display, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 1, errorHandlerQuiet, 0); + r = (jint) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, errorHandlerQuiet, 0); return r; } @@ -411,23 +431,68 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - x11ErrorHandlerEnable((Display *) (intptr_t) display, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 1, errorHandlerQuiet, 0); _res = XCloseDisplay((Display *) (intptr_t) display); - x11ErrorHandlerEnable(NULL, 0, env); + // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, errorHandlerQuiet, 0); return _res; } +static void NativewindowX11_setNormalWindowEWMH (Display *dpy, Window w) { + Atom _NET_WM_WINDOW_TYPE = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE", False ); + Atom types[1]={0}; + types[0] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False ); + XChangeProperty( dpy, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *)&types, 1); + XSync(dpy, False); +} + +#define DECOR_USE_MWM 1 // works for known WMs +// #define DECOR_USE_EWMH 1 // haven't seen this to work (NORMAL->POPUP, never gets undecorated) + +/* see <http://tonyobryan.com/index.php?article=9> */ +#define MWM_HINTS_DECORATIONS (1L << 1) +#define PROP_MWM_HINTS_ELEMENTS 5 + +static void NativewindowX11_setDecorations (Display *dpy, Window w, Bool decorated) { + +#ifdef DECOR_USE_MWM + unsigned long mwmhints[PROP_MWM_HINTS_ELEMENTS] = { MWM_HINTS_DECORATIONS, 0, decorated, 0, 0 }; // flags, functions, decorations, input_mode, status + Atom _MOTIF_WM_HINTS = XInternAtom( dpy, "_MOTIF_WM_HINTS", False ); +#endif + +#ifdef DECOR_USE_EWMH + Atom _NET_WM_WINDOW_TYPE = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE", False ); + Atom types[3]={0}; + int ntypes=0; + if(True==decorated) { + types[ntypes++] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False ); + } else { + types[ntypes++] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False ); + } +#endif + +#ifdef DECOR_USE_MWM + XChangeProperty( dpy, w, _MOTIF_WM_HINTS, _MOTIF_WM_HINTS, 32, PropModeReplace, (unsigned char *)&mwmhints, PROP_MWM_HINTS_ELEMENTS); +#endif + +#ifdef DECOR_USE_EWMH + XChangeProperty( dpy, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *)&types, ntypes); +#endif + + XSync(dpy, False); +} + /* * Class: jogamp_nativewindow_x11_X11Lib - * Method: CreateDummyWindow - * Signature: (JIIII)J + * Method: CreateWindow + * Signature: (JJIIIIZZ)J */ -JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow - (JNIEnv *env, jclass unused, jlong display, jint screen_index, jint visualID, jint width, jint height) +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow + (JNIEnv *env, jclass unused, jlong parent, jlong display, jint screen_index, jint visualID, jint width, jint height, jboolean input, jboolean visible) { Display * dpy = (Display *)(intptr_t)display; int scrn_idx = (int)screen_index; - Window windowParent = 0; + Window root = RootWindow(dpy, scrn_idx); + Window windowParent = (Window) parent; Window window = 0; XVisualInfo visualTemplate; @@ -451,9 +516,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow return 0; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); + if(0==windowParent) { + windowParent = root; + } // try given VisualID on screen memset(&visualTemplate, 0, sizeof(XVisualInfo)); @@ -471,7 +539,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow if (visual==NULL) { - x11ErrorHandlerEnable(dpy, 0, env); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } @@ -481,9 +549,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow pVisualQuery=NULL; } - if(0==windowParent) { - windowParent = XRootWindowOfScreen(scrn); - } attrMask = ( CWBackingStore | CWBackingPlanes | CWBackingPixel | CWBackPixmap | CWBorderPixel | CWColormap | CWOverrideRedirect ) ; @@ -495,15 +560,22 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow xswa.backing_store=NotUseful; /* NotUseful, WhenMapped, Always */ xswa.backing_planes=0; /* planes to be preserved if possible */ xswa.backing_pixel=0; /* value to use in restoring planes */ + if( input ) { + xswa.event_mask = X11_MOUSE_EVENT_MASK; + xswa.event_mask |= KeyPressMask | KeyReleaseMask ; + } + if( visible ) { + xswa.event_mask |= FocusChangeMask | SubstructureNotifyMask | StructureNotifyMask | ExposureMask ; + } xswa.colormap = XCreateColormap(dpy, - XRootWindow(dpy, scrn_idx), + windowParent, visual, AllocNone); window = XCreateWindow(dpy, windowParent, - 0, 0, + 0, 0, // only a hint, WM most likely will override width, height, 0, // border width depth, @@ -511,13 +583,27 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow visual, attrMask, &xswa); + if(0==window) { + NativewindowCommon_throwNewRuntimeException(env, "could not create Window, bail out!"); + return 0; + } - XSync(dpy, False); + NativewindowX11_setNormalWindowEWMH(dpy, window); + NativewindowX11_setDecorations(dpy, window, False); + + if( visible ) { + XEvent event; + + XMapWindow(dpy, window); + } - XSelectInput(dpy, window, 0); // no events XSync(dpy, False); - x11ErrorHandlerEnable(dpy, 0, env); + if( !input ) { + XSelectInput(dpy, window, 0); // no events + } + + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); @@ -527,25 +613,57 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow /* * Class: jogamp_nativewindow_x11_X11Lib - * Method: DestroyDummyWindow + * Method: DestroyWindow * Signature: (JJ)V */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow +JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyWindow (JNIEnv *env, jclass unused, jlong display, jlong window) { Display * dpy = (Display *)(intptr_t)display; Window w = (Window) window; + XWindowAttributes xwa; if(NULL==dpy) { NativewindowCommon_throwNewRuntimeException(env, "invalid display connection.."); return; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); + XSync(dpy, False); + memset(&xwa, 0, sizeof(XWindowAttributes)); + XGetWindowAttributes(dpy, w, &xwa); // prefetch colormap to be destroyed after window destruction + XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); - x11ErrorHandlerEnable(dpy, 0, env); + if( None != xwa.colormap ) { + XFreeColormap(dpy, xwa.colormap); + } + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); +} + +JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_SetWindowPosSize + (JNIEnv *env, jclass unused, jlong display, jlong window, jint x, jint y, jint width, jint height) { + Display * dpy = (Display *)(intptr_t)display; + Window w = (Window) window; + XWindowChanges xwc; + int flags = 0; + + memset(&xwc, 0, sizeof(XWindowChanges)); + + if(0<=x && 0<=y) { + flags |= CWX | CWY; + xwc.x=x; + xwc.y=y; + } + + if(0<width && 0<height) { + flags |= CWWidth | CWHeight; + xwc.width=width; + xwc.height=height; + } + XConfigureWindow(dpy, w, flags, &xwc); + XSync(dpy, False); } /* @@ -569,11 +687,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio if( 0 == jdest_win ) { dest_win = root; } if( 0 == jsrc_win ) { src_win = root; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); res = XTranslateCoordinates(dpy, src_win, dest_win, src_x, src_y, &dest_x, &dest_y, &child); - x11ErrorHandlerEnable(dpy, 0, env); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 0); DBG_PRINT( "X11: GetRelativeLocation0: %p %d/%d -> %p %d/%d - ok: %d\n", (void*)src_win, src_x, src_y, (void*)dest_win, dest_x, dest_y, (int)res); @@ -581,3 +699,38 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio return (*env)->NewObject(env, pointClz, pointCstr, (jint)dest_x, (jint)dest_y); } +/* + * Class: jogamp_nativewindow_x11_X11Lib + * Method: QueryExtension0 + * Signature: (JLjava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_x11_X11Lib_QueryExtension0 + (JNIEnv *env, jclass unused, jlong jdisplay, jstring jextensionName) +{ + int32_t major_opcode, first_event, first_error; + jboolean res = JNI_FALSE; + Display * display = (Display *) (intptr_t) jdisplay; + const char* extensionName = NULL; + + if(NULL==display) { + NativewindowCommon_throwNewRuntimeException(env, "NULL argument \"display\""); + return res; + } + if ( NULL == jextensionName ) { + NativewindowCommon_throwNewRuntimeException(env, "NULL argument \"extensionName\""); + return res; + } + extensionName = (*env)->GetStringUTFChars(env, jextensionName, (jboolean*)NULL); + if ( NULL == extensionName ) { + NativewindowCommon_throwNewRuntimeException(env, "Failed to get UTF-8 chars for argument \"extensionName\""); + return res; + } + + res = True == XQueryExtension(display, extensionName, &major_opcode, &first_event, &first_error) ? JNI_TRUE : JNI_FALSE; + + if ( NULL != jextensionName ) { + (*env)->ReleaseStringUTFChars(env, jextensionName, extensionName); + } + return res; +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/native/x11/Xmisc.h index f2993abab..91f2ac5d9 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java +++ b/src/nativewindow/native/x11/Xmisc.h @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR @@ -20,55 +20,23 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ -package com.jogamp.nativewindow; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.SurfaceChangeable; - - -public class WrappedSurface extends ProxySurface implements SurfaceChangeable { - protected long surfaceHandle; - - public WrappedSurface(AbstractGraphicsConfiguration cfg) { - this(cfg, 0); - } - - public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle) { - super(cfg); - surfaceHandle=handle; - } - - protected final void invalidateImpl() { - surfaceHandle = 0; - } - - final public long getSurfaceHandle() { - return surfaceHandle; - } - - final public void setSurfaceHandle(long surfaceHandle) { - this.surfaceHandle=surfaceHandle; - } - - final protected int lockSurfaceImpl() { - return LOCK_SUCCESS; - } +#ifndef Xmisc_h +#define Xmisc_h - final protected void unlockSurfaceImpl() { - } +#include <jni.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <stdarg.h> +#include <unistd.h> +#include <errno.h> +#include <X11/Xlib.h> +#include <X11/Xutil.h> - public String toString() { - return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ - ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + - ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + - ", size " + getWidth() + "x" + getHeight() + - ", surfaceLock "+surfaceLock+"]"; - } -} +#endif /* Xmisc_h */ |