diff options
author | Sven Gothel <[email protected]> | 2010-04-15 03:44:12 +0200 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2010-04-15 03:44:12 +0200 |
commit | 2ae28d54858ff684bc2368e0476a7a357dc63432 (patch) | |
tree | 41524bc7be69f029d2b183128cc0c8b89ec4754c /src/nativewindow | |
parent | 2df3bea10859ee2f2c4b3622f3b610b17a5749d6 (diff) |
Further ATI (fglrx) X11Display bug workaround/cleanup
- See https://bugzilla.mozilla.org/show_bug.cgi?id=486277
- Calling XCloseDisplay occasionally leads to a SIGSEGV,
even thought the reference is valid and OK.
Workaround is not to close any X11Display,
but to hold them stashed and reuse them.
Since we already pipeline all X11Display's
via Nativewindow's X11Util, an added referenceCounter
and a global active/passive list solved this problem.
This workaround is only active in case 'isVendorATI()'.
NEWT/NativeWindow X11:
- Let XIOErrorHandler and invalid display references
fail hard with FatalError, otherwise we won't see
the stack trace - and those bugs are indeed fatal.
NativeWindow X11:
- Install XIOErrorHandler, which stays active.
- X11Util.X11Display:
- Add reference counter
- Add global active/passive list.
Passive if reference count == 0
and marked as 'un-closeable' (-> ATI).
Reusing passive members when create a new display.
-
JOGL:
- Use DeleteLocalRef() calls to free temp NIO buffer
in manual *Copied implementation.
- GLDrawableFactoryImpl: Be serious about the shutdown() semantics
- *GraphicsConfiguration:
- Fix the invalid Onscreen/PBuffer/Pixmap determination (X11/EGL/WGL)
- Just return null if not valid
- X11GLXGraphicsConfigurationFactory - FBConfig
- Determine recommendedIndex properly ..
- Don't bail out if a FBConfig is invalid ..
- Use Chooser in case nothing is recommended ..
- X11OffscreenGLXDrawable fixes bugs:
- wrong (int) cast of parent window in XCreatePixmap call
- setting display to zero too early in destruction, ie
before XCloseDisplay
- X11GLXDrawableFactory is using [singleton] shared dummy resources for
- Screen, Drawable and Context
which are utilized in case they are needed ..
They are removed at shutdown call
- GLXVersion gathering in GLXUtil now ..
- DefaultGLCapabilitiesChooser: Respect PBuffer selection
Tests:
- Add DrawableFactory shutdown()
- Add various Offscreen Capabilties
- Add Offscreen and non-pbuffer case
- JUnit Passed (Linux64bit: NVidia/ATI)
- demos.jrefract.JRefract passed (Linux64bit: NVidia/ATI)
Diffstat (limited to 'src/nativewindow')
3 files changed, 670 insertions, 31 deletions
diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/impl/x11/X11Util.java b/src/nativewindow/classes/com/jogamp/nativewindow/impl/x11/X11Util.java index 95fd6c72b..41ffccc42 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/impl/x11/X11Util.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/impl/x11/X11Util.java @@ -34,6 +34,9 @@ package com.jogamp.nativewindow.impl.x11; import java.util.HashMap; import java.util.Map; +import java.util.Collection; +import java.util.ArrayList; +import java.util.Iterator; import javax.media.nativewindow.*; @@ -41,7 +44,7 @@ import com.jogamp.nativewindow.impl.*; /** * Contains a thread safe X11 utility to retrieve thread local display connection,<br> - * as well as the static global discplay connection.<br> + * as well as the static global display connection.<br> * * The TLS variant is thread safe per se, but be aware of the memory leak risk * where an application heavily utilizing this class on temporary new threads.<br> @@ -51,27 +54,98 @@ public class X11Util { static { NativeLibLoaderBase.loadNativeWindow("x11"); + installIOErrorHandler(); } private X11Util() {} private static ThreadLocal currentDisplayMap = new ThreadLocal(); + // 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 Collection globalNamedDisplayActive = new ArrayList(); + private static Collection globalNamedDisplayPassive = new ArrayList(); + + public static final String nullDeviceName = "nil" ; + public static class NamedDisplay implements Cloneable { - private String name; - private long handle; + String name; + long handle; + int refCount; + boolean unCloseable; protected NamedDisplay(String name, long handle) { this.name=name; this.handle=handle; + this.refCount=1; + this.unCloseable=false; } - public String getName() { return name; } - public long getHandle() { return handle; } + public final String getName() { return name; } + public final String getNameSafe() { return null == name ? nullDeviceName : name; } + public final long getHandle() { return handle; } + public final int getRefCount() { return refCount; } + public final boolean isUncloseable() { return unCloseable; } public Object clone() throws CloneNotSupportedException { return super.clone(); } + + public String toString() { + return "NamedX11Display["+name+", 0x"+Long.toHexString(handle)+", refCount "+refCount+", unCloseable "+unCloseable+"]"; + } + } + + /** Returns the number of unclosed X11 Displays. + * @param realXClosePendingDisplays if true, call XCloseDisplay on the remaining ones + */ + public static int shutdown(boolean realXClosePendingDisplays, boolean verbose) { + int num=0; + String msg; + if(DEBUG||verbose) { + msg = "X11Util.Display: Shutdown (active: "+globalNamedDisplayActive.size()+ + ", passive: "+globalNamedDisplayPassive.size() + ")"; + if(DEBUG) { + Exception e = new Exception(msg); + e.printStackTrace(); + } else if(verbose) { + System.err.println(msg); + } + } + + msg = realXClosePendingDisplays ? "Close" : "Keep" ; + + synchronized(globalLock) { + // for all passive displays .. + Collection namedDisplays = globalNamedDisplayPassive; + globalNamedDisplayPassive = new ArrayList(); + for(Iterator iter=namedDisplays.iterator(); iter.hasNext(); ) { + NamedDisplay ndpy = (NamedDisplay)iter.next(); + if(DEBUG||verbose) { + System.err.println(msg+" passive: "+ndpy); + } + if(realXClosePendingDisplays) { + X11Lib.XCloseDisplay(ndpy.getHandle()); + } + num++; + } + + // for all active displays .. + namedDisplays = globalNamedDisplayActive; + globalNamedDisplayActive = new ArrayList(); + for(Iterator iter=namedDisplays.iterator(); iter.hasNext(); ) { + NamedDisplay ndpy = (NamedDisplay)iter.next(); + if(DEBUG||verbose) { + System.err.println(msg+" active: "+ndpy); + } + if(realXClosePendingDisplays) { + X11Lib.XCloseDisplay(ndpy.getHandle()); + } + num++; + } + } + return num; } /** Returns a clone of the thread local display map, you may {@link Object#wait()} on it */ @@ -79,48 +153,120 @@ public class X11Util { return (Map) ((HashMap)getCurrentDisplayMapImpl()).clone(); } - /** Returns this thread current default display. If it doesn not exist, it is being created */ - public static long getThreadLocalDefaultDisplay() { - return getThreadLocalDisplay(null); + /** Returns this thread current default display. If it doesn not exist, it is being created, otherwise the reference count is increased */ + public static long createThreadLocalDefaultDisplay() { + return createThreadLocalDisplay(null); } - /** Returns this thread named display. If it doesn not exist, it is being created */ - public static long getThreadLocalDisplay(String name) { + /** Returns this thread named display. If it doesn not exist, it is being created, otherwise the reference count is increased */ + public static long createThreadLocalDisplay(String name) { NamedDisplay namedDpy = getCurrentDisplay(name); if(null==namedDpy) { + synchronized(globalLock) { + namedDpy = getNamedDisplay(globalNamedDisplayPassive, name); + if(null != namedDpy) { + if(!globalNamedDisplayPassive.remove(namedDpy)) { throw new RuntimeException("Internal: "+namedDpy); } + globalNamedDisplayActive.add(namedDpy); + addCurrentDisplay( namedDpy ); + } + } + } + if(null==namedDpy) { long dpy = X11Lib.XOpenDisplay(name); if(0==dpy) { throw new NativeWindowException("X11Util.Display: Unable to create a display("+name+") connection in Thread "+Thread.currentThread().getName()); } namedDpy = new NamedDisplay(name, dpy); - setCurrentDisplay( namedDpy ); + synchronized(globalLock) { + globalNamedDisplayActive.add(namedDpy); + addCurrentDisplay( namedDpy ); + } if(DEBUG) { - Exception e = new Exception("X11Util.Display: Created new TLS display("+name+") connection 0x"+Long.toHexString(dpy)+" in thread "+Thread.currentThread().getName()); + Exception e = new Exception("X11Util.Display: Created new TLS "+namedDpy+" in thread "+Thread.currentThread().getName()); + e.printStackTrace(); + } + } else { + namedDpy.refCount++; + if(DEBUG) { + Exception e = new Exception("X11Util.Display: Reused TLS "+namedDpy+" in thread "+Thread.currentThread().getName()); e.printStackTrace(); } } return namedDpy.getHandle(); } - /** Closes this thread named display. It returns the handle of the closed display or 0, if it does not exist. */ + /** Decrease the reference count of this thread named display. If it reaches 0, close it. + It returns the handle of the to be closed display. + It throws a RuntimeException in case the named display does not exist, + or the reference count goes below 0. + */ public static long closeThreadLocalDisplay(String name) { - NamedDisplay namedDpy = removeCurrentDisplay(name); + NamedDisplay namedDpy = getCurrentDisplay(name); if(null==namedDpy) { + throw new RuntimeException("X11Util.Display: Display("+name+") with given handle is not mapped to TLS in thread "+Thread.currentThread().getName()); + } + if(0==namedDpy.refCount) { + throw new RuntimeException("X11Util.Display: "+namedDpy+" has refCount already 0 in thread "+Thread.currentThread().getName()); + } + long dpy = namedDpy.getHandle(); + namedDpy.refCount--; + if(0==namedDpy.refCount) { + synchronized(globalLock) { + if(!globalNamedDisplayActive.remove(namedDpy)) { throw new RuntimeException("Internal: "+namedDpy); } + if(namedDpy.isUncloseable()) { + globalNamedDisplayPassive.add(namedDpy); + } else { + X11Lib.XCloseDisplay(dpy); + } + removeCurrentDisplay(namedDpy); + } if(DEBUG) { - Exception e = new Exception("X11Util.Display: Display("+name+") with given handle is not mapped to TLS in thread "+Thread.currentThread().getName()); + String type = namedDpy.isUncloseable() ? "passive" : "real" ; + Exception e = new Exception("X11Util.Display: Closing ( "+type+" ) TLS "+namedDpy+" in thread "+Thread.currentThread().getName()); e.printStackTrace(); } - return 0; - } - long dpy = namedDpy.getHandle(); - if(DEBUG) { - Exception e = new Exception("X11Util.Display: Closing TLS Display("+name+") with handle 0x"+Long.toHexString(dpy)+" in thread "+Thread.currentThread().getName()); + } else if(DEBUG) { + Exception e = new Exception("X11Util.Display: Keep TLS "+namedDpy+" in thread "+Thread.currentThread().getName()); e.printStackTrace(); } - X11Lib.XCloseDisplay(dpy); return dpy; } + public static String getThreadLocalDisplayName(long handle) { + NamedDisplay ndpy = getNamedDisplay(getCurrentDisplayMapImpl().values(), handle); + return null != ndpy ? ndpy.getName() : null; + } + + public static boolean markThreadLocalDisplayUndeletable(long handle) { + NamedDisplay ndpy = getNamedDisplay(getCurrentDisplayMapImpl().values(), handle); + if( null != ndpy ) { + ndpy.unCloseable=true; + return true; + } + return false; + } + + public static String getGlobalDisplayName(long handle, boolean active) { + String name; + synchronized(globalLock) { + NamedDisplay ndpy = getNamedDisplay(active ? globalNamedDisplayActive : globalNamedDisplayPassive, handle); + name = null != ndpy ? ndpy.getName() : null; + } + return name; + } + + public static boolean markGlobalDisplayUndeletable(long handle) { + boolean r=false; + synchronized(globalLock) { + NamedDisplay ndpy = getNamedDisplay(globalNamedDisplayActive, handle); + if( null != ndpy ) { + ndpy.unCloseable=true; + r=true; + } + } + return r; + } + private static Map getCurrentDisplayMapImpl() { Map displayMap = (Map) currentDisplayMap.get(); if(null==displayMap) { @@ -132,12 +278,11 @@ public class X11Util { /** maps the given display to the thread local display map * and notifies all threads synchronized to this display map. */ - private static NamedDisplay setCurrentDisplay(NamedDisplay newDisplay) { + private static NamedDisplay addCurrentDisplay(NamedDisplay newDisplay) { Map displayMap = getCurrentDisplayMapImpl(); NamedDisplay oldDisplay = null; synchronized(displayMap) { - String name = (null==newDisplay.getName())?"nil":newDisplay.getName(); - oldDisplay = (NamedDisplay) displayMap.put(name, newDisplay); + oldDisplay = (NamedDisplay) displayMap.put(newDisplay.getNameSafe(), newDisplay); displayMap.notifyAll(); } return oldDisplay; @@ -145,22 +290,45 @@ public class X11Util { /** removes the mapping of the given name from the thread local display map * and notifies all threads synchronized to this display map. */ - private static NamedDisplay removeCurrentDisplay(String name) { + private static NamedDisplay removeCurrentDisplay(NamedDisplay ndpy) { Map displayMap = getCurrentDisplayMapImpl(); - NamedDisplay oldDisplay = null; synchronized(displayMap) { - if(null==name) name="nil"; - oldDisplay = (NamedDisplay) displayMap.remove(name); + NamedDisplay ndpyDel = (NamedDisplay) displayMap.remove(ndpy.getNameSafe()); + if(ndpyDel!=ndpy) { + throw new RuntimeException("Wrong mapping req: "+ndpy+", got "+ndpyDel); + } displayMap.notifyAll(); } - return oldDisplay; + return ndpy; } /** Returns the thread local display mapped to the given name */ private static NamedDisplay getCurrentDisplay(String name) { - if(null==name) name="nil"; + if(null==name) name=nullDeviceName; Map displayMap = getCurrentDisplayMapImpl(); return (NamedDisplay) displayMap.get(name); } + private static NamedDisplay getNamedDisplay(Collection namedDisplays, String name) { + if(null==name) name=nullDeviceName; + for(Iterator iter=namedDisplays.iterator(); iter.hasNext(); ) { + NamedDisplay ndpy = (NamedDisplay)iter.next(); + if (ndpy.getNameSafe().equals(name)) { + return ndpy; + } + } + return null; + } + + private static NamedDisplay getNamedDisplay(Collection namedDisplays, long handle) { + for(Iterator iter=namedDisplays.iterator(); iter.hasNext(); ) { + NamedDisplay ndpy = (NamedDisplay)iter.next(); + if (ndpy.getHandle()==handle) { + return ndpy; + } + } + return null; + } + + private static native void installIOErrorHandler(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java index 52f48660a..69ace3c52 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java @@ -57,7 +57,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl /** Creates a new X11GraphicsScreen using a thread local display connection */ public static AbstractGraphicsScreen createDefault() { NativeWindowFactory.getDefaultFactory().getToolkitLock().lock(); - long display = X11Util.getThreadLocalDefaultDisplay(); + long display = X11Util.createThreadLocalDefaultDisplay(); try { X11Lib.XLockDisplay(display); int scrnIdx = X11Lib.DefaultScreen(display); diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c new file mode 100644 index 000000000..4320a8f12 --- /dev/null +++ b/src/nativewindow/native/x11/Xmisc.c @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2010 Sven Gothel. 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 Sven Gothel 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 + * SVEN GOTHEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + */ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <stdarg.h> +#include <unistd.h> +#include <X11/Xlib.h> +#include <X11/Xutil.h> +/* Linux headers don't work properly */ +#define __USE_GNU +#include <dlfcn.h> +#undef __USE_GNU + +/* Current versions of Solaris don't expose the XF86 extensions, + although with the recent transition to Xorg this will probably + happen in an upcoming release */ +#if !defined(__sun) && !defined(_HPUX) +#include <X11/extensions/xf86vmode.h> +#else +/* Need to provide stubs for these */ +Bool XF86VidModeGetGammaRampSize( + Display *display, + int screen, + int* size) +{ + return False; +} + +Bool XF86VidModeGetGammaRamp( + Display *display, + int screen, + int size, + unsigned short *red_array, + unsigned short *green_array, + unsigned short *blue_array) { + return False; +} +Bool XF86VidModeSetGammaRamp( + Display *display, + int screen, + int size, + unsigned short *red_array, + unsigned short *green_array, + unsigned short *blue_array) { + return False; +} +#endif /* defined(__sun) || defined(_HPUX) */ + +/* HP-UX doesn't define RTLD_DEFAULT. */ +#if defined(_HPUX) && !defined(RTLD_DEFAULT) +#define RTLD_DEFAULT NULL +#endif + +#include "com_jogamp_nativewindow_impl_x11_X11Lib.h" + +// #define VERBOSE_ON 1 + +#ifdef VERBOSE_ON + // Workaround for ancient compiler on Solaris/SPARC + // #define DBG_PRINT(args...) fprintf(stderr, args); + #define DBG_PRINT0(str) fprintf(stderr, str); + #define DBG_PRINT1(str, arg1) fprintf(stderr, str, arg1); + #define DBG_PRINT2(str, arg1, arg2) fprintf(stderr, str, arg1, arg2); + #define DBG_PRINT3(str, arg1, arg2, arg3) fprintf(stderr, str, arg1, arg2, arg3); + #define DBG_PRINT4(str, arg1, arg2, arg3, arg4) fprintf(stderr, str, arg1, arg2, arg3, arg4); + #define DBG_PRINT5(str, arg1, arg2, arg3, arg4, arg5) fprintf(stderr, str, arg1, arg2, arg3, arg4, arg5); + #define DBG_PRINT6(str, arg1, arg2, arg3, arg4, arg5, arg6) fprintf(stderr, str, arg1, arg2, arg3, arg4, arg5, arg6); + #define DBG_PRINT7(str, arg1, arg2, arg3, arg4, arg5, arg6, arg7) fprintf(stderr, str, arg1, arg2, arg3, arg4, arg5, arg6, arg7); + #define DBG_PRINT8(str, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) fprintf(stderr, str, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); + +#else + + // Workaround for ancient compiler on Solaris/SPARC + // #define DBG_PRINT(args...) + #define DBG_PRINT0(str) + #define DBG_PRINT1(str, arg1) + #define DBG_PRINT2(str, arg1, arg2) + #define DBG_PRINT3(str, arg1, arg2, arg3) + #define DBG_PRINT4(str, arg1, arg2, arg3, arg4) + #define DBG_PRINT5(str, arg1, arg2, arg3, arg4, arg5) + #define DBG_PRINT6(str, arg1, arg2, arg3, arg4, arg5, arg6) + #define DBG_PRINT7(str, arg1, arg2, arg3, arg4, arg5, arg6, arg7) + #define DBG_PRINT8(str, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) + +#endif + +/* Need to pull this in as we don't have a stub header for it */ +extern Bool XineramaEnabled(Display* display); + +static void _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); + + fprintf(stderr, buffer); + (*env)->FatalError(env, buffer); +} + +static const char * const ClazzNameInternalBufferUtil = "com/jogamp/nativewindow/impl/InternalBufferUtil"; +static const char * const ClazzNameInternalBufferUtilStaticCstrName = "copyByteBuffer"; +static const char * const ClazzNameInternalBufferUtilStaticCstrSignature = "(Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;"; +static const char * const ClazzNameByteBuffer = "java/nio/ByteBuffer"; +static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; +static jclass clazzInternalBufferUtil = NULL; +static jmethodID cstrInternalBufferUtil = NULL; +static jclass clazzByteBuffer = NULL; +static jclass clazzRuntimeException=NULL; + +static void _initClazzAccess(JNIEnv *env) { + jclass c; + + if(NULL!=clazzRuntimeException) return ; + + c = (*env)->FindClass(env, ClazzNameRuntimeException); + if(NULL==c) { + _FatalError(env, "Nativewindow X11Lib: can't find %s", ClazzNameRuntimeException); + } + clazzRuntimeException = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==clazzRuntimeException) { + _FatalError(env, "FatalError: NEWT X11Window: can't use %s", ClazzNameRuntimeException); + } + + c = (*env)->FindClass(env, ClazzNameInternalBufferUtil); + if(NULL==c) { + _FatalError(env, "FatalError: Java_com_jogamp_nativewindow_impl_x11_X11Lib: can't find %s", ClazzNameInternalBufferUtil); + } + clazzInternalBufferUtil = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==clazzInternalBufferUtil) { + _FatalError(env, "FatalError: Java_com_jogamp_nativewindow_impl_x11_X11Lib: can't use %s", ClazzNameInternalBufferUtil); + } + c = (*env)->FindClass(env, ClazzNameByteBuffer); + if(NULL==c) { + _FatalError(env, "FatalError: Java_com_jogamp_nativewindow_impl_x11_X11Lib: can't find %s", ClazzNameByteBuffer); + } + clazzByteBuffer = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==c) { + _FatalError(env, "FatalError: Java_com_jogamp_nativewindow_impl_x11_X11Lib: can't use %s", ClazzNameByteBuffer); + } + + cstrInternalBufferUtil = (*env)->GetStaticMethodID(env, clazzInternalBufferUtil, + ClazzNameInternalBufferUtilStaticCstrName, ClazzNameInternalBufferUtilStaticCstrSignature); + if(NULL==cstrInternalBufferUtil) { + _FatalError(env, "FatalError: Java_com_jogamp_nativewindow_impl_x11_X11Lib:: can't create %s.%s %s", + ClazzNameInternalBufferUtil, ClazzNameInternalBufferUtilStaticCstrName, ClazzNameInternalBufferUtilStaticCstrSignature); + } +} + +static void _throwNewRuntimeException(Display * unlockDisplay, JNIEnv *env, const char* msg, ...) +{ + char buffer[512]; + va_list ap; + + if(NULL!=unlockDisplay) { + XUnlockDisplay(unlockDisplay); + } + + _initClazzAccess(env); + + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); + + (*env)->ThrowNew(env, clazzRuntimeException, buffer); +} + +static XIOErrorHandler origIOErrorHandler = NULL; +static JNIEnv * displayIOErrorHandlerJNIEnv = NULL; + +static int displayIOErrorHandler(Display *dpy) +{ + _FatalError(displayIOErrorHandlerJNIEnv, "Nativewindow X11 IOError: Display %p not available", dpy); + origIOErrorHandler(dpy); + return 0; +} + +static void displayIOErrorHandlerEnable(int onoff, JNIEnv * env) { + if(onoff) { + if(NULL==origIOErrorHandler) { + displayIOErrorHandlerJNIEnv = env; + origIOErrorHandler = XSetIOErrorHandler(displayIOErrorHandler); + } + } else { + XSetIOErrorHandler(origIOErrorHandler); + origIOErrorHandler = NULL; + displayIOErrorHandlerJNIEnv = NULL; + } +} + +JNIEXPORT void JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Util_installIOErrorHandler(JNIEnv *env, jclass _unused) { + displayIOErrorHandlerEnable(1, env); +} + +JNIEXPORT jlong JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_dlopen(JNIEnv *env, jclass _unused, jstring name) { + const jbyte* chars; + void* res; + chars = (*env)->GetStringUTFChars(env, name, NULL); + res = dlopen(chars, RTLD_LAZY | RTLD_GLOBAL); + (*env)->ReleaseStringUTFChars(env, name, chars); + return (jlong) ((intptr_t) res); +} + +JNIEXPORT jlong JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_dlsym(JNIEnv *env, jclass _unused, jstring name) { + const jbyte* chars; + void* res; + chars = (*env)->GetStringUTFChars(env, name, NULL); + res = dlsym(RTLD_DEFAULT, chars); + (*env)->ReleaseStringUTFChars(env, name, chars); + return (jlong) ((intptr_t) res); +} + +/* Java->C glue code: + * Java package: com.jogamp.nativewindow.impl.x11.X11Lib + * Java method: XVisualInfo XGetVisualInfo(long arg0, long arg1, XVisualInfo arg2, java.nio.IntBuffer arg3) + * C function: XVisualInfo * XGetVisualInfo(Display * , long, XVisualInfo * , int * ); + */ +JNIEXPORT jobject JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_XGetVisualInfoCopied1__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) { + _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); + } + _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); + count = _ptr3[0]; + if (arg3 != NULL) { + (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); + } + if (_res == NULL) return NULL; + + _initClazzAccess(env); + + jbyteSource = (*env)->NewDirectByteBuffer(env, _res, count * sizeof(XVisualInfo)); + jbyteCopy = (*env)->CallStaticObjectMethod(env, + clazzInternalBufferUtil, cstrInternalBufferUtil, jbyteSource); + + XFree(_res); + + return jbyteCopy; +} + +JNIEXPORT jlong JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, jlong display, jint screen) { + jlong r; + if(0==display) { + _FatalError(env, "invalid display connection.."); + } + r = (jlong) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); + return r; +} + +/* Java->C glue code: + * Java package: com.jogamp.nativewindow.impl.x11.X11Lib + * Java method: void XLockDisplay(long display) + * C function: void XLockDisplay(Display * display); + */ +JNIEXPORT void JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_XLockDisplay__J(JNIEnv *env, jclass _unused, jlong display) { + if(0==display) { + _FatalError(env, "invalid display connection.."); + } + XLockDisplay((Display *) (intptr_t) display); +} + +/* Java->C glue code: + * Java package: com.jogamp.nativewindow.impl.x11.X11Lib + * Java method: void XUnlockDisplay(long display) + * C function: void XUnlockDisplay(Display * display); + */ +JNIEXPORT void JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_XUnlockDisplay__J(JNIEnv *env, jclass _unused, jlong display) { + if(0==display) { + _FatalError(env, "invalid display connection.."); + } + XUnlockDisplay((Display *) (intptr_t) display); +} + + +/* Java->C glue code: + * Java package: com.jogamp.nativewindow.impl.x11.X11Lib + * Java method: int XCloseDisplay(long display) + * C function: int XCloseDisplay(Display * display); + */ +JNIEXPORT jint JNICALL +Java_com_jogamp_nativewindow_impl_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused, jlong display) { + int _res; + if(0==display) { + _FatalError(env, "invalid display connection.."); + } + _res = XCloseDisplay((Display *) (intptr_t) display); + return _res; +} + +/* + * Class: com_jogamp_nativewindow_impl_x11_X11Lib + * Method: CreateDummyWindow + * Signature: (JIJ)J +JNIEXPORT jlong JNICALL Java_com_jogamp_nativewindow_impl_x11_X11Lib_CreateDummyWindow + (JNIEnv *env, jobject obj, jlong display, jint screen_index, jlong visualID) +{ + Display * dpy = (Display *)(intptr_t)display; + int scrn_idx = (int)screen_index; + Window windowParent = 0; + Window window = 0; + + XVisualInfo visualTemplate; + XVisualInfo *pVisualQuery = NULL; + Visual *visual = NULL; + int depth; + + XSetWindowAttributes xswa; + unsigned long attrMask; + int n; + + Screen* scrn; + + if(NULL==dpy) { + _FatalError(env, "invalid display connection.."); + return 0; + } + + if(visualID<0) { + _throwNewRuntimeException(NULL, env, "invalid VisualID ..\n"); + return 0; + } + + XLockDisplay(dpy) ; + + XSync(dpy, False); + + scrn = ScreenOfDisplay(dpy, scrn_idx); + + // try given VisualID on screen + memset(&visualTemplate, 0, sizeof(XVisualInfo)); + visualTemplate.screen = scrn_idx; + visualTemplate.visualid = (VisualID)visualID; + pVisualQuery = XGetVisualInfo(dpy, VisualIDMask|VisualScreenMask, &visualTemplate,&n); + if(pVisualQuery!=NULL) { + visual = pVisualQuery->visual; + depth = pVisualQuery->depth; + visualID = (jlong)pVisualQuery->visualid; + XFree(pVisualQuery); + pVisualQuery=NULL; + } + DBG_PRINT5( "X11: [CreateWindow] trying given (dpy %p, screen %d, visualID: %d, parent %p) found: %p\n", dpy, scrn_idx, (int)visualID, windowParent, visual); + + if (visual==NULL) + { + _throwNewRuntimeException(dpy, env, "could not query Visual by given VisualID, bail out!\n"); + return 0; + } + + if(pVisualQuery!=NULL) { + XFree(pVisualQuery); + pVisualQuery=NULL; + } + + if(0==windowParent) { + windowParent = XRootWindowOfScreen(scrn); + } + + attrMask = (CWBackPixel | CWBorderPixel | CWColormap | CWOverrideRedirect) ; + + memset(&xswa, 0, sizeof(xswa)); + xswa.override_redirect = True; // not decorated + xswa.border_pixel = 0; + xswa.background_pixel = 0; + xswa.event_mask = 0 ; // no events + xswa.colormap = XCreateColormap(dpy, + XRootWindow(dpy, scrn_idx), + visual, + AllocNone); + + window = XCreateWindow(dpy, + windowParent, + 0, 0, + 64, 64, + 0, // border width + depth, + InputOutput, + visual, + attrMask, + &xswa); + + XSync(dpy, False); + + XUnlockDisplay(dpy) ; + + DBG_PRINT2( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); + + return (jlong) window; +} + */ + + +/* + * Class: com_jogamp_nativewindow_impl_x11_X11Lib + * Method: DestroyDummyWindow + * Signature: (JJ)V +JNIEXPORT void JNICALL Java_com_jogamp_nativewindow_impl_x11_X11Lib_DestroyDummyWindow + (JNIEnv *env, jobject obj, jlong display, jlong window) +{ + Display * dpy = (Display *)(intptr_t)display; + Window w = (Window) window; + + if(NULL==dpy) { + _throwNewRuntimeException(NULL, env, "invalid display connection..\n"); + return; + } + XLockDisplay(dpy) ; + + XSync(dpy, False); + XUnmapWindow(dpy, w); + XSync(dpy, False); + XDestroyWindow(dpy, w); + XSync(dpy, False); + + XUnlockDisplay(dpy) ; +} + */ + |